SlideShare ist ein Scribd-Unternehmen logo
1 von 100
Programming in java
Section-I
1. Introduction (6 hrs)
2. Applet as java application (2 hrs)
3. Multithreaded programming (4 hrs)
4. AWT and Java Input Output (8 hrs)
Section-II
1. Introduction to Swing (5 hrs)
2. Networking with Java (5 hrs)
3. JDBC (6 hrs)
4. RMI (4 hrs)
1. Introduction
Brief history of Java
Java Version History
Features of Java
Objects and classes
Inheritance
Abstract classes
Interface
Use of final Keyword
Use of String functions
Packages
Exception handling
Brief history of Java
 History of java starts from Green Team
 James Gosling, Mike Sheridan, and Patrick Naughton Green
Team initiated the Java language project in June 1991
 Originally designed for small, embedded systems in
electronic appliances
 Earlier it was called Oak and developed as a part of the
Green project
 Oak is a symbol of strength and choosen as a national tree
of many countries like U.S.A
 In 1995, Oak was renamed as "Java" because it was already
a trademark by Oak Technologies
Why Java name for java language?
 Java is an island of Indonesia where first coffee was
produced (called java coffee)
 Java is just a name not an acronym
 Originally developed by James Gosling at Sun
Microsystems and released in 1995.
 JDK 1.0 released in (January 23, 1996)
<BACK>
Java Version History
Java versions:
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (1996)
3. JDK 1.1 (1997)
4. J2SE 1.2 (1998)
5. J2SE 1.3 (2000)
6. J2SE 1.4 (2002)
7. J2SE 5.0 (2004)
8. Java SE 6 (2006)
9. Java SE 7 (2011)
10. Java SE 8 (18th March, 2014) Current stable release
of Java
Features of Java
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
1. Syntax is based on C++
2. Removed many confusing features e.g. explicit
pointers, operator overloading etc
3. Automatic Garbage Collection in java
Simple
Object-Oriented
Object-oriented means organize software as combination of
different types of objects that incorporate both data and
behavior
Basic concepts of OOPs are:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Platform independent
A platform is hardware or software environment in which a
program runs
Java provides software-based platform
 Runtime Environment
 API(Application Programming Interface)
Java code is compiled by the compiler and converted into
bytecode.
Bytecode is a platform independent code because it can be run
on multiple platforms i.e. Write Once and Run
Anywhere(WORA).
Platform independent (Cont..)
Java is secured because :
No explicit pointer
Programs run inside virtual machine sandbox
Secured
1. Robust means strong.
2. Java uses strong memory management.
3. Lack of pointers that avoids security problem.
4. Automatic garbage collection.
5. Exception handling and type checking mechanism.
All these makes java robust.
No implementation dependent features e.g. size of primitive
types is set
Architecture neutral
Robust
Portable
Allow to carry the java bytecode to any platform
Dynamic
Java is capable of dynamically linking new class libraries,
methods and objects.
Determines the class through query, making possible to link
dynamically
Interpreted
Java interpreter generates machine code that can be directly by
the machine with the help of JVM
High Performance
Java is faster than traditional interpretation since byte code is
"close" to native code still somewhat slower than a compiled
language (e.g., C++)
Multithreaded
Java allow to handle multiple tasks simultaneously. Java supports
multithreaded programs
Distributed
We can create distributed applications in java.
RMI and EJB are used for creating distributed applications.
We may access files by calling the methods from any machine
on the internet
<BACK>
Data Types in Java
1. Primitive data types
2. Non-primitive data types
Data Type Default Value Default size
boolean false 1 bit
char 'u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Operators in java
Operator is a symbol that is used to perform operations.
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>=>>>=
Objects and classes
Object in Java
An entity that has state and behavior is known as an object.
It can be physical or logical.
Object is an instance of a class.
Instance variable in Java
A variable that is created inside the class but outside the
method, is known as instance variable. Instance variable
doesn't get memory at compile time.
 State: Represents data (value) of an object.
 Behavior: Represents the behavior (functionality) of an
object e.g. deposit, withdraw etc.
 Identity: Object identity is a unique ID. JVM use ID to
identify each object uniquely
Object Properties
Class in Java
Class is a template or blueprint from which objects are created.
A class is a group of objects that has common properties
A class contains :
1. Data member
2. Method
3. Constructor
4. Block
5. Class and interface
Syntax to declare a class:
class <class_name>
{
data member;
method;
}
Example of Object and Class
class Student {
int id; String name; //data member (also instance variable)
public static void main(String args[])
{ Student s1 = new Student(); //creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
class Student {
int rollno;
String name;
void insertRecord (int r, String n) { rollno = r; name = n; }
void displayRecord() {System.out.println(rollno+" "+name);}
public static void main(String args[]){
Student s1 = new Student();
Student s2 = new Student();
s1.insertRecord(111,"Amit");
s2.insertRecord(222,"Ajay");
s1.displayRecord ();
s2.displayRecord ();
}
}
<BACK>
class Rectangle {
int length; int width;
void insert(int l,int w) { length=l; width=w; }
void calculateArea() { System.out.println(length*width); }
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
r1.insert(11,5); r2.insert(3,15);
r1.calculateArea(); r2.calculateArea();
}
}
Method Overloading in Java
If a class have multiple methods with same name but different
parameters, it is known as Method Overloading.
Different ways to overload the method
1. By changing the no. of arguments
2. By changing the data type
Method overloading increases the readability of the program.
Can we overload the main method?
Method Overloading by changing the no. of arguments
class Myclass{
void sum(int a, int b) { System.out.println(a+b);}
void sum(int a, int b, int c) { System.out.println(a+b+c); }
public static void main(String args[]) {
Myclass obj =new Myclass();
obj.sum(10, 10, 10);
obj.sum(20, 20);
}
}
Method Overloading by changing data type of an argument
class Myclass{
void sum(int a, int b) { System.out.println(a+b); }
void sum(double a, double b) { System.out.println(a+b); }
public static void main(String args[]) {
Myclass obj = new Myclass();
obj.sum(10.5, 10.5);
obj.sum(20, 20);
}
}
Method Overloading and Type Promotion
One type is promoted to another implicitly if no matching
data type is found as in figure given below;
As displayed in the diagram, byte can be promoted to
short, int, long, float or double.
Method Overloading and Type Promotion (cont…)
class Myclass {
void sum(int a, long b) { System.out.println(a+b); }
void sum(int a, int b, int c) { System.out.println(a+b+c); }
public static void main(String args[]) {
Myclass obj =new Myclass();
obj.sum(20, 20); //now second int literal will be promoted to long
obj.sum(20, 20, 20);
}
}
Output: 40
60
Constructor in Java
Types of constructors
1. Default Constructor
2. Parameterized Constructor
Constructor Overloading
Does constructor return any value
Does constructor perform other task instead initialization
Rules to define the constructor
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Constructor is a special type of method that is used to
initialize the object
Default Constructor
A constructor that has no parameter is known as default
constructor.
Syntax of default constructor:
<class_name>() { }
Example of default constructor
class Bike {
Bike() {System.out.println("Bike is created");}
public static void main(String args[])
{ Bike b=new Bike(); }
}
Output: Bike is created
Parameterized constructor
A constructor that has parameters is known as parameterized
constructor
Example of parameterized constructor
class Student {
int id; String name;
Student(int i, String n) { id = i; name = n; }
void display() {System.out.println(id+" "+name);}
public static void main(String args[]) {
Student s1 = new Student(111,“Vijay");
Student s2 = new Student(222,“Ajay");
s1.display(); s2.display();
}
Output: 111 Vijay 222 Ajay
No copy constructor in java
We can copy the values of one object to another like copy
constructor in C++.
Ways to copy the values of one object into another in java.
1. By constructor
2. By assigning the values of one object into another
Copy the values of one object into another using constructor
class Student {
int id; String name;
Student(int i,String n) { id = i; name = n; }
Student(Student s) { id = s.id; name =s.name; }
void display() {System.out.println(id+" "+name); }
public static void main(String args[]) {
Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display(); s2.display();
} }
Output: 111 Karan
111 Karan
Copying values without constructor
class Student {
int id; String name;
Student(int i,String n) { id = i; name = n; }
Student(Student s) { id = s.id; name =s.name; }
void display() {System.out.println(id+" "+name);}
public static void main(String args[]) {
Student s1 = new Student(111,"Karan");
Student s2 = new Student();
s2.id = s1.id; s2.name = s1.name;
s1.display(); s2.display();
} }
Output: 111 Karan 111 Karan
Constructor Overloading
Constructor overloading is a technique in which a class can
have any number of constructors that differ in parameter lists.
class Student {
int id; String name; int age;
Student(int i, String n) { id = i; name = n; }
Student(int i, String n, int a) { id = i; name = n; age=a; }
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]) {
Student s1 = new Student(111,“Ajay");
Student s2 = new Student(222,“Vijay",25);
s1.display(); s2.display(); }
}
Output: 111 Ajay 0 222 Vijay 25
static keyword
1. The static keyword is used for memory management
mainly.
2. We can apply static keyword with variables, methods,
blocks and nested class.
3. The static keyword belongs to the class than instance of the
class.
The static keyword can be used with:
1. class variable
2. class method
static variable and method
1. The static variable can be used to refer the common property of all
objects.
2. The static variable gets memory only once in class area at the time of
class loading.
Example of static variable
1. class Student {
2. int rollno; String name;
3. static String college =“sscs";
4. Student(int r, String n) { rollno = r; name = n; }
5. void display () {System.out.println(rollno+" "+name+" "+college); }
6. public static void main(String args[]){
7. Student s1 = new Student(111, “Vijay");
8. Student s2 = new Student(222, “Ajay");
9. s1.display(); s2.display();
10. } }
this keyword
Usages of this keyword.
1. to refer current class instance variable.
2. to return the current class instance.
3. to invoke current class method (implicitly)
4. this can be used to invoked current class constructor
5. can be passed as an argument in the method call
If there is ambiguity between the instance variable and
parameter, this keyword resolves the problem of ambiguity
1. class Student{
2. int id; String name;
3. Student(int id, String name){
4. this.id = id; this.name = name;
5. }
6. void display(){System.out.println(id+" "+name);}
7. public static void main(String args[]){
8. Student s1 = new Student(111,“Vijay");
9. Student s2 = new Student(222,“Ajay");
10. s1.display();
11. s2.display();
12. }
13. }
Output: 111 Vijay
222 Ajay
Refer current class instance variable
Program of this() constructor call (constructor chaining)
1. class Student {
2. int id; String name;
3. Student() {System.out.println("default constructor is invoked");}
4. Student(int id, String name) {
5. this (); //it is used to invoked current class constructor.
6. this.id = id; this.name = name;
7. }
8. void display() {System.out.println(id+" "+name);}
9. public static void main(String args[]){
10. Student e1 = new Student(111,“Vijay");
11. Student e2 = new Student(222,“Ajay");
12. e1.display(); e2.display();
13. } }
Output: default constructor is invoked
default constructor is invoked
111 Vijay 222 Ajay
1. class Student {
2. int id; String name; String city;
3. Student(int id,String name) {
4. this.id = id; this.name = name;
5. }
6. Student(int id, String name, String city) {
7. this(id, name); //now no need to initialize id and name
8. this.city=city;
9. }
10. void display() {System.out.println(id+" "+name+" "+city);}
11. public static void main(String args[])
{ Student e1 = new Student(111,"karan");
12. Student e2 = new Student(222,"Aryan","delhi");
13. e1.display();
14. e2.display(); }
15. }
Invoke current class constructor
this use to invoke current class method
1. class S {
2. void m() { System.out.println("method is invoked"); }
3. void n() { this.m(); //no need because compiler does it for you. }
4. void p() { n(); }
//complier will add this to invoke n() method as this.n()
5. public static void main(String args[])
6. { S s1 = new S();
7. s1.p();
8. }
9. }
this pass as an argument in the method
1. class S {
2. void m (S obj) { System.out.println("method is invoked"); }
3. void p(){ m(this); }
4. public static void main(String args[]){
5. S s1 = new S();
6. s1.p();
7. }
8. }
Output:method is invoked
this use to return current class instance
1. class A {
2. A getA() { return this; }
3. void msg() {System.out.println("Hello java");}
4. }
5.
6. class Test1 {
7. public static void main(String args[]) {
8. new A().getA().msg();
9. }
10. }
Program of counter by static variable
1. class Counter{
2. static int count=0;
//will get memory only once and retain its value
3. Counter () {
4. count++;
5. System.out.println(count); }
6. public static void main(String args[]){
7. Counter c1=new Counter2();
8. Counter c2=new Counter2();
9. Counter c3=new Counter2();
10. }
11. }
Output:1 2 3
static method
static keyword with any method, it is known as static method.
1. A static method belongs to the class rather than object of a class.
2. A static method can be invoked without creating an instance of a class.
3. A static method can access static data member and can change the value
•class Student {
• int rollno; String name; static String college = "ITS";
• static void change() { college = "BBDIT"; }
• Student(int r, String n) { rollno = r; name = n; }
• void display (){System.out.println(rollno+" "+name+" "+college);}
• public static void main(String args[]){
• Student.change();
• Student s1 = new Student (111,"Karan");
• Student s2 = new Student (222,"Aryan");
• Student s3 = new Student (333,"Sonoo");
• s1.display(); s2.display(); s3.display();
• } }
Output: 111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT
Restrictions for the static method
The static method can not use non static data member or call
non-static method directly.
this and super cannot be used in static context.
Restrictions for static method
1. class A {
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
Output:Compile Time Error
static block
1. Is used to initialize the static data member.
2. It is executed before main method at the time of class
loading.
3. class A {
4. static{System.out.println("static block is invoked");}
5. public static void main(String args[]){
6. System.out.println("Hello main");
7. }
8. }
Output: static block is invoked
Hello main
Inheritance
Inheritance is a process in which one object acquires all properties
and behaviors of parent object.
When we inherit from an existing class, we can reuse methods and
fields of parent class, and add new methods and fields.
Inheritance represents the IS-A relationship or parent-child
relationship.
Inheritance allow :
 Method Overriding
 Code Reusability
<BACK>
Syntax of Inheritance
class Subclass-name extends Super class-name
{ //methods and fields }
The extends keyword indicates that we are making a new class that derives
from an existing class.
Relationship between two classes is Programmer IS-A Employee e.g.
Programmer is a type of Employee.
1. class Employee { float salary=50000; }
2. class Programmer extends Employee {
3. int bonus=10000;
4. public static void main(String args[]){
5. Programmer p=new Programmer();
6. System.out.println("Programmer salary is:"+p.salary);
7. System.out.println("Bonus of Programmer is:"+p.bonus
8. } }
Types of inheritance
There are three types of inheritance as :
1. Single
2. Multilevel and
3. Hierarchical
Multiple and hybrid inheritance is not supported through interface.
To reduce the complexity and simplify the language, multiple inheritance is
not supported in java.
Consider A, B and C are three classes. The C class inherits A and
B classes. If A and B classes have same method and we call it
from child class object.
class A { void msg() { System.out.println("Hello"); } }
class B { void msg() { System.out.println("Welcome");} }
class C extends A, B {
public Static void main(String args[]) {
C obj = new C();
obj.msg(); //Now which msg() method would be invoked?
}
}
<BACK>
Aggregation
If a class have an entity reference, it is known as Aggregation.
Aggregation represents HAS-A relationship.
Consider an Employee object contains information as id, name,
email id etc. It contains other object address, which contains
information as city, state, country, zip code etc. as below.
class Employee{
int id; String name;
Address address;//Address is a class
...
}
Aggregation is for Code Reusability.
Example of Aggregation
public class Address { String city, state, country;
public Address (String city, String state, String country) {
this.city = city; this.state = state; this.country = country; } }
public class Emp { int id; String name; Address address;
public Emp(int id, String name, Address address) {
this.id = id; this.name = name; this.address=address; }
void display() { System.out.println (id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country); }
public static void main(String[] args) {
Address address1 = new Address(“abc",“Sol","india");
Address address2 = new Address(“lmn",“Sol","india");
Emp e1 = new Emp(111, “Vijay", Solapur);
Emp e2 = new Emp(112, “Ajay", Pandharpur);
e1.display(); e2.display(); }
}
Method Overriding
Subclass (child class) has the same method as declared in the
parent class, it is known as method overriding.
Usage of Method Overriding
1. To provide specific implementation of a method that is
already provided by its super class.
2. For runtime polymorphism
Rules for Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent
class.
3. must be IS-A relationship (inheritance).
Example of method overriding
1. class Vehicle{
2. void run() { System.out.println("Vehicle runs"); }
3. }
4. class Bike extends Vehicle{
5. void run() { System.out.println(“Runs safely"); }
6.
7. public static void main(String args[]){
8. Bike obj = new Bike();
9. obj.run();
10. }
Difference between method Overloading and Overriding
Method Overloading Method Overriding
Used to increase the
readability of the program
Used to provide the specific
implementation of the method that is
already provided by its super class
Performed within a class. Occurs in two classes that have IS-A
relationship
In method overloading,
parameter must be different
In method overriding, parameter must be
same
super keyword
super keyword is a reference variable that is used to refer immediate
parent class object.
When we create the instance of subclass, an instance of parent class
is created implicitly i.e. referred by super reference variable
Usage of super Keyword
1. To refer immediate parent class instance variable
2. To invoke immediate parent class constructor
3. To invoke immediate parent class method
Example to use super():
1. class Vehicle {
2. Vehicle() { System.out.println("Vehicle is created");
3. myvehicle() { System.out.println(“My car”); }
4. }
5. class Bike extends Vehicle {
6. Bike() { super(); //will invoke parent class constructor
7. System.out.println("Bike is created"); }
8. public static void main(String args[]) {
9. Bike b=new Bike(); super.myvehicle(); }
10. }
Output: Vehicle is created Bike is created
My car
Use of final keyword
The final keyword is used to restrict the user. The final keyword can be
used in many case.
Final can be used with :
1. variable
2. method
3. Class
Is final method inherited ?
Can you declare a final constructor?
final variable
If we make any variable as final, we cannot change the value of
final variable.
Example:
1. class Bike {
2. final int speedlimit=90; //final variable
3. void run() { speedlimit=400; }
4. public static void main(String args[]) {
5. Bike obj = new Bike();
6. obj.run(); }
7. } //end of class
Output: Compile Time Error
final method
If we make any method as final, we cannot override it.
Example:
class Bike { final void run() { S.o.p("running");} }
class Honda extends Bike {
void run() { ystem.out.println(“Runs safely with 100kmph"); }
public static void main(String args[]) {
Honda hunk = new Honda();
hunk.run(); }
}
Output: Compile Time Error
final class
If we make class as final, we cannot extend it.
Example:
1. final class Bike {}
2. class Honda extends Bike {
3. void run()
4. { System.out.println("running safely with 100kmph"); }
5. public static void main(String args[]) {
6. Honda hunk= new Honda();
7. hunk.run();
8. }
9. }
Output: Compile Time Error
Is final method inherited? Yes, final method is inherited but can’t override.
Final parameter
If we declare any parameter as final, we can’t change the value of it.
1. class Bike {
2. int cube( final int n) {
3. n=n+2; //can't be changed as n is final
4. n*n*n; }
5. public static void main(String args[]) {
6. Bike b = new Bike();
7. b.cube(5);
8. }
9. }
Output: Compile Time Error
<BACK>
Abstract class
 Abstraction is a process of hiding implementation details and showing
only functionality.
 It shows only important things and hides the internal details.
e.g. sending sms
 Abstraction focus on what the object does instead of how it does it.
Abstract class
A class that is declared with abstract keyword, is known as abstract class.
It can have abstract and non-abstract methods (method with body).
Abstract class example:
abstract class A { … }
Abstract method
A method that is declared as abstract and does not have implementation
(body) is known as abstract method.
Abstract method example:
abstract void print(); //no implementation and is abstract
Program Example:
1. abstract class Bike { abstract void run(); }
2. class Honda extends Bike {
3. void run() {System.out.println("running safely..");}
4. public static void main(String args[]) {
5. Bike obj = new Honda4(); obj.run(); }
6. }
Output put : running safely..
Interface in Java
An interface is a frame of a class. It has static constants and abstract
methods only. Interface represents IS-A relationship.
Reasons to use interface:
1. To achieve fully abstraction.
2. Support the multiple inheritance.
3. Achieve loose coupling.
Interface data members are public,
static and final by default.
Methods are public and abstract.
A class extends another class, an interface extends another
interface but a class implements an interface
‘Printable’ interface have only one method, its implementation is
provided in the A class.
Example of interface
interface printable { void print(); }
1. class A implements printable {
2. public void print() { System.out.println("Hello"); }
3. public static void main(String args[]) {
4. A obj = new A(); obj.print();
5. }
6. }
Output: Hello
Multiple inheritance by interface
A class implements multiple interfaces or an interface extends multiple
interfaces known as multiple inheritance.
Multiple inheritance example
1. interface Printable { void print(); }
2.
3. interface Showable { void show(); }
4.
5. class A implements Printable, Showable {
6.
7. public void print() { System.out.println("Hello"); }
8. public void show() { System.out.println("Welcome"); }
9. public static void main(String args[]) {
10. A obj = new A();
11. obj.print();
12. obj.show();
13. }
14. }
Output: Hello
Welcome
Interface inheritance
A class implements interface but one interface extends another interface.
1. interface Printable { void print(); }
2. interface Showable extends Printable { void show(); }
3. class Testinterface implements Showable {
4. public void print() {System.out.println("Hello"); }
5. public void show() {System.out.println("Welcome"); }
6. public static void main(String args[]) {
7. Testinterface obj = new Testinterface();
8. obj.print(); obj.show();
9. }
10. }
Output : Hello
Welcome
An interface that have no member is known as marker or tagged interface.
Example: Serializable, Cloneable, Remote etc.
They are used to provide essential information to the JVM.
Java String
String is an object that represents sequence of characters. Java String is
immutable. An array of characters also works as string.
e.g. char[] ch = {'S', 'i', 'n', 'h', 'g', 'a', 'd' };
String s = new String(ch); is same as:
String s="Sinhgad";
There are two ways to create Strings.
As string literal : String s1="Welcome"; String s2="Welcome";
// s2 will not create new instance
By new keyword : String s = new String("Welcome");
//creates one object and one reference variable
JVM creates a new string object in heap memory and the literal "Welcome"
placed in the string constant pool. The variable 's' refer to the object in heap.
StringBuffer and StringBuilder classes are mutable.
Java String Cont …
String Example
1. public class StringExample {
2. public static void main(String args[]) {
3. String s1="java"; //creating string by java string literal
4. char ch[] = {'s','t','r','i','n','g','s'};
5. String s2 = new String(ch); //converting array to string
6. String s3 = new String(“sscs"); //creating by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }
11. }
java
strings
example
Java String Cont …
java.lang.String provides methods to perform operations on string values.
Sr. No. Method Description
1 char charAt(int index) returns char value for the index
2 int length() returns string length
3 String substring(int beginIndex) returns substring for given index
4 String substring(int beginIndex,
int endIndex)
returns substring for given begin
index and end index
5 boolean equals(Object another) checks the equality of string with
object
6 boolean isEmpty() checks if string is empty
7 String concat(String str) concatenates specified string
8 String replace(char old, char new) replaces all occurrences of specified
char value
Java String Cont …
Sr. No. Method Description
9 int indexOf(int ch) returns specified char value index
10 int indexOf(String substring) returns specified substring index
11 String toLowerCase() returns string in lowercase.
12 String toUpperCase() returns string in uppercase.
13 String split(String regex, int
limit)
returns splitted string matching
regex and limit
14 String trim() returns trimmed string omitting
leading and trailing spaces
Java String Cont …
Immutable String
String objects are immutable means unmodifiable or unchangeable.
An example:
1. class Timmutablestring {
2. public static void main(String args[]) {
3. String s="Sinhgad";
4. s.concat("Institute");
//concat() method appends the string at the end
5. System.out.println(s);
6. //will print Sinhgad because strings are immutable objects
7. }
8. }
Output: Sinhgad
Java String Cont …
Here two objects are created but 's' reference variable still refers to
"Sinhgad" not to "Sinhgad Institute".
For example:
1. class Testimmutablestring {
2. public static void main(String args[]) {
3. String s = "Sinhgad";
4. s = s.concat(" Institute");
5. System.out.println(s);
6. }
7. }
Exception Handling
An Exception is an abnormal condition.
An exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
Exception handling is mechanism to handle the runtime errors so that
normal flow of the program execution can be maintained.
Examples;
ClassNotFound, IO, SQL, Remote etc.
An advantage of exception handling is to maintain the normal flow of the
application.
Hierarchy of Exception classes
Exception Handling Cont …
Exception Handling Cont …
1. Checked Exception : These extend from Throwable class.
e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.
2. Unchecked Exception : These extend from Runtime Exception.
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are checked at runtime.
3. Error : These are irrecoverable
e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Type of exceptions:
Exception Handling Cont …
Scenarios where exceptions occur
1) ArithmeticException : If we divide any number by zero.
int a = 50/0; //ArithmeticException
2) NullPointerException : If we have null value in any variable and
performing any operation on it.
String s = null;
System.out.println(s.length()); //NullPointerException
3) NumberFormatException : A string variable that has characters,
converting into digit.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) ArrayIndexOutOfBoundsException : If we are inserting any value beyond
array capacity.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Exception Handling Cont …
• try block enclose the code that might throw an exception.
• Try block must be followed by catch or finally block.
• catch block handle the Exception. It placed after the try block only.
• Finally block can be used to put "cleanup" code such
as closing a file, closing connection etc.
Syntax of try-catch block
1. try {
2. //code that may throw exception
3. } catch(Exception_class_Name ref) { … }
Syntax of try-catch-finally block
1. try {
//code that may throw exception
2. } catch(Exception_class_Name ref) { … }
3. finally{}
try-catch-finally block
Exception Handling Cont …
Working of java try-catch block
Exception Handling Cont …
1.public class Testtrycatch {
2. public static void main(String args[]) {
3. try {
4. int data=50/0;
5. } catch(ArithmeticException e) { System.out.println(e); }
6. System.out.println(“Rest of the code...");
7. }
8.}
Output:
Exception in thread main java.lang.ArithmeticException: divide by zero
Rest of the code...
Exception handling example
Exception Handling Cont …
Use of finally block
1. public class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Output:
Exception in thread main java.lang.ArithmeticException: Divide by zero
finally block always executed
rest of the code...
Exception Handling Cont …
Nested try block : The try block within a try block is known as nested
try block in java.
Nested try example
Simple example of java nested try block.
1. class NestedExcep{
2. public static void main(String args[]){
3. try { try { System.out.println(“to do divide");
4. int b =39/0;
5. } catch(ArithmeticException e) { S.O.P(e); }
6. try { int a[]=new int[5];
7. a[5]=4;
8. } catch (ArrayIndexOutOfBoundsException e) { S.O.P(e);}
9. System.out.println("other statement);
10. } catch(Exception e){System.out.println("handeled");}
11. System.out.println("normal flow..");
12. }
13. }
Throw keyword explicitly throws an exception.
Throw keyword throws checked or unchecked exception.
Throw keyword is used to throw custom exception.
syntax : throw ExceptionObject;
Program example
1. public class TestThrow{
2. static void validate(int age) {
3. if (age<18)
4. throw new ArithmeticException("not valid");
5. else System.out.println("welcome to vote");
6. }
7. public static void main(String args[]) {
8. validate(13);
9. System.out.println("rest of the code...");
10. }
11. }
Output: Exception in thread main java.lang.ArithmeticException: not valid
Exception Handling Cont …
throw keyword
Exception Handling Cont …
Used to declare an exception.
Gives an information to the programmer that there may occur an exception.
Exception Handling is used to handle the checked exceptions.
If occurs unchecked exception it is programmers fault.
throws example
1. import java.io.IOException;
2. class Testthrows{
3. void m() throws IOException
4. { throw new IOException("device error"); //checked exception }
5. void n()
{ try { m(); }
catch(Exception e) { System.out.println("exception handled"); }
1. public static void main(String args[]){
2. Testthrows obj = new Testthrows();
3. obj.n(); System.out.println("normal flow...");
4. }
5. }
Output: exception handled
normal flow
throws keyword
Exception Handling Cont …
throw throws
1) Used to throw an exception. Used to declare an exception.
2) checked exception can not be
propagated with throw.
checked exception can be
propagated with throws.
3) throw is followed by an instance. throws is followed by class.
4) throw is used within the
method.
throws is used with the method
signature.
5) We cannot throw multiple
exceptions
We can declare multiple exception
e.g. public void method() throws
IOException, SQLException.
Difference between throw and throws keywords:
User created exception is known as custom exception or user-defined
exception.
Custom exceptions customize the exception according to user need .
Java Custom Exception
Example
1. class InvalidAgeException extends Exception
2. { InvalidAgeException(String s) { super(s); } }
3. class TestCustomException {
4. static void validate(int age) throws InvalidAgeException
5. { if (age<18) throw new InvalidAgeException("not valid");
6. else System.out.println("welcome");
7. }
8. public static void main(String args[]) {
9. try { validate(13);
10. } catch(Exception m) {S.O.P("Exception occurred: "+m;}
11. System.out.println("rest of the code...");
12. } }
Output: Exception occured: InvalidAgeException: not valid rest of the code...
Packages
A package is a group of classes, interfaces and sub-packages.
Package is a built-in or user-defined.
Built-in packages e.g. java, lang, awt, javax, swing, net, io, util, sql etc.
Advantages of Java
Package
1. Categorize the
classes, interfaces to
easily maintain.
2. Provides access
protection.
3. Removes naming
collision.
Packages cont …
Packages cont …
The package keyword is used to create a package.
1. // save as Simple.java
2. package mypack;
3. public class Simple {
4. public static void main(String args[]) {
5. System.out.println("Welcome to package"); }
6. }
Compile package as
javac -d directory javafilename
e.g. javac -d . Simple.java
-d switch specifies the destination to put the generated class file.
e.g. 'd:/abc' or for same directory use . (dot).
Example of package
Packages cont …
Example of package
Three ways to access the class from outside the package.
1. import package.*;
2. import package.classname; or
3. fully qualified name;
Run java package program by command
java mypack.Simple
Use fully qualified name e.g. mypack.Simple to run the class.
Example of package
1. // save by A.java
2. package pack;
3. public class A {
4. public void msg() { System.out.println("Hello"); }
5. }
Packages cont …
1. // save by B.java
2. import pack.*;
3. class B {
4. public static void main(Strincontg args[]) {
5. A obj = new A(); obj.msg();
6. } }
7. Output:Hello
Example of package cont …
1. import pack.A;
2. class B {
3. public static void main(String args[]) {
4. A obj = new A(); obj.msg();
5. } }
6. Output: Hello
pack.A obj = new pack.A(); //using fully qualified name
Packages cont …
Sequence of the program code
Subpackage
Package inside the package is called
the subpackage.
subpackage should be created to
categorize the package further.
1. Example of Subpackage
2. package com.myjava.core;
3. class Simple {
4. public static void main(String args[]){
5. System.out.println("Hello subpackage");
6. } }
Packages cont …
The access modifiers specify accessibility (scope) of a data member,
method or class.
There are 4 types of access modifiers:
1. private
2. default
3. protected
4. Public
Access Modifiers in java
• The private access modifier is accessible only within class.
• If you don't use any modifier, it is treated as default. The default
modifier is accessible only within package.
• The protected access modifier is accessible within package and
outside the package but through inheritance only.
• The public access modifier is accessible everywhere.

Weitere ähnliche Inhalte

Was ist angesagt?

Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Sagar Verma
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java BasicsVicter Paul
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with JavaJussi Pohjolainen
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 
Core java Basics
Core java BasicsCore java Basics
Core java BasicsRAMU KOLLI
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar Verma
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introductionSagar Verma
 

Was ist angesagt? (20)

Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 
Core java
Core javaCore java
Core java
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java Basics
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
 
Core Java
Core JavaCore Java
Core Java
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
 
Core java
Core java Core java
Core java
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 

Andere mochten auch

is_1_Introduction to Information Security
is_1_Introduction to Information Securityis_1_Introduction to Information Security
is_1_Introduction to Information SecuritySARJERAO Sarju
 
第十一堂 學習編譯與上架
第十一堂 學習編譯與上架第十一堂 學習編譯與上架
第十一堂 學習編譯與上架力中 柯
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
Keyboard-Dj linux project
Keyboard-Dj linux projectKeyboard-Dj linux project
Keyboard-Dj linux projectHSUHJ
 
第二堂 學習 Java 語法 (1) Java 歷史與程序開發
第二堂 學習 Java 語法 (1) Java 歷史與程序開發第二堂 學習 Java 語法 (1) Java 歷史與程序開發
第二堂 學習 Java 語法 (1) Java 歷史與程序開發力中 柯
 
String handling session 5
String handling session 5String handling session 5
String handling session 5Raja Sekhar
 
Java 基本程式設計
Java 基本程式設計Java 基本程式設計
Java 基本程式設計Brad Chao
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 

Andere mochten auch (9)

is_1_Introduction to Information Security
is_1_Introduction to Information Securityis_1_Introduction to Information Security
is_1_Introduction to Information Security
 
第十一堂 學習編譯與上架
第十一堂 學習編譯與上架第十一堂 學習編譯與上架
第十一堂 學習編譯與上架
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Keyboard-Dj linux project
Keyboard-Dj linux projectKeyboard-Dj linux project
Keyboard-Dj linux project
 
第二堂 學習 Java 語法 (1) Java 歷史與程序開發
第二堂 學習 Java 語法 (1) Java 歷史與程序開發第二堂 學習 Java 語法 (1) Java 歷史與程序開發
第二堂 學習 Java 語法 (1) Java 歷史與程序開發
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
Java 基本程式設計
Java 基本程式設計Java 基本程式設計
Java 基本程式設計
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Java string handling
Java string handlingJava string handling
Java string handling
 

Ähnlich wie 1_JavIntro

Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2miiro30
 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxDrYogeshDeshmukh1
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxPoonam60376
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxDrYogeshDeshmukh1
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301ArthyR3
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdfamitbhachne
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginersdivaskrgupta007
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
Java quick reference
Java quick referenceJava quick reference
Java quick referenceArthyR3
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introductionchnrketan
 
A seminar report on core java
A  seminar report on core javaA  seminar report on core java
A seminar report on core javaAisha Siddiqui
 

Ähnlich wie 1_JavIntro (20)

Oop java
Oop javaOop java
Oop java
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptx
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Java basic concept
Java basic conceptJava basic concept
Java basic concept
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
Java Tutorial 1
Java Tutorial 1Java Tutorial 1
Java Tutorial 1
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptx
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
DAY_1.1.pptx
DAY_1.1.pptxDAY_1.1.pptx
DAY_1.1.pptx
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introduction
 
A seminar report on core java
A  seminar report on core javaA  seminar report on core java
A seminar report on core java
 

1_JavIntro

  • 1. Programming in java Section-I 1. Introduction (6 hrs) 2. Applet as java application (2 hrs) 3. Multithreaded programming (4 hrs) 4. AWT and Java Input Output (8 hrs) Section-II 1. Introduction to Swing (5 hrs) 2. Networking with Java (5 hrs) 3. JDBC (6 hrs) 4. RMI (4 hrs)
  • 2. 1. Introduction Brief history of Java Java Version History Features of Java Objects and classes Inheritance Abstract classes Interface Use of final Keyword Use of String functions Packages Exception handling
  • 3. Brief history of Java  History of java starts from Green Team  James Gosling, Mike Sheridan, and Patrick Naughton Green Team initiated the Java language project in June 1991  Originally designed for small, embedded systems in electronic appliances  Earlier it was called Oak and developed as a part of the Green project  Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A  In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies
  • 4. Why Java name for java language?  Java is an island of Indonesia where first coffee was produced (called java coffee)  Java is just a name not an acronym  Originally developed by James Gosling at Sun Microsystems and released in 1995.  JDK 1.0 released in (January 23, 1996) <BACK>
  • 5. Java Version History Java versions: 1. JDK Alpha and Beta (1995) 2. JDK 1.0 (1996) 3. JDK 1.1 (1997) 4. J2SE 1.2 (1998) 5. J2SE 1.3 (2000) 6. J2SE 1.4 (2002) 7. J2SE 5.0 (2004) 8. Java SE 6 (2006) 9. Java SE 7 (2011) 10. Java SE 8 (18th March, 2014) Current stable release of Java
  • 6. Features of Java 1. Simple 2. Object-Oriented 3. Platform independent 4. Secured 5. Robust 6. Architecture neutral 7. Portable 8. Dynamic 9. Interpreted 10. High Performance 11. Multithreaded 12. Distributed
  • 7. 1. Syntax is based on C++ 2. Removed many confusing features e.g. explicit pointers, operator overloading etc 3. Automatic Garbage Collection in java Simple
  • 8. Object-Oriented Object-oriented means organize software as combination of different types of objects that incorporate both data and behavior Basic concepts of OOPs are:  Object  Class  Inheritance  Polymorphism  Abstraction  Encapsulation
  • 9. Platform independent A platform is hardware or software environment in which a program runs Java provides software-based platform  Runtime Environment  API(Application Programming Interface) Java code is compiled by the compiler and converted into bytecode. Bytecode is a platform independent code because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
  • 11. Java is secured because : No explicit pointer Programs run inside virtual machine sandbox Secured
  • 12. 1. Robust means strong. 2. Java uses strong memory management. 3. Lack of pointers that avoids security problem. 4. Automatic garbage collection. 5. Exception handling and type checking mechanism. All these makes java robust. No implementation dependent features e.g. size of primitive types is set Architecture neutral Robust
  • 13. Portable Allow to carry the java bytecode to any platform Dynamic Java is capable of dynamically linking new class libraries, methods and objects. Determines the class through query, making possible to link dynamically
  • 14. Interpreted Java interpreter generates machine code that can be directly by the machine with the help of JVM High Performance Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++)
  • 15. Multithreaded Java allow to handle multiple tasks simultaneously. Java supports multithreaded programs Distributed We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet <BACK>
  • 16. Data Types in Java 1. Primitive data types 2. Non-primitive data types
  • 17. Data Type Default Value Default size boolean false 1 bit char 'u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte
  • 18. Operators in java Operator is a symbol that is used to perform operations. Operators Precedence postfix expr++ expr-- unary ++expr --expr +expr -expr ~ ! multiplicative * / % additive + - shift << >> >>> relational < > <= >= instanceof equality == != bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | logical AND && logical OR || ternary ? : assignment = += -= *= /= %= &= ^= |= <<= >>=>>>=
  • 19. Objects and classes Object in Java An entity that has state and behavior is known as an object. It can be physical or logical. Object is an instance of a class. Instance variable in Java A variable that is created inside the class but outside the method, is known as instance variable. Instance variable doesn't get memory at compile time.
  • 20.  State: Represents data (value) of an object.  Behavior: Represents the behavior (functionality) of an object e.g. deposit, withdraw etc.  Identity: Object identity is a unique ID. JVM use ID to identify each object uniquely Object Properties
  • 21. Class in Java Class is a template or blueprint from which objects are created. A class is a group of objects that has common properties A class contains : 1. Data member 2. Method 3. Constructor 4. Block 5. Class and interface
  • 22. Syntax to declare a class: class <class_name> { data member; method; }
  • 23. Example of Object and Class class Student { int id; String name; //data member (also instance variable) public static void main(String args[]) { Student s1 = new Student(); //creating an object of Student System.out.println(s1.id); System.out.println(s1.name); } }
  • 24. class Student { int rollno; String name; void insertRecord (int r, String n) { rollno = r; name = n; } void displayRecord() {System.out.println(rollno+" "+name);} public static void main(String args[]){ Student s1 = new Student(); Student s2 = new Student(); s1.insertRecord(111,"Amit"); s2.insertRecord(222,"Ajay"); s1.displayRecord (); s2.displayRecord (); } } <BACK>
  • 25. class Rectangle { int length; int width; void insert(int l,int w) { length=l; width=w; } void calculateArea() { System.out.println(length*width); } public static void main(String args[]) { Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); r1.insert(11,5); r2.insert(3,15); r1.calculateArea(); r2.calculateArea(); } }
  • 26. Method Overloading in Java If a class have multiple methods with same name but different parameters, it is known as Method Overloading. Different ways to overload the method 1. By changing the no. of arguments 2. By changing the data type Method overloading increases the readability of the program. Can we overload the main method?
  • 27. Method Overloading by changing the no. of arguments class Myclass{ void sum(int a, int b) { System.out.println(a+b);} void sum(int a, int b, int c) { System.out.println(a+b+c); } public static void main(String args[]) { Myclass obj =new Myclass(); obj.sum(10, 10, 10); obj.sum(20, 20); } }
  • 28. Method Overloading by changing data type of an argument class Myclass{ void sum(int a, int b) { System.out.println(a+b); } void sum(double a, double b) { System.out.println(a+b); } public static void main(String args[]) { Myclass obj = new Myclass(); obj.sum(10.5, 10.5); obj.sum(20, 20); } }
  • 29. Method Overloading and Type Promotion One type is promoted to another implicitly if no matching data type is found as in figure given below; As displayed in the diagram, byte can be promoted to short, int, long, float or double.
  • 30. Method Overloading and Type Promotion (cont…) class Myclass { void sum(int a, long b) { System.out.println(a+b); } void sum(int a, int b, int c) { System.out.println(a+b+c); } public static void main(String args[]) { Myclass obj =new Myclass(); obj.sum(20, 20); //now second int literal will be promoted to long obj.sum(20, 20, 20); } } Output: 40 60
  • 31. Constructor in Java Types of constructors 1. Default Constructor 2. Parameterized Constructor Constructor Overloading Does constructor return any value Does constructor perform other task instead initialization Rules to define the constructor 1. Constructor name must be same as its class name 2. Constructor must have no explicit return type Constructor is a special type of method that is used to initialize the object
  • 32. Default Constructor A constructor that has no parameter is known as default constructor. Syntax of default constructor: <class_name>() { } Example of default constructor class Bike { Bike() {System.out.println("Bike is created");} public static void main(String args[]) { Bike b=new Bike(); } } Output: Bike is created
  • 33. Parameterized constructor A constructor that has parameters is known as parameterized constructor Example of parameterized constructor class Student { int id; String name; Student(int i, String n) { id = i; name = n; } void display() {System.out.println(id+" "+name);} public static void main(String args[]) { Student s1 = new Student(111,“Vijay"); Student s2 = new Student(222,“Ajay"); s1.display(); s2.display(); } Output: 111 Vijay 222 Ajay
  • 34. No copy constructor in java We can copy the values of one object to another like copy constructor in C++. Ways to copy the values of one object into another in java. 1. By constructor 2. By assigning the values of one object into another
  • 35. Copy the values of one object into another using constructor class Student { int id; String name; Student(int i,String n) { id = i; name = n; } Student(Student s) { id = s.id; name =s.name; } void display() {System.out.println(id+" "+name); } public static void main(String args[]) { Student s1 = new Student(111,"Karan"); Student s2 = new Student(s1); s1.display(); s2.display(); } } Output: 111 Karan 111 Karan
  • 36. Copying values without constructor class Student { int id; String name; Student(int i,String n) { id = i; name = n; } Student(Student s) { id = s.id; name =s.name; } void display() {System.out.println(id+" "+name);} public static void main(String args[]) { Student s1 = new Student(111,"Karan"); Student s2 = new Student(); s2.id = s1.id; s2.name = s1.name; s1.display(); s2.display(); } } Output: 111 Karan 111 Karan
  • 37. Constructor Overloading Constructor overloading is a technique in which a class can have any number of constructors that differ in parameter lists. class Student { int id; String name; int age; Student(int i, String n) { id = i; name = n; } Student(int i, String n, int a) { id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]) { Student s1 = new Student(111,“Ajay"); Student s2 = new Student(222,“Vijay",25); s1.display(); s2.display(); } } Output: 111 Ajay 0 222 Vijay 25
  • 38. static keyword 1. The static keyword is used for memory management mainly. 2. We can apply static keyword with variables, methods, blocks and nested class. 3. The static keyword belongs to the class than instance of the class. The static keyword can be used with: 1. class variable 2. class method
  • 39. static variable and method 1. The static variable can be used to refer the common property of all objects. 2. The static variable gets memory only once in class area at the time of class loading. Example of static variable 1. class Student { 2. int rollno; String name; 3. static String college =“sscs"; 4. Student(int r, String n) { rollno = r; name = n; } 5. void display () {System.out.println(rollno+" "+name+" "+college); } 6. public static void main(String args[]){ 7. Student s1 = new Student(111, “Vijay"); 8. Student s2 = new Student(222, “Ajay"); 9. s1.display(); s2.display(); 10. } }
  • 40. this keyword Usages of this keyword. 1. to refer current class instance variable. 2. to return the current class instance. 3. to invoke current class method (implicitly) 4. this can be used to invoked current class constructor 5. can be passed as an argument in the method call If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity
  • 41. 1. class Student{ 2. int id; String name; 3. Student(int id, String name){ 4. this.id = id; this.name = name; 5. } 6. void display(){System.out.println(id+" "+name);} 7. public static void main(String args[]){ 8. Student s1 = new Student(111,“Vijay"); 9. Student s2 = new Student(222,“Ajay"); 10. s1.display(); 11. s2.display(); 12. } 13. } Output: 111 Vijay 222 Ajay Refer current class instance variable
  • 42. Program of this() constructor call (constructor chaining) 1. class Student { 2. int id; String name; 3. Student() {System.out.println("default constructor is invoked");} 4. Student(int id, String name) { 5. this (); //it is used to invoked current class constructor. 6. this.id = id; this.name = name; 7. } 8. void display() {System.out.println(id+" "+name);} 9. public static void main(String args[]){ 10. Student e1 = new Student(111,“Vijay"); 11. Student e2 = new Student(222,“Ajay"); 12. e1.display(); e2.display(); 13. } } Output: default constructor is invoked default constructor is invoked 111 Vijay 222 Ajay
  • 43. 1. class Student { 2. int id; String name; String city; 3. Student(int id,String name) { 4. this.id = id; this.name = name; 5. } 6. Student(int id, String name, String city) { 7. this(id, name); //now no need to initialize id and name 8. this.city=city; 9. } 10. void display() {System.out.println(id+" "+name+" "+city);} 11. public static void main(String args[]) { Student e1 = new Student(111,"karan"); 12. Student e2 = new Student(222,"Aryan","delhi"); 13. e1.display(); 14. e2.display(); } 15. } Invoke current class constructor
  • 44. this use to invoke current class method 1. class S { 2. void m() { System.out.println("method is invoked"); } 3. void n() { this.m(); //no need because compiler does it for you. } 4. void p() { n(); } //complier will add this to invoke n() method as this.n() 5. public static void main(String args[]) 6. { S s1 = new S(); 7. s1.p(); 8. } 9. }
  • 45. this pass as an argument in the method 1. class S { 2. void m (S obj) { System.out.println("method is invoked"); } 3. void p(){ m(this); } 4. public static void main(String args[]){ 5. S s1 = new S(); 6. s1.p(); 7. } 8. } Output:method is invoked
  • 46. this use to return current class instance 1. class A { 2. A getA() { return this; } 3. void msg() {System.out.println("Hello java");} 4. } 5. 6. class Test1 { 7. public static void main(String args[]) { 8. new A().getA().msg(); 9. } 10. }
  • 47. Program of counter by static variable 1. class Counter{ 2. static int count=0; //will get memory only once and retain its value 3. Counter () { 4. count++; 5. System.out.println(count); } 6. public static void main(String args[]){ 7. Counter c1=new Counter2(); 8. Counter c2=new Counter2(); 9. Counter c3=new Counter2(); 10. } 11. } Output:1 2 3
  • 48. static method static keyword with any method, it is known as static method. 1. A static method belongs to the class rather than object of a class. 2. A static method can be invoked without creating an instance of a class. 3. A static method can access static data member and can change the value •class Student { • int rollno; String name; static String college = "ITS"; • static void change() { college = "BBDIT"; } • Student(int r, String n) { rollno = r; name = n; } • void display (){System.out.println(rollno+" "+name+" "+college);} • public static void main(String args[]){ • Student.change(); • Student s1 = new Student (111,"Karan"); • Student s2 = new Student (222,"Aryan"); • Student s3 = new Student (333,"Sonoo"); • s1.display(); s2.display(); s3.display(); • } } Output: 111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT
  • 49. Restrictions for the static method The static method can not use non static data member or call non-static method directly. this and super cannot be used in static context. Restrictions for static method 1. class A { 2. int a=40;//non static 3. 4. public static void main(String args[]){ 5. System.out.println(a); 6. } Output:Compile Time Error
  • 50. static block 1. Is used to initialize the static data member. 2. It is executed before main method at the time of class loading. 3. class A { 4. static{System.out.println("static block is invoked");} 5. public static void main(String args[]){ 6. System.out.println("Hello main"); 7. } 8. } Output: static block is invoked Hello main
  • 51. Inheritance Inheritance is a process in which one object acquires all properties and behaviors of parent object. When we inherit from an existing class, we can reuse methods and fields of parent class, and add new methods and fields. Inheritance represents the IS-A relationship or parent-child relationship. Inheritance allow :  Method Overriding  Code Reusability <BACK>
  • 52. Syntax of Inheritance class Subclass-name extends Super class-name { //methods and fields } The extends keyword indicates that we are making a new class that derives from an existing class. Relationship between two classes is Programmer IS-A Employee e.g. Programmer is a type of Employee. 1. class Employee { float salary=50000; } 2. class Programmer extends Employee { 3. int bonus=10000; 4. public static void main(String args[]){ 5. Programmer p=new Programmer(); 6. System.out.println("Programmer salary is:"+p.salary); 7. System.out.println("Bonus of Programmer is:"+p.bonus 8. } }
  • 53. Types of inheritance There are three types of inheritance as : 1. Single 2. Multilevel and 3. Hierarchical Multiple and hybrid inheritance is not supported through interface. To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
  • 54. Consider A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and we call it from child class object. class A { void msg() { System.out.println("Hello"); } } class B { void msg() { System.out.println("Welcome");} } class C extends A, B { public Static void main(String args[]) { C obj = new C(); obj.msg(); //Now which msg() method would be invoked? } } <BACK>
  • 55. Aggregation If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship. Consider an Employee object contains information as id, name, email id etc. It contains other object address, which contains information as city, state, country, zip code etc. as below. class Employee{ int id; String name; Address address;//Address is a class ... } Aggregation is for Code Reusability.
  • 56. Example of Aggregation public class Address { String city, state, country; public Address (String city, String state, String country) { this.city = city; this.state = state; this.country = country; } } public class Emp { int id; String name; Address address; public Emp(int id, String name, Address address) { this.id = id; this.name = name; this.address=address; } void display() { System.out.println (id+" "+name); System.out.println(address.city+" "+address.state+" "+address.country); } public static void main(String[] args) { Address address1 = new Address(“abc",“Sol","india"); Address address2 = new Address(“lmn",“Sol","india"); Emp e1 = new Emp(111, “Vijay", Solapur); Emp e2 = new Emp(112, “Ajay", Pandharpur); e1.display(); e2.display(); } }
  • 57. Method Overriding Subclass (child class) has the same method as declared in the parent class, it is known as method overriding. Usage of Method Overriding 1. To provide specific implementation of a method that is already provided by its super class. 2. For runtime polymorphism Rules for Method Overriding 1. method must have same name as in the parent class 2. method must have same parameter as in the parent class. 3. must be IS-A relationship (inheritance).
  • 58. Example of method overriding 1. class Vehicle{ 2. void run() { System.out.println("Vehicle runs"); } 3. } 4. class Bike extends Vehicle{ 5. void run() { System.out.println(“Runs safely"); } 6. 7. public static void main(String args[]){ 8. Bike obj = new Bike(); 9. obj.run(); 10. }
  • 59. Difference between method Overloading and Overriding Method Overloading Method Overriding Used to increase the readability of the program Used to provide the specific implementation of the method that is already provided by its super class Performed within a class. Occurs in two classes that have IS-A relationship In method overloading, parameter must be different In method overriding, parameter must be same
  • 60. super keyword super keyword is a reference variable that is used to refer immediate parent class object. When we create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable Usage of super Keyword 1. To refer immediate parent class instance variable 2. To invoke immediate parent class constructor 3. To invoke immediate parent class method
  • 61. Example to use super(): 1. class Vehicle { 2. Vehicle() { System.out.println("Vehicle is created"); 3. myvehicle() { System.out.println(“My car”); } 4. } 5. class Bike extends Vehicle { 6. Bike() { super(); //will invoke parent class constructor 7. System.out.println("Bike is created"); } 8. public static void main(String args[]) { 9. Bike b=new Bike(); super.myvehicle(); } 10. } Output: Vehicle is created Bike is created My car
  • 62. Use of final keyword The final keyword is used to restrict the user. The final keyword can be used in many case. Final can be used with : 1. variable 2. method 3. Class Is final method inherited ? Can you declare a final constructor?
  • 63. final variable If we make any variable as final, we cannot change the value of final variable. Example: 1. class Bike { 2. final int speedlimit=90; //final variable 3. void run() { speedlimit=400; } 4. public static void main(String args[]) { 5. Bike obj = new Bike(); 6. obj.run(); } 7. } //end of class Output: Compile Time Error
  • 64. final method If we make any method as final, we cannot override it. Example: class Bike { final void run() { S.o.p("running");} } class Honda extends Bike { void run() { ystem.out.println(“Runs safely with 100kmph"); } public static void main(String args[]) { Honda hunk = new Honda(); hunk.run(); } } Output: Compile Time Error
  • 65. final class If we make class as final, we cannot extend it. Example: 1. final class Bike {} 2. class Honda extends Bike { 3. void run() 4. { System.out.println("running safely with 100kmph"); } 5. public static void main(String args[]) { 6. Honda hunk= new Honda(); 7. hunk.run(); 8. } 9. } Output: Compile Time Error Is final method inherited? Yes, final method is inherited but can’t override.
  • 66. Final parameter If we declare any parameter as final, we can’t change the value of it. 1. class Bike { 2. int cube( final int n) { 3. n=n+2; //can't be changed as n is final 4. n*n*n; } 5. public static void main(String args[]) { 6. Bike b = new Bike(); 7. b.cube(5); 8. } 9. } Output: Compile Time Error <BACK>
  • 67. Abstract class  Abstraction is a process of hiding implementation details and showing only functionality.  It shows only important things and hides the internal details. e.g. sending sms  Abstraction focus on what the object does instead of how it does it. Abstract class A class that is declared with abstract keyword, is known as abstract class. It can have abstract and non-abstract methods (method with body).
  • 68. Abstract class example: abstract class A { … } Abstract method A method that is declared as abstract and does not have implementation (body) is known as abstract method. Abstract method example: abstract void print(); //no implementation and is abstract Program Example: 1. abstract class Bike { abstract void run(); } 2. class Honda extends Bike { 3. void run() {System.out.println("running safely..");} 4. public static void main(String args[]) { 5. Bike obj = new Honda4(); obj.run(); } 6. } Output put : running safely..
  • 69. Interface in Java An interface is a frame of a class. It has static constants and abstract methods only. Interface represents IS-A relationship. Reasons to use interface: 1. To achieve fully abstraction. 2. Support the multiple inheritance. 3. Achieve loose coupling. Interface data members are public, static and final by default. Methods are public and abstract.
  • 70. A class extends another class, an interface extends another interface but a class implements an interface
  • 71. ‘Printable’ interface have only one method, its implementation is provided in the A class. Example of interface interface printable { void print(); } 1. class A implements printable { 2. public void print() { System.out.println("Hello"); } 3. public static void main(String args[]) { 4. A obj = new A(); obj.print(); 5. } 6. } Output: Hello
  • 72. Multiple inheritance by interface A class implements multiple interfaces or an interface extends multiple interfaces known as multiple inheritance.
  • 73. Multiple inheritance example 1. interface Printable { void print(); } 2. 3. interface Showable { void show(); } 4. 5. class A implements Printable, Showable { 6. 7. public void print() { System.out.println("Hello"); } 8. public void show() { System.out.println("Welcome"); } 9. public static void main(String args[]) { 10. A obj = new A(); 11. obj.print(); 12. obj.show(); 13. } 14. } Output: Hello Welcome
  • 74. Interface inheritance A class implements interface but one interface extends another interface. 1. interface Printable { void print(); } 2. interface Showable extends Printable { void show(); } 3. class Testinterface implements Showable { 4. public void print() {System.out.println("Hello"); } 5. public void show() {System.out.println("Welcome"); } 6. public static void main(String args[]) { 7. Testinterface obj = new Testinterface(); 8. obj.print(); obj.show(); 9. } 10. } Output : Hello Welcome
  • 75. An interface that have no member is known as marker or tagged interface. Example: Serializable, Cloneable, Remote etc. They are used to provide essential information to the JVM.
  • 76. Java String String is an object that represents sequence of characters. Java String is immutable. An array of characters also works as string. e.g. char[] ch = {'S', 'i', 'n', 'h', 'g', 'a', 'd' }; String s = new String(ch); is same as: String s="Sinhgad"; There are two ways to create Strings. As string literal : String s1="Welcome"; String s2="Welcome"; // s2 will not create new instance By new keyword : String s = new String("Welcome"); //creates one object and one reference variable JVM creates a new string object in heap memory and the literal "Welcome" placed in the string constant pool. The variable 's' refer to the object in heap. StringBuffer and StringBuilder classes are mutable.
  • 77. Java String Cont … String Example 1. public class StringExample { 2. public static void main(String args[]) { 3. String s1="java"; //creating string by java string literal 4. char ch[] = {'s','t','r','i','n','g','s'}; 5. String s2 = new String(ch); //converting array to string 6. String s3 = new String(“sscs"); //creating by new keyword 7. System.out.println(s1); 8. System.out.println(s2); 9. System.out.println(s3); 10. } 11. } java strings example
  • 78. Java String Cont … java.lang.String provides methods to perform operations on string values. Sr. No. Method Description 1 char charAt(int index) returns char value for the index 2 int length() returns string length 3 String substring(int beginIndex) returns substring for given index 4 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index 5 boolean equals(Object another) checks the equality of string with object 6 boolean isEmpty() checks if string is empty 7 String concat(String str) concatenates specified string 8 String replace(char old, char new) replaces all occurrences of specified char value
  • 79. Java String Cont … Sr. No. Method Description 9 int indexOf(int ch) returns specified char value index 10 int indexOf(String substring) returns specified substring index 11 String toLowerCase() returns string in lowercase. 12 String toUpperCase() returns string in uppercase. 13 String split(String regex, int limit) returns splitted string matching regex and limit 14 String trim() returns trimmed string omitting leading and trailing spaces
  • 80. Java String Cont … Immutable String String objects are immutable means unmodifiable or unchangeable. An example: 1. class Timmutablestring { 2. public static void main(String args[]) { 3. String s="Sinhgad"; 4. s.concat("Institute"); //concat() method appends the string at the end 5. System.out.println(s); 6. //will print Sinhgad because strings are immutable objects 7. } 8. } Output: Sinhgad
  • 81. Java String Cont … Here two objects are created but 's' reference variable still refers to "Sinhgad" not to "Sinhgad Institute". For example: 1. class Testimmutablestring { 2. public static void main(String args[]) { 3. String s = "Sinhgad"; 4. s = s.concat(" Institute"); 5. System.out.println(s); 6. } 7. }
  • 82. Exception Handling An Exception is an abnormal condition. An exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. Exception handling is mechanism to handle the runtime errors so that normal flow of the program execution can be maintained. Examples; ClassNotFound, IO, SQL, Remote etc. An advantage of exception handling is to maintain the normal flow of the application.
  • 83. Hierarchy of Exception classes Exception Handling Cont …
  • 84. Exception Handling Cont … 1. Checked Exception : These extend from Throwable class. e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time. 2. Unchecked Exception : These extend from Runtime Exception. e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are checked at runtime. 3. Error : These are irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. Type of exceptions:
  • 85. Exception Handling Cont … Scenarios where exceptions occur 1) ArithmeticException : If we divide any number by zero. int a = 50/0; //ArithmeticException 2) NullPointerException : If we have null value in any variable and performing any operation on it. String s = null; System.out.println(s.length()); //NullPointerException 3) NumberFormatException : A string variable that has characters, converting into digit. String s="abc"; int i=Integer.parseInt(s);//NumberFormatException 4) ArrayIndexOutOfBoundsException : If we are inserting any value beyond array capacity. int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException
  • 86. Exception Handling Cont … • try block enclose the code that might throw an exception. • Try block must be followed by catch or finally block. • catch block handle the Exception. It placed after the try block only. • Finally block can be used to put "cleanup" code such as closing a file, closing connection etc. Syntax of try-catch block 1. try { 2. //code that may throw exception 3. } catch(Exception_class_Name ref) { … } Syntax of try-catch-finally block 1. try { //code that may throw exception 2. } catch(Exception_class_Name ref) { … } 3. finally{} try-catch-finally block
  • 87. Exception Handling Cont … Working of java try-catch block
  • 88. Exception Handling Cont … 1.public class Testtrycatch { 2. public static void main(String args[]) { 3. try { 4. int data=50/0; 5. } catch(ArithmeticException e) { System.out.println(e); } 6. System.out.println(“Rest of the code..."); 7. } 8.} Output: Exception in thread main java.lang.ArithmeticException: divide by zero Rest of the code... Exception handling example
  • 89. Exception Handling Cont … Use of finally block 1. public class TestFinallyBlock { 2. public static void main(String args[]){ 3. try{ 4. int data=25/0; 5. System.out.println(data); 6. } 7. catch(ArithmeticException e){System.out.println(e);} 8. finally{System.out.println("finally block always executed");} 9. System.out.println("rest of the code..."); 10. } 11. } Output: Exception in thread main java.lang.ArithmeticException: Divide by zero finally block always executed rest of the code...
  • 90. Exception Handling Cont … Nested try block : The try block within a try block is known as nested try block in java. Nested try example Simple example of java nested try block. 1. class NestedExcep{ 2. public static void main(String args[]){ 3. try { try { System.out.println(“to do divide"); 4. int b =39/0; 5. } catch(ArithmeticException e) { S.O.P(e); } 6. try { int a[]=new int[5]; 7. a[5]=4; 8. } catch (ArrayIndexOutOfBoundsException e) { S.O.P(e);} 9. System.out.println("other statement); 10. } catch(Exception e){System.out.println("handeled");} 11. System.out.println("normal flow.."); 12. } 13. }
  • 91. Throw keyword explicitly throws an exception. Throw keyword throws checked or unchecked exception. Throw keyword is used to throw custom exception. syntax : throw ExceptionObject; Program example 1. public class TestThrow{ 2. static void validate(int age) { 3. if (age<18) 4. throw new ArithmeticException("not valid"); 5. else System.out.println("welcome to vote"); 6. } 7. public static void main(String args[]) { 8. validate(13); 9. System.out.println("rest of the code..."); 10. } 11. } Output: Exception in thread main java.lang.ArithmeticException: not valid Exception Handling Cont … throw keyword
  • 92. Exception Handling Cont … Used to declare an exception. Gives an information to the programmer that there may occur an exception. Exception Handling is used to handle the checked exceptions. If occurs unchecked exception it is programmers fault. throws example 1. import java.io.IOException; 2. class Testthrows{ 3. void m() throws IOException 4. { throw new IOException("device error"); //checked exception } 5. void n() { try { m(); } catch(Exception e) { System.out.println("exception handled"); } 1. public static void main(String args[]){ 2. Testthrows obj = new Testthrows(); 3. obj.n(); System.out.println("normal flow..."); 4. } 5. } Output: exception handled normal flow throws keyword
  • 93. Exception Handling Cont … throw throws 1) Used to throw an exception. Used to declare an exception. 2) checked exception can not be propagated with throw. checked exception can be propagated with throws. 3) throw is followed by an instance. throws is followed by class. 4) throw is used within the method. throws is used with the method signature. 5) We cannot throw multiple exceptions We can declare multiple exception e.g. public void method() throws IOException, SQLException. Difference between throw and throws keywords:
  • 94. User created exception is known as custom exception or user-defined exception. Custom exceptions customize the exception according to user need . Java Custom Exception Example 1. class InvalidAgeException extends Exception 2. { InvalidAgeException(String s) { super(s); } } 3. class TestCustomException { 4. static void validate(int age) throws InvalidAgeException 5. { if (age<18) throw new InvalidAgeException("not valid"); 6. else System.out.println("welcome"); 7. } 8. public static void main(String args[]) { 9. try { validate(13); 10. } catch(Exception m) {S.O.P("Exception occurred: "+m;} 11. System.out.println("rest of the code..."); 12. } } Output: Exception occured: InvalidAgeException: not valid rest of the code...
  • 95. Packages A package is a group of classes, interfaces and sub-packages. Package is a built-in or user-defined. Built-in packages e.g. java, lang, awt, javax, swing, net, io, util, sql etc. Advantages of Java Package 1. Categorize the classes, interfaces to easily maintain. 2. Provides access protection. 3. Removes naming collision. Packages cont …
  • 96. Packages cont … The package keyword is used to create a package. 1. // save as Simple.java 2. package mypack; 3. public class Simple { 4. public static void main(String args[]) { 5. System.out.println("Welcome to package"); } 6. } Compile package as javac -d directory javafilename e.g. javac -d . Simple.java -d switch specifies the destination to put the generated class file. e.g. 'd:/abc' or for same directory use . (dot). Example of package
  • 97. Packages cont … Example of package Three ways to access the class from outside the package. 1. import package.*; 2. import package.classname; or 3. fully qualified name; Run java package program by command java mypack.Simple Use fully qualified name e.g. mypack.Simple to run the class. Example of package 1. // save by A.java 2. package pack; 3. public class A { 4. public void msg() { System.out.println("Hello"); } 5. }
  • 98. Packages cont … 1. // save by B.java 2. import pack.*; 3. class B { 4. public static void main(Strincontg args[]) { 5. A obj = new A(); obj.msg(); 6. } } 7. Output:Hello Example of package cont … 1. import pack.A; 2. class B { 3. public static void main(String args[]) { 4. A obj = new A(); obj.msg(); 5. } } 6. Output: Hello pack.A obj = new pack.A(); //using fully qualified name
  • 99. Packages cont … Sequence of the program code Subpackage Package inside the package is called the subpackage. subpackage should be created to categorize the package further. 1. Example of Subpackage 2. package com.myjava.core; 3. class Simple { 4. public static void main(String args[]){ 5. System.out.println("Hello subpackage"); 6. } }
  • 100. Packages cont … The access modifiers specify accessibility (scope) of a data member, method or class. There are 4 types of access modifiers: 1. private 2. default 3. protected 4. Public Access Modifiers in java • The private access modifier is accessible only within class. • If you don't use any modifier, it is treated as default. The default modifier is accessible only within package. • The protected access modifier is accessible within package and outside the package but through inheritance only. • The public access modifier is accessible everywhere.

Hinweis der Redaktion

  1. Object e.g. chair, bike, marker, pen, table, car etc. , tangible and intangible.
  2. ID value is not visible to the external user.
  3. Class e.g. student, college, vehicle