You are on page 1of 117

Java

Object and Class in Java

Object
A runtime entity that has state and behaviour is known as an object. For example: chair, table, pen etc. It can be tengible or intengible physical or logical!. An object has three characterstics:

state:represents the data o" an object. behaviour:represents the behaviour o" an object. identity:#bject identity is typically implemented via a uni$ue I%. &he value o" the I% is not visible to the external user, but is used internally by the J'( to identi"y each object uni$uely.

For )xample: *en is an object. Its name is +eynolds, color is white etc. known as its state. It is used to write, so writing is its behaviour. Object is an instance of a class.,lass is a template or blueprint "rom which objects are created.-o object is the instance result! o" a class. Class A class is a group o" objects that have common property. It is a template or blueprint "rom which objects are created. A class in java can contain: data member method constructor

block

Syntax to declare a class:


..
3. 5. 6. class /class0name12 data member4 method4 7

Simple Example of Object and Class In this example, we have created a -tudent class that have two data members id and name. 8e are creating the object o" the -tudent class by new keyword and printing the objects value.

.. 3. 5.
6.

class -tudent2 int id499data member also instance variable! -tring name499data member also instance variable! public static void main -tring args;<!2 -tudent s.>new -tudent !499creating an object o" -tudent -ystem.out.println s..id@A A@s..name!4

:. =. ?.
B.

C.

7 Output:D

.D. 7

null

Instance variable A variable that is created inside the class but outside the method, is known as instance variable.Instance variable doesnEt get memory at compile time.It gets memory at runtime when object instance! is created.&hat is why, it is known as instance variable. ethod In java, a method is like "unction i.e. used to expose behaviour o" an object. !dvanta"e of ethod

,ode +eusability ,ode #ptimiFation

ne# key#ord &he new keyword is used to allocate memory at runtime. Example of Object and class that maintains the records of students In this example, we are creating the two objects o" -tudent class and initialiFing the value to these objects by invoking the insert+ecord method on it. Gere, we are displaying the state data! o" the objects by invoking the displayIn"ormation method.

.. 3.
5. 6.

class -tudent2 int rollno4 -tring name4 void insert+ecord int r, -tring n!2 99method rollno>r4 name>n4 7 void displayIn"ormation !2-ystem.out.println rollno@A A@name!4799method public static void main -tring args;<!2 -tudent s.>new -tudent !4 -tudent s3>new -tudent !4 s..insert+ecord ...,AHaranA!4

:.
=. ?. B. C.

.D.
...

.3. .5. .6.


.:.

.=. .?.

s3.insert+ecord 333,AAryanA!4 .B. .C. s..displayIn"ormation !4 3D. s3.displayIn"ormation !4 3.. 33. 7 35. 7 Output:111 Karan 222 Aryan

Another )xample o" #bject and ,lass .. class +ectangle2

3. 5.
6.

int length4 int width4 void insert int l,int w!2 length>l4 width>w4 7 void calculateArea !2-ystem.out.println lengthIwidth!47 public static void main -tring args;<!2 +ectangle r.>new +ectangle !4 +ectangle r3>new +ectangle !4 r..insert ..,:!4

:.
=. ?. B. C.

.D.
...

.3. .5. .6.


.:.

.=. .?.

r3.insert 5,.:!4 .B. .C. r..calculateArea !4 3D. r3.calculateArea !4 3.. 7 33. 7 Output:55 45 $hat are the different #ays to create an object in Java% &here are many ways to create an object in java. &hey are: Jy new keyword Jy newInstance ! method Jy clone ! method Jy "actory method etc. 8e will learn, these ways to create the object later. !nnonymous object Annonymous simply means nameless.An object that have no re"erence is known as annonymous object. I" you have to use an object only once, annonymous object is a good approach.

..
3.

class ,alculation2 void "act int n!2 int "act>.4 "or int i>.4i/>n4i@@!2 "act>"actIi4 7 -ystem.out.println A"actorial is A@"act!4 7

5. 6. :.
=. ?.

B.
C. .D.

... public static void main -tring args;<!2 .3. new ,alculation !."act :!499calling method with annonymous object
.5. 7 .6. 7 Output:Factorial is 120

Creatin" multiple objects by one type only


..
+ectangle r.>new +ectangle !,r3>new +ectangle !499creating two objects

KetEs see the example:

.. 3. 5.
6.

class +ectangle2 int length4 int width4 void insert int l,int w!2 length>l4 width>w4 7 void calculateArea !2-ystem.out.println lengthIwidth!47 public static void main -tring args;<!2 +ectangle r.>new +ectangle !,r3>new +ectangle !499creating two objects r..insert ..,:!4

:.
=. ?. B. C.

.D.
...

.3. .5.
.6.

.:. .=.

r3.insert 5,.:!4 .?. .B. r..calculateArea !4 .C. r3.calculateArea !4 3D. 7 3.. 7 Output:55 45 ethod Overloadin" in Java I" a class have multiple methods by same name but di""erent parameters, it is known as ethod Overloadin".

I" we have to per"orm only one operation, having same name o" the methods increases the readability o" the program. -uppose you have to per"orm addition o" the given numbers but there can be any number o" arguments, i" you write the method such as a int,int! "or two parameters, and b int,int,int! "or three parameters then it may be di""icult "or you as well as other programmers to understand the behaviour o" the method because its name di""ers. -o, we per"orm method overloading to "igure out the program $uickly. Advantage of method overloading? (ethod overloading increases the readability of the pro"ram. &ifferent #ays to overload the method &here are two ways to overload the method in java .. Jy changing number o" arguments 3. In java' Jy changing the data type ethood Overloadin" is not possible by chan"in" the return type of the method.

()Example of
.. 3. 5.
6.

ethod Overloadin" by chan"in" the no. of ar"uments

class ,alculation2 void sum int a,int b!2-ystem.out.println a@b!47 void sum int a,int b,int c!2-ystem.out.println a@b@c!47 public static void main -tring args;<!2 ,alculation obj>new ,alculation !4 obj.sum .D,.D,.D!4

:. =. ?. B.

obj.sum 3D,3D!4 C. 7 .D. 7 Output:30

40 2)Example of Method Overloading by changing data type of argument

.. 3. 5.
6.

class ,alculation2 void sum int a,int b!2-ystem.out.println a@b!47 void sum double a,double b!2-ystem.out.println a@b!47 public static void main -tring args;<!2 ,alculation obj>new ,alculation !4 obj.sum .D.:,.D.:!4

:. =. ?. B.

obj.sum 3D,3D!4 C. .D. 7 ... 7 Output:21.0 40 *ue) $hy ethod Overloain" is not possible by chan"in" the return type of method%

In java, method overloading is not possible by changing the return type o" the method because there may occur ambiguity. KetEs see how ambiguity may occur:

because there was problem: .. 3. 5.


6. class ,alculation2 int sum int a,int b!2-ystem.out.println a@b!47 double sum int a,int b!2-ystem.out.println a@b!47 public static void main -tring args;<!2 ,alculation obj>new ,alculation !4

:. =. ?.

int result>obj.sum 3D,3D!4 99,ompile &ime )rror B. C. 7 .D. 7 int result>obj.sum 3D,3D!4 99Gere how can java determine which sum ! method should be called

Can #e overload main+) method%

Les, by method overloading. Lou can have any number o" main methods in a class by method overloading. KetEs see the simple example: .. 3.
5. 6. :. class -imple2 public static void main int a!2 -ystem.out.println a!4 7 public static void main -tring args;<!2 -ystem.out.println Amain ! method invokedA!4

=. ?. B.

main .D!4 C. 7 .D. 7 Output:main() method invoked 10

Constructor in Java
Constructor is a special type of method that is used to initialiFe the object. ,onstructor is invoked at the time of object creation. It constructs the values i.e. provides data "or the object that is why it is known as constructor.

,ules for creatin" constructor


&here are basically two rules de"ined "or the constructor. .. ,onstructor name must be same as its class name 3. ,onstructor must have no explicit return type

-ypes of constructors
&here are two types o" constructors: .. de"ault constructor noMarg constructor! 3. parameteriFed constructor

() &efault Constructor
A constructor that have no parameter is known as de"ault constructor.

Syntax of default constructor:


.. /class0name1 !27

Example of default constructor


In this example, we are creating the noMarg constructor in the Jike class. It will be invoked at the time o" object creation. .. 3. 5. 6. :. =. ?. B. class Jike2 Jike !2-ystem.out.println AJike is createdA!47 public static void main -tring args;<!2 Jike b>new Jike !4 7 7

Out ut! "ike is created

,ule: If there is no constructor in a class' compiler automatically creates a default constructor.

*ue)$hat is the purpose of default constructor%


%e"ault constructor provides the de"ault values to the object like D, null etc. depending on the type.

Example of default constructor that displays the default values


.. class -tudent2 3. int id4 5. -tring name4 6. :. void display !2-ystem.out.println id@A A@name!47 =. ?. public static void main -tring args;<!2 B. -tudent s.>new -tudent !4 C. -tudent s3>new -tudent !4 .D. s..display !4 ... s3.display !4

.3. 7 .5. 7 .. #utput:D null 3. D null Explanation:In the above class,you are not creating any constructor so compiler provides you a de"ault constructor.Gere D and null values are provided by de"ault constructor.

.arameteri/ed constructor
A constructor that have parameters is known as parameteriFed constructor.

$hy use parameteri/ed constructor%


*arameteriFed constructor is used to provide di""erent values to the distinct objects.

Example of parameteri/ed constructor


In this example, we have created the constructor o" -tudent class that have two parameters. 8e can have any number o" parameters in the constructor. .. class -tudent2 3. int id4 5. -tring name4 6. :. -tudent int i,-tring n!2 =. id > i4 ?. name > n4 B. 7 C. void display !2-ystem.out.println id@A A@name!47 .D. ... public static void main -tring args;<!2 .3. -tudent s. > new -tudent ...,AHaranA!4 .5. -tudent s3 > new -tudent 333,AAryanA!4 .6. s..display !4 .:. s3.display !4 .=. 7 .?. 7
Out ut!111 Karan 222 Aryan

Constructor Overloadin"
,onstructor overloading is a techni$ue in Java in which a class can have any number

o" constructors that di""er in parameter lists.&he compiler di""erentiates these constructors by taking into account the number o" parameters in the list and their type.

Example of Constructor Overloadin"


.. class -tudent2 3. int id4 5. -tring name4 6. int age4 :. -tudent int i,-tring n!2 =. id > i4 ?. name > n4 B. 7 C. -tudent int i,-tring n,int a!2 .D. id > i4 ... name > n4 .3. age>a4 .5. 7 .6. void display !2-ystem.out.println id@A A@name@A A@age!47 .:. .=. public static void main -tring args;<!2 .?. -tudent s. > new -tudent ...,AHaranA!4 .B. -tudent s3 > new -tudent 333,AAryanA,3:!4 .C. s..display !4 3D. s3.display !4 3.. 7 33. 7
Out ut!111 Karan 0 222 Aryan 25

$hat is the difference bet#een constructor and method %


&here are many di""erences between constructors and methods. &hey are given below. Constructor ethod ,onstructor is used to initialiFe the state o" an (ethod is used to expose object. behaviour o" an object. ,onstructor must not have return type. (ethod must have return type. ,onstructor is invoked implicitly. (ethod is invoked explicitly. &he java compiler provides a de"ault constructor i" (ethod is not provided by you donEt have any constructor. compiler in any case. (ethod name may or may not be ,onstructor name must be same as the class name. same as class name.

Copyin" the values of one object to another like copy constructor in C0 0


&here are many ways to copy the values o" one object into another. &hey are:

Jy constructor Jy assigning the values o" one object into another Jy clone ! method o" #bject class

In this example, we are going to copy the values o" one object into another using constructor. .. class -tudent2 3. int id4 5. -tring name4 6. -tudent int i,-tring n!2 :. id > i4 =. name > n4 ?. 7 B. C. -tudent -tudent s!2 .D. id > s.id4 ... name >s.name4 .3. 7 .5. void display !2-ystem.out.println id@A A@name!47 .6. .:. public static void main -tring args;<!2 .=. -tudent s. > new -tudent ...,AHaranA!4 .?. -tudent s3 > new -tudent s.!4 .B. s..display !4 .C. s3.display !4 3D. 7 3.. 7
Out ut!111 Karan 111 Karan

Copyin" the values of one object to another #ithout constructor


8e can copy the values o" one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor. .. class -tudent2 3. int id4 5. -tring name4 6. -tudent int i,-tring n!2 :. id > i4 =. name > n4 ?. 7 B. -tudent !27 C. void display !2-ystem.out.println id@A A@name!47 .D. ... public static void main -tring args;<!2 .3. -tudent s. > new -tudent ...,AHaranA!4 .5. -tudent s3 > new -tudent !4

.6. s3.id>s..id4 .:. s3.name>s..name4 .=. s..display !4 .?. s3.display !4 .B. 7 .C. 7
Out ut!111 Karan 111 Karan

*ue)&oes constructor return any value%


!ns:yes,that is current class instance Lou cannot use return type yet it returns a value!.

this key#ord
&here can be a lot o" usage o" this key#ord. In java, this is a reference variable that re"ers to the current object.

Usage of this keyword


Gere is given the = usage o" this keyword. .. this keyword can be used to re"er current class instance variable. 3. this ! can be used to invoke current class constructor. 5. this keyword can be used to invoke current class method implicitly! 6. this can be passed as an argument in the method call. :. this can be passed as argument in the constructor call. =. this keyword can also be used to return the current class instance. Su""estion:I" you are beginner to java, lookup only two usage o" this keyword.

() -he this key#ord can be used to refer current class instance variable.
I" there is ambiguity between the instance variable and parameter, this keyword resolves the problem o" ambiguity. 1nderstandin" the problem #ithout this key#ord

KetEs understand the problem i" we donEt use this keyword by the example given below: .. class student2 3. int id4 5. -tring name4 6. :. student int id,-tring name!2 =. id > id4 ?. name > name4 B. 7 C. void display !2-ystem.out.println id@A A@name!47 .D. ... public static void main -tring args;<!2 .3. student s. > new student ...,AHaranA!4 .5. student s3 > new student 53.,AAryanA!4 .6. s..display !4 .:. s3.display !4 .=. 7 .?. 7
Output:0 null 0 null

In the above example, parameter "ormal arguments! and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable. Solution of the above problem by this key#ord .. 99example o" this keyword 3. class -tudent2 5. int id4 6. -tring name4 :. =. student int id,-tring name!2 ?. this.id > id4 B. this.name > name4 C. 7 .D. void display !2-ystem.out.println id@A A@name!47 ... public static void main -tring args;<!2 .3. -tudent s. > new -tudent ...,AHaranA!4 .5. -tudent s3 > new -tudent 333,AAryanA!4 .6. s..display !4 .:. s3.display !4 .=. 7 .?. 7
Output:111 Karan 222 Aryan

I" local variables "ormal arguments! and instance variables are di""erent, there is no need to use this keyword like in the "ollowing program: .ro"ram #here this key#ord is not re2uired .. class -tudent2 3. int id4 5. -tring name4 6. :. student int i,-tring n!2 =. id > i4 ?. name > n4 B. 7 C. void display !2-ystem.out.println id@A A@name!47 .D. public static void main -tring args;<!2 ... -tudent e. > new -tudent ...,AkaranA!4 .3. -tudent e3 > new -tudent 333,AAryanA!4 .5. e..display !4 .6. e3.display !4 .:. 7 .=. 7
Output:111 Karan 222 Aryan

3) this+) can be used to invoked current class constructor.


&he this ! constructor call can be used to invoke the current class constructor constructor chaining!. &his approach is better i" you have many constructors in the class and want to reuse that constructor. .. 99*rogram o" this ! constructor call constructor chaining! 3. 5. class -tudent2 6. int id4 :. -tring name4 =. -tudent !2-ystem.out.println Ade"ault constructor is invokedA!47 ?. B. -tudent int id,-tring name!2 C. this !499it is used to invoked current class constructor. .D. this.id > id4 ... this.name > name4 .3. 7 .5. void display !2-ystem.out.println id@A A@name!47 .6. .:. public static void main -tring args;<!2 .=. -tudent e. > new -tudent ...,AkaranA!4 .?. -tudent e3 > new -tudent 333,AAryanA!4

.B. e..display !4 .C. e3.display !4 3D. 7 3.. 7


Output: de#ault constructor is invoked de#ault constructor is invoked 111 Karan 222 Aryan

Inheritance in Java
.. Inheritance 3. &ypes o" Inheritance 5. 8hy multiple inheritance is not possible in java in case o" classN Inheritance is a mechanism in which one object ac$uires all the properties and behaviours o" parent object. &he idea behind inheritance is that you can create new classes that are built upon existing classes. 8hen you inherit "rom an existing class, you reuse or inherit! methods and "ields, and you add new methods and "ields to adapt your new class to new situations. Inheritance represents the IS4! relationship.

$hy use Inheritance%


For (ethod #verriding -o +untime *olymorphism!. For ,ode +eusability.

Syntax of Inheritance
.. class -ubclassMname extends -uperclassMname 3. 2 5. 99methods and "ields 6. 7 &he keyword extends indicates that you are making a new class that derives "rom an existing class. In the terminology o" Java, a class that is inherited is called a superclass. &he new class is called a subclass.

1nderstandin" the simple example of inheritance

As displayed in the above "igure, *rogrammer is the subclass and )mployee is the superclass. +elationship between two classes is .ro"rammer IS4! Employee.It means that *rogrammer is a type o" )mployee. .. class )mployee2 3. "loat salary>6DDDD4 5. 7 6. :. class *rogrammer extends )mployee2 =. int bonus>.DDDD4 ?. B. public static void main -tring args;<!2 C. *rogrammer p>new *rogrammer !4 .D. -ystem.out.println A*rogrammer salary is:A@p.salary!4 ... -ystem.out.println AJonus o" *rogrammer is:A@p.bonus!4 .3. 7 .5. 7
Output:$ro%rammer salary is!40000.0 "onus o# ro%rammer is!10000

In the above example,*rogrammer object can access the "ield o" own class as well as o" )mployee class i.e. code reusability.

-ypes of Inheritance
#n the basis o" class, there can be three types o" inheritance: single, multilevel and hierarchical.

(ultiple and Gybrid is supported through inter"ace only. 8e will learn about inter"aces later.

ultiple inheritance is not supported in java in case of class. 8hen a class extends multiple classes i.e. known as multiple inheritance. For )xample:

*ue) $hy multiple inheritance is not supported in java%

&o reduce the complexity and simpli"y the language, multiple inheritance is not supported in java. For example:

.. class A2 3. void msg !2-ystem.out.println AGelloA!47 5. 7 6. :. class J2 =. void msg !2-ystem.out.println A8elcomeA!47 ?. 7 B. C. class , extends A,J299suppose i" it were .D. ... *ublic -tatic void main -tring args;<!2 .3. , obj>new , !4

.5. obj.msg !499Oow which msg ! method would be invokedN .6. 7 .:. 7

ethod Overridin" in Java


Gaving the same method in the subclass as declared in the parent class is known as method overridin". In other words, I" subclass provides the speci"ic implementation o" the method i.e. already provided by its parent class, it is known as (ethod #verriding.

!dvanta"e of

ethod Overridin"

(ethod #verriding is used to provide speci"ic implementation o" a method that is already provided by its super class. (ethod #verriding is used "or +untime *olymorphism

,ules for ethod Overridin": .. method must have same name as in the parent class 3. method must have same parameter as in the parent class. 5. must be inheritance I-MA! relationship.

1nderstandin" the problem #ithout mehtod overridin"


KetEs understand the problem that we may "ace in the program i" we donEt use method overriding. .. class 'ehicle2 3. void run !2-ystem.out.println A'ehicle is runningA!47 5. 7 6. class Jike extends 'ehicle2 :. =. public static void main -tring args;<!2 ?. Jike obj > new Jike !4 B. obj.run !4 C. 7 .D. 7
Output:&ehicle is runnin%

*roblem is that I have to provide a speci"ic implementation o" run ! method in subclass that is why we use method overriding.

Example of method overridin"


In this example, we have de"ined the run method in the subclass as de"ined in the parent class but it has some speci"ic implementation. &he name and parameter o" the method is same and there is I-MA relationship between the classes, so there is method overriding. .. class 'ehicle2 3. void run !2-ystem.out.println A'ehicle is runningA!47 5. 7 6. class Jike extends 'ehicle2 :. void run !2-ystem.out.println AJike is running sa"elyA!47 =. ?. public static void main -tring args;<!2 B. Jike obj > new Jike !4 C. obj.run !4 .D. 7
Out ut!"ike is runnin% sa#ely

Can #e override static method%


Oo, static method cannot be overridden. It can be proved by runtime polymorphism so we will learn it later.

$hy #e cannot override static method%


because static method is bound with class whereas instance method is bound with object. -tatic belongs to class area and instance belongs to heap area.

$hat is the difference bet#een method Overloadin" and Overridin"%

ethod

&here are three basic di""erences between the method overloading and method overriding. &hey are as "ollows: ethod Overloadin" .! (ethod overloading is used to increase the readability o" the program. 3! method overlaoding is per"ormed within a class. 5! In case o" method overloading parameter must be di""erent. ethod Overridin" (ethod overriding is used to provide the speci"ic implementation o" the method that is already provided by its super class. (ethod overriding occurs in two classes that have I-MA relationship. In case o" method overriding parameter must be same.

super key#ord

&he super is a re"erence variable that is used to re"er immediate parent class object. 8henever you create the instance o" subclass, an instance o" parent class is created implicitely i.e. re"erred by super re"erence variable. 1sa"e of super 5ey#ord .. super is used to re"er immediate parent class instance variable. 3. super ! is used to invoke immediate parent class constructor. 5. super is used to invoke immediate parent class method.

() super is used to refer immediate parent class instance variable.


Problem without super keyword .. class 'ehicle2 3. int speed>:D4 5. 7 6. :. class Jike extends 'ehicle2 =. int speed>.DD4 ?. B. void display !2 C. -ystem.out.println speed!499will print speed o" Jike .D. 7 ... public static void main -tring args;<!2 .3. Jike b>new Jike !4 .5. b.display !4 .6. .:. 7 .=. 7
Out ut!100

In the above example 'ehicle and Jike both class have a common property speed. Instance variable o" current class is re"ered by instance byde"ault, but I have to re"er parent class instance variable that is why we use super keyword to distinguish between parent class instance variable and current class instance variable. Solution by super keyword .. 99example o" super keyword 3. 5. class 'ehicle2 6. int speed>:D4 :. 7 =. ?. class Jike extends 'ehicle2 B. int speed>.DD4 C. .D. void display !2

... -ystem.out.println super.speed!499will print speed o" 'ehicle now .3. 7 .5. public static void main -tring args;<!2 .6. Jike b>new Jike !4 .:. b.display !4 .=. .?. 7 .B. 7
Out ut!50

3) super is used to invoke parent class constructor.


&he super keyword can also be used to invoke the parent class constructor as given below: .. class 'ehicle2 3. 'ehicle !2-ystem.out.println A'ehicle is createdA!47 5. 7 6. :. class Jike extends 'ehicle2 =. Jike !2 ?. super !499will invoke parent class constructor B. -ystem.out.println AJike is createdA!4 C. 7 .D. public static void main -tring args;<!2 ... Jike b>new Jike !4 .3. .5. 7 .6. 7
Out ut!&ehicle is created "ike is created

super+) is added in each class construtor automatically by compiler. As we know well that de"ault constructor is provided by compiler automatically but it also adds super ! "or the "irst statement.I" you are creating your own constructor and you donEt have either this ! or super ! as the "irst statement, compiler will provide super ! as the "irst statement o" the consructor. !nother example of super key#ord #here super+) is provided by the compiler implicitely. .. class 'ehicle2 3. 'ehicle !2-ystem.out.println A'ehicle is createdA!47 5. 7 6.

:. class Jike extends 'ehicle2 =. int speed4 ?. Jike int speed!2 B. this.speed>speed4 C. -ystem.out.println speed!4 .D. 7 ... public static void main -tring args;<!2 .3. Jike b>new Jike .D!4 .5. 7 .6. 7
Out ut!&ehicle is created 10

6) super can be used to invoke parent class method.


&he super keyword can also be used to invoke parent class method. It should be used in case subclass contains the same method as parent class as in the example given below: .. class *erson2 3. void message !2-ystem.out.println AwelcomeA!47 5. 7 6. :. class -tudent extends *erson2 =. void message !2-ystem.out.println Awelcome to javaA!47 ?. B. void display !2 C. message !499will invoke current class message ! method .D. super.message !499will invoke parent class message ! method ... 7 .3. .5. public static void main -tring args;<!2 .6. -tudent s>new -tudent !4 .:. s.display !4 .=. 7 .?. 7
Out ut!'elcome to (ava 'elcome

In the above example -tudent and *erson both classes have message ! method i" we call message ! method "rom -tudent class, it will call the message ! method o" -tudent class not o" *erson class because priority is given to local. In case there is no method in subclass as parent, there is no need to use super. In the example given below message ! method is invoked "rom -tudent class but -tudent class does not have message ! method, so you can directly call message ! method.

.ro"ram in case super is not re2uired

.. class *erson2 3. void message !2-ystem.out.println AwelcomeA!47 5. 7 6. :. class -tudent extends *erson2 =. ?. void display !2 B. message !499will invoke parent class message ! method C. 7 .D. ... public static void main -tring args;<!2 .3. -tudent s>new -tudent !4 .5. s.display !4 .6. 7 .:. 7
Out ut!'elcome

7inal 5ey#ord in Java


&he final key#ord in java is used to restrict the user. &he "inal keyword can be used in many context. Final can be: .. variable 3. method 5. class &he "inal keyword can be applied with the variables, a "inal variable that have no value it is called blank "inal variable or uninitialiFed "inal variable. It can be initialiFed in the constructor only. &he blank "inal variable can be static also which will be initialiFed in the static block only. 8e will have detailed learning o" these. KetEs "irst learn the basics o" "inal keyword.

() final variable

I" you make any variable as "inal, you cannot change the value o" "inal variable It will be constant!.

Example of final variable


&here is a "inal variable speedlimit, we are going to change the value o" this variable, but It canEt be changed because "inal variable once assigned a value can never be changed. .. class Jike2 3. "inal int speedlimit>CD499"inal variable 5. void run !2 6. speedlimit>6DD4 :. 7 =. public static void main -tring args;<!2 ?. Jike obj>new Jike !4 B. obj.run !4 C. 7 .D. 799end o" class
Out ut!)om ile *ime +rror

3) final method
I" you make any method as "inal, you cannot override it.

Example of final method


.. class Jike2 3. "inal void run !2-ystem.out.println ArunningA!47 5. 7 6. :. class Gonda extends Jike2 =. void run !2-ystem.out.println Arunning sa"ely with .DDkmphA!47 ?. B. public static void main -tring args;<!2 C. Gonda honda> new Gonda !4 .D. honda.run !4 ... 7 .3. 7
Out ut!)om ile *ime +rror

6) final class
I" you make any class as "inal, you cannot extend it.

Example of final class


.. "inal class Jike27 3. 5. class Gonda extends Jike2 6. void run !2-ystem.out.println Arunning sa"ely with .DDkmphA!47 :. =. public static void main -tring args;<!2 ?. Gonda honda> new Gonda !4 B. honda.run !4 C. 7 .D. 7
Out ut!)om ile *ime +rror

*) Is final method inherited%


Ans! Les, "inal method is inherited but you cannot override it. For )xample: .. 3. 5. 6. :. =. ?. B. class Jike2 "inal void run !2-ystem.out.println Arunning...A!47 7 class Gonda extends Jike2 public static void main -tring args;<!2 new Gonda !.run !4 7 7

Out ut!runnin%...

*) $hat is blank or uninitiali/ed final variable%


A "inal variable that is not initaliFed at the time o" declaration is known as blank "inal variable. I" you want to create a variable that is initialiFed at the time o" creating object and once initialiFed may not be changed, it is use"ul. For example *AO ,A+% number o" an employee. It can be initialiFed only in constuctor.

Example of blank final variable


.. 3. 5. 6. class -tudent2 int id4 -tring name4 "inal -tring *AO0,A+%0OP(J)+4

:. ... =. 7

*ue) Can #e intiali/e blank final variable%


Les, but only in constructor. For example: .. class Jike2 3. "inal int speedlimit499blank "inal variable 5. 6. Jike !2 :. speedlimit>?D4 =. -ystem.out.println speedlimit!4 ?. 7 B. C. public static void main -tring args;<!2 .D. new Jike !4 ... 7 .3. 7
Out ut!,0

static blank final variable


A static "inal variable that is not initaliFed at the time o" declaration is known as static blank "inal variable. It can be initialiFed only in static block.

Example of static blank final variable


.. class A2 3. static "inal int data499static blank "inal variable 5. static2 data>:D47 6. public static void main -tring args;<!2 :. -ystem.out.println A.data!4 =. 7 ?. 7

*) $hat is final parameter%


I" you declare any parameter as "inal, you cannot change the value o" it. .. class Jike2 3. int cube "inal int n!2 5. n>n@3499canEt be changed as n is "inal 6. nInIn4

:. 7 =. public static void main -tring args;<!2 ?. Jike b>new Jike !4 B. b.cube :!4 C. 7 .D. 7
Out ut!)om ile *ime +rror

*) Can #e declare a constructor final%


Oo, because constructor is never inherited.

Static 8indin" and &ynamic 8indin"

,onnecting a method call to the method body is known as binding. &here are two types o" binding .. static binding also known as early binding!. 3. dynamic binding also known as late binding!.

1nderstandin" -ype
KetEs understand the type o" instance. () variables have a type )ach variable has a type, it may be primitive and nonMprimitive. .. int data>5D4 Gere data variable is a type o" int. 3) ,eferences have a type .. class %og2 3. public static void main -tring args;<!2 5. %og d.499Gere d. is a type o" %og 6. 7

:. 7 6) Objects have a type An object is an instance o" particular java class,but it is also an instance o" its superclass. .. class Animal27 3. 5. class %og extends Animal2 6. public static void main -tring args;<!2 :. %og d.>new %og !4 =. 7 ?. 7 Gere d. is an instance o" %og class, but it is also an instance o" Animal.

static bindin"
8hen type o" the object is determined at compiled time by the compiler!, it is known as static binding. I" there is any private, "inal or static method in a class, there is static binding.

Example of static bindin"


.. class %og2 3. private void eat !2-ystem.out.println Adog is eating...A!47 5. 6. public static void main -tring args;<!2 :. %og d.>new %og !4 =. d..eat !4 ?. 7 B. 7

&ynamic bindin"
8hen type o" the object is determined at runMtime, it is known as dynamic binding.

Example of dynamic bindin"


.. class Animal2 3. void eat !2-ystem.out.println Aanimal is eating...A!47 5. 7 6. :. class %og extends Animal2

=. void eat !2-ystem.out.println Adog is eating...A!47 ?. B. public static void main -tring args;<!2 C. Animal a>new %og !4 .D. a.eat !4 ... 7 .3. 7
Output:do% is eatin%...

In the above example object type cannot be determined by the compiler, because the instance o" %og is also an instance o" Animal.-o compiler doesnEt know its type, only its base type.

instanceof operator
.. 3. 5. 6. :. &he instanceo" operator )xample o" instanceo" operator Applying the instanceo" operator with a variable the have null value %owncasting with instanceo" operator %owncasting without instanceo" operator

&he instanceof operator is used to test whether the object is an instance o" the speci"ied type class or subclass or inter"ace!. &he instanceo" operator is also known as type comparison operator because it compares the instance with type. It returns either true or "alse. I" we apply the instanceo" operator with any variable that have null value, it returns "alse.

Simple example of instanceof operator


KetEs see the simple example o" instance operator where it tests the current class. .. class -imple2 3. public static void main -tring args;<!2 5. -imple s>new -imple !4 6. -ystem.out.println s instanceo" -imple!499true :. 7 =. 7
Out ut!true

An object o" subclass type is also a type o" parent class. For example, i" %og extends Animal then object o" %og can be re""ered by either %og or Animal class.

Another example of instanceof operator

.. class Animal27 3. class %og extends Animal299%og inherits Animal 5. 6. public static void main -tring args;<!2 :. %og d>new %og !4 =. -ystem.out.println d instanceo" Animal!499true ?. 7 B. 7
Out ut!true

!bstract class in Java


A class that is declared with abstract keyword, is known as abstract class. Je"ore learning abstract class, letEs understand the abstraction "irst.

!bstraction
!bstraction is a process o" hiding the implementation details and showing only "unctionality to the user. Another way, it shows only important things to the user and hides the internal details "or example sending sms, you just type the text and send the message. Lou donEt know the internal processing about the message delivery. Abstraction lets you "ocus on what the object does instead o" how it does it.

$ays to achieve !bstaction


&here are two ways to achieve abstraction in java .. Abstract class D to .DDQ! 3. Inter"ace .DDQ!

!bstract class
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Syntax to declare the abstract class


.. abstract class /class0name127

abstract method

A method that is declared as abstract and does not have implementation is known as abstract method.

Syntax to define the abstract method


.. abstract return0type /method0name1 !499no braces27

Example of abstract class that have abstract method


In this example, Jike the abstract class that contains only one abstract method run. It implementation is provided by the Gonda class. .. abstract class Jike2 3. abstract void run !4 5. 7 6. :. class Gonda extends Jike2 =. void run !2-ystem.out.println Arunning sa"ely..A!47 ?. B. public static void main -tring args;<!2 C. Jike obj > new Gonda !4 .D. obj.run !4 ... 7 .3. 7
Out ut!runnin% sa#ely..

1nderstandin" the real scenario of abstract class


In this example, -hape is the abstract class, its implementation is provided by the +ectangle and ,ircle classes. (ostly, we donEt know about the implementation class i.e. hidden to the end user! and object o" the implementation class is provided by the factory method. A factory method is the method that returns the instance o" the class. 8e will learn about the "actory method later. In this example, i" you create the instance o" +ectangle class, draw method o" +ectangle class will be invoked. .. 3. 5. 6. :. =. abstract class -hape2 abstract void draw !4 7 class +ectangle extends -hape2 void draw !2-ystem.out.println Adrawing rectangleA!47

?. 7 B. C. class ,ircle extends -hape2 .D. void draw !2-ystem.out.println Adrawing circleA!47 ... 7 .3. .5. class &est2 .6. public static void main -tring args;<!2 .:. -hape s>new ,ircle !4 .=. 99In real scenario, #bject is provided through "actory method .?. s.draw !4 .B. 7 .C. 7
Out ut!dra'in% circle

!bstract class havin" constructor' data member' methods etc.


9ote: !n abstract class can have data member' abstract method' method body' constructor and even main+) method. .. 99example o" abstract class that have method body 3. abstract class Jike2 5. abstract void run !4 6. void changeRear !2-ystem.out.println Agear changedA!47 :. 7 =. ?. class Gonda extends Jike2 B. void run !2-ystem.out.println Arunning sa"ely..A!47 C. .D. public static void main -tring args;<!2 ... Jike obj > new Gonda !4 .3. obj.run !4 .5. obj.changeRear !4 .6. 7 .:. 7
Out ut!runnin% sa#ely.. %ear chan%ed

.. 3. 5. 6. :. =. ?. B. C.

99example o" abstract class having constructor, "ield and method abstract class Jike 2 int limit>5D4 Jike !2-ystem.out.println Aconstructor is invokedA!47 void get%etails !2-ystem.out.println Ait has two wheelsA!47 abstract void run !4 7

.D. class Gonda extends Jike2 ... void run !2-ystem.out.println Arunning sa"ely..A!47 .3. .5. public static void main -tring args;<!2 .6. Jike obj > new Gonda !4 .:. obj.run !4 .=. obj.get%etails !4 .?. -ystem.out.println obj.limit!4 .B. 7 .C. 7
Out ut!constructor is invoked runnin% sa#ely.. it has t'o 'heels 30

,ule: If there is any abstract method in a class' that class must be abstract. .. class Jike2 3. abstract void run !4 5. 7
Out ut!com ile time error

,ule: If you are extendin" any abstact class that have abstract method' you must either provide the implementation of the method or make this class abstract.

!nother real scenario of abstract class


&he abstract class can also be used to provide some implementation o" the inter"ace. In such case, the end user may not be "orced to override all the methods o" the inter"ace. 9ote: If you are be"inner to java' learn interface first and skip this example. .. inter"ace A2 3. void a !4 5. void b !4 6. void c !4 :. void d !4 =. 7 ?. B. abstract class J implements A2 C. public void c !2-ystem.out.println AI am ,A!47 .D. 7 ... .3. class ( extends J2 .5. public void a !2-ystem.out.println AI am aA!47

.6. public void b !2-ystem.out.println AI am bA!47 .:. public void d !2-ystem.out.println AI am dA!47 .=. 7 .?. .B. class &est2 .C. public static void main -tring args;<!2 3D. A a>new ( !4 3.. a.a !4 33. a.b !4 35. a.c !4 36. a.d !4 3:. 77
Out ut!am am am am a . c d

Interface in Java
.. 3. 5. 6. Inter"ace )xample o" Inter"ace (ultiple inheritance by Inter"ace 8hy multiple inheritance is supported in Inter"ace while it is not supported in case o" class. :. (arker Inter"ace =. Oested Inter"ace An interface is a blueprint o" a class. It has static constants and abstract methods. &he inter"ace is a mechanism to achieve fully abstraction in java. &here can be only abstract methods in the inter"ace. It is used to achieve "ully abstraction and multiple inheritance in Java. Inter"ace also represents IS4! relationship. It cannot be instantiated just like abstract class.

Why use Interface?


&here are mainly three reasons to use inter"ace. &hey are given below. It is used to achieve "ully abstraction. Jy inter"ace, we can support the "unctionality o" multiple inheritance.

It can be used to achieve loose coupling.

-he java compiler adds public and abstract key#ords before the interface method and public' static and final key#ords before data members.

In other words, Inter"ace "ields are public, static and "inal byde"ault, and methods are public and abstract.

1nderstandin" relationship bet#een classes and interfaces As shown in the "igure given below, a class extends another class, an inter"ace extends another inter"ace but a class implements an interface.

Simple example of Interface


In this exmple, *rintable inter"ace have only one method, its implemenation is provided in the A class. .. inter"ace printable2 3. void print !4 5. 7 6. :. class A implements printable2 =. public void print !2-ystem.out.println AGelloA!47 ?. B. public static void main -tring args;<!2 C. A obj > new A !4 .D. obj.print !4 ... 7 .3. 7
Output:/ello

Multiple inheritance in Java y interface


I" a class implements multiple inter"aces, or an inter"ace extends multiple inter"aces i.e. known as multiple inheritance.

.. inter"ace *rintable2 3. void print !4 5. 7 6. :. inter"ace -howable2 =. void show !4 ?. 7 B. C. class A implements *rintable,-howable2 .D. ... public void print !2-ystem.out.println AGelloA!47 .3. public void show !2-ystem.out.println A8elcomeA!47 .5. .6. public static void main -tring args;<!2 .:. A obj > new A !4 .=. obj.print !4 .?. obj.show !4 .B. 7 .C. 7
Output:/ello 0elcome

!" Multiple inheritance is not supported in case of class ut it is supported in case of interface# why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case o" class. Jut it is supported in case o" inter"ace because there is no ambiguity as implmentation is provided by the implementation class. For example: .. inter"ace *rintable2 3. void print !4 5. 7 6.

:. inter"ace -howable2 =. void print !4 ?. 7 B. C. class A implements *rintable,-howable2 .D. ... public void print !2-ystem.out.println AGelloA!47 .3. .5. public static void main -tring args;<!2 .6. A obj > new A !4 .:. obj.print !4 .=. 7 .?. 7
Output:/ello

As you can see in the above example, *rintable and -howable inter"ace have same methods but its implementation is provided by class A, so there is no ambiguity. 9ote: ! class implements interface but One interface extends another interface . .. inter"ace *rintable2 3. void print !4 5. 7 6. :. inter"ace -howable extends *rintable2 =. void show !4 ?. 7 B. C. class A implements -howable2 .D. ... public void print !2-ystem.out.println AGelloA!47 .3. public void show !2-ystem.out.println A8elcomeA!47 .5. .6. public static void main -tring args;<!2 .:. A obj > new A !4 .=. obj.print !4 .?. obj.show !4 .B. 7 .C. 7
Output:/ello 0elcome
*akage http:99www.javatpoint.com9package

!ccess

odifiers

.. 3. 5. 6. :. =.

private access modi"ier +ole o" private constructor de"ault access modi"ier protected access modi"ier public access modi"ier Applying access modi"er with method overriding

&here are two types o" modi"iers in java: access modifier and non4access modifier. &he access modi"iers speci"ies accessibility scope! o" a datamember, method, constructor or class. &here are 6 types o" access modi"iers: .. 3. 5. 6. private de"ault protected public

&here are many nonMaccess modi"iers such as static, abstract, synchroniFed, native, volatile, transient etc. Gere, we will learn access modi"iers.

() private
&he private access modi"ier is accessible only within class.

Simple example of private access modifer


In this example, we have created two classes A and -imple. A class contains private data member and private method. 8e are accessing these private members "rom outside the class, so there is compile time error. .. class A2 3. private int data>6D4 5. private void msg !2-ystem.out.println AGello javaA!47 6. 7 :. =. public class -imple2 ?. public static void main -tring args;<!2 B. A obj>new A !4 C. -ystem.out.println obj.data!499,ompile &ime )rror .D. obj.msg !499,ompile &ime )rror ... 7 .3. 7

,ole of .rivate Constructor:


I" you make any class constructor private, you cannot create the instance o" that class "rom outside the class. For example:

.. class A2 3. private A !2799private constructor 5. 6. void msg !2-ystem.out.println AGello javaA!47 :. 7 =. ?. public class -imple2 B. public static void main -tring args;<!2 C. A obj>new A !499,ompile &ime )rror .D. 7 ... 7 9ote: ! class cannot be private or protected except nested class.

3) default
I" you donEt use any modi"ier, it is treated as default byde"ault. &he de"ault modi"ier is accessible only within package.

Example of default access modifier


In this example, we have created two packages pack and mypack. 8e are accessing the A class "rom outside its package, since A class is not public, so it cannot be accessed "rom outside the package. .. 3. 5. 6. :. =. 99save by A.java package pack4 class A2 void msg !2-ystem.out.println AGelloA!47 7

.. 99save by J.java 3. 5. package mypack4 6. import pack.I4 :. =. class J2 ?. public static void main -tring args;<!2 B. A obj > new A !499,ompile &ime )rror C. obj.msg !499,ompile &ime )rror .D. 7 ... 7 In the above example, the scope o" class A and its method msg ! is de"ault so it cannot be accessed "rom outside the package.

6) protected
&he protected access modifier is accessible within package and outside the package but through inheritance only. &he protected access modi"ier can be applied on the data member, method and constructor. It canEt be applied on the class.

Example of protected access modifier


In this example, we have created the two packages pack and mypack. &he A class o" pack package is public, so can be accessed "rom outside the package. Jut msg method o" this package is declared as protected, so it can be accessed "rom outside the class only through inheritance. .. 3. 5. 6. :. =. 99save by A.java package pack4 public class A2 protected void msg !2-ystem.out.println AGelloA!47 7

.. 99save by J.java 3. 5. package mypack4 6. import pack.I4 :. =. class J extends A2 ?. public static void main -tring args;<!2 B. J obj > new J !4 C. obj.msg !4 .D. 7 ... 7
Output:/ello

:) public
&he public access modifier is accessible everywhere. It has the widest scope among all other modiers.

Example of public access modifier


.. 99save by A.java 3. 5. package pack4 6. public class A2

:. public void msg !2-ystem.out.println AGelloA!47 =. 7 .. 99save by J.java 3. 5. package mypack4 6. import pack.I4 :. =. class J2 ?. public static void main -tring args;<!2 B. A obj > new A !4 C. obj.msg !4 .D. 7 ... 7
Output:/ello

1nderstandin" all java access modifiers


KetEs understand the access mod"iers by a simple table. !ccess odifier .rivate &efault .rotected .ublic #ithin class L L L L O L L L #ithin packa"e O O L L outside packa"e by subclass only O O O L outside packa"e

Immutable Strin"
In java, strings are immutable unmodi"iable! objects.For example .. class -imple2 3. public static void main -tring args;<!2 5. 6. -tring s>A-achinA4 :. s.concat A &endulkarA!499concat ! method appends the string at the end =. -ystem.out.println s!499will print -achin because strings are immutable objec ts ?. 7 B. 7
Output:1achin

As you can see in the above "igure that two objects will be created but no re"erence

variable re"ers to A-achin &endulkarA.Jut i" we explicitely assign it to the re"erence variable, it will re"er to A-achin &endulkarA object.For example: .. class -imple2 3. public static void main -tring args;<!2 5. 6. -tring s>A-achinA4 :. s>s.concat A &endulkarA!4 =. -ystem.out.println s!4 ?. 7 B. 7
Output:1achin *endulkar

$hy strin" objects are immutable in java%


Jecause java uses the concept o" string literal.-uppose there are : re"erence variables,all re"eres to one object AsachinA.I" one re"erence variable changes the value o" the object, it will be a""ected to all the re"erence variables. &hat is why string objects are immutable in java.

Strin" comparison in Java


8e can compare two given on the basis o" content and re"erence. It is used in authentication e$uals ! method!, sorting compare&o ! method! etc. &here are three ways to compare -tring objects: .. Jy e$uals ! method 3. Jy > > operator 5. Jy compare&o ! method

() 8y e2uals+) method:
e$uals ! method compares the original content o" the string.It compares values o" string "or e$uality.-tring class provides two methods: public boolean e2uals+Object another);< compares this string to the speci"ied object. public boolean e2ualsI"noreCase+Strin" another);< compares this -tring to another -tring, ignoring case. .. 99/b1/i1)xample o" e$uals #bject! method/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s.>A-achinA4 ?. -tring s3>A-achinA4

B. -tring s5>new -tring A-achinA!4 C. -tring s6>A-auravA4 .D. ... -ystem.out.println s..e$uals s3!!499true .3. -ystem.out.println s..e$uals s5!!499true .5. -ystem.out.println s..e$uals s6!!499"alse .6. 7 .:. 7
Output:true true #alse

.. 99/b1/i1)xample o" e$ualsIgnore,ase -tring! method/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s.>A-achinA4 ?. -tring s3>A-A,GIOA4 B. C. -ystem.out.println s..e$uals s3!!499"alse .D. -ystem.out.println s..e$ualsIgnore,ase s5!!499true ... 7 .3. 7
Output:#alse true

3) 8y == operator:
&he > > operator compares re"erences not values. .. 99/b1/i1)xample o" >> operator/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s.>A-achinA4 ?. -tring s3>A-achinA4 B. -tring s5>new -tring A-achinA!4 C. .D. -ystem.out.println s.>>s3!499true because both re"er to same instance! ... -ystem.out.println s.>>s5!499"alse because s5 re"ers to instance created in no npool! .3. 7 .5. 7
Output:true #alse

6) 8y compare-o+) method:
compare&o ! method compares values and returns an int which tells i" the values compare less than, e$ual, or greater than. -uppose s. and s3 are two string variables.I": s( == s3 :D s( > s3 :positive value

s( ? s3 :negative value

.. 99/b1/i1)xample o" compare&o ! method:/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s.>A-achinA4 ?. -tring s3>A-achinA4 B. -tring s5>A+atanA4 C. .D. -ystem.out.println s..compare&o s3!!499D ... -ystem.out.println s..compare&o s5!!499. because s.1s5! .3. -ystem.out.println s5.compare&o s.!!499M. because s5 / s. ! .5. 7 .6. 7
Output:0 1 21

Strin" Concatenation in Java


,oncating strings "orm a new string i.e. the combination o" multiple strings. &here are two ways to concat string objects: .. Jy @ string concatenation! operator 3. Jy concat ! method

() 8y 0 +strin" concatenation) operator


-tring concatenation operator is used to add strings.For )xample: .. 99)xample o" string concatenation operator 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s>A-achinA@A &endulkarA4

?. -ystem.out.println s!499-achin &endulkar B. 7 C. 7


Output:1achin *endulkar

&he compiler trans"orms this to: .. -tring s> new -tringJuilder !!.append A-achinA!.append A &endulkar!.to-trin g !4 -tring concatenation is implemented through the -tringJuilder or -tringJu""er! class and its append method.-tring concatenation operator produces a new string by appending the second operand onto the end o" the "irst operand.&he string concatenation operator can concat not only string but primitive values also.For )xample: .. class -imple2 3. public static void main -tring args;<!2 5. 6. -tring s>:D@5D@A-achinA@6D@6D4 :. -ystem.out.println s!499BD-achin6D6D =. 7 ?. 7
Output:301achin4040

9ote:I" either operand is a string, the resulting operation will be string concatenation. I" both operands are numbers, the operator will per"orm an addition.

3) 8y concat+) method
concat ! method concatenates the speci"ied string to the end o" current string. Syntax:public -tring concat -tring another!27 .. 99/b1/i1)xample o" concat -tring! method/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s.>A-achin A4 ?. -tring s3>A&endulkarA4 B. C. -tring s5>s..concat s3!4 .D. ... -ystem.out.println s5!499-achin &endulkar .3. 7 .5. 7
Output:1achin *endulkar

Substrin" in Java
A part o" string is called substrin". In other words, substring is a subset o" another string. In case o" substring startIndex starts "rom D and endIndex starts "rom . or startIndex is inclusive and endIndex is exclusive. Lou can get substring "rom the given -tring object by one o" the two methods: .. public Strin" substrin"+int startIndex): &his method returns new -tring object containing the substring o" the given string "rom speci"ied startIndex inclusive!. 3. public Strin" substrin"+int startIndex'int endIndex): &his method returns new -tring object containing the substring o" the given string "rom speci"ied startIndex to endIndex. In case o" string: startIndex:starts "rom index D inclusive!.

endIndex:starts "rom index . exclusive!.

Example of java substrin"


.. 99)xample o" substring ! method 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s>A-achin &endulkarA4 ?. -ystem.out.println s.substring =!!499&endulkar B. -ystem.out.println s.substring D,=!!499-achin C. 7 .D. 7
Output:*endulkar 1achin

ethods of Strin" class

java.lang.-tring class provides a lot o" methods to work on string. KetEs see the commonly used methods o" -tring class. ethod &escription .!public boolean e$uals #bject an#bject! ,ompares this string to the speci"ied object. 3!public boolean e$ualsIgnore,ase -tring ,ompares this -tring to another -tring, another! ignoring case. ,oncatenates the speci"ied string to the end 5!public -tring concat -tring str! o" this string. 6!public int compare&o -tring str! ,ompares two strings and returns int :!public int compare&oIgnore,ase -tring ,ompares two strings, ignoring case str! di""erences. +eturns a new string that is a substring o" =!public -tring substring int beginIndex! this string. ?!public -tring substring int +eturns a new string that is a substring o" beginIndex,int endIndex! this string. ,onverts all o" the characters in this -tring B!public -tring toPpper,ase ! to upper case ,onverts all o" the characters in this -tring C!public -tring toKower,ase ! to lower case. +eturns a copy o" the string, with leading .D!public -tring trim ! and trailing whitespace omitted. ..!public boolean starts8ith -tring &ests i" this string starts with the speci"ied pre"ix! pre"ix. .3!public boolean ends8ith -tring &ests i" this string ends with the speci"ied su""ix! su""ix. +eturns the char value at the speci"ied .5!public char charAt int index! index. .6!public int length ! +eturns the length o" this string. +eturns a canonical representation "or the .:!public -tring intern ! string object. First seven methods have already been discussed.Oow KetEs take the example o" other methods:

to1pperCase+) and to@o#erCase+) method


.. 99/b1/i1)xample o" toPpper,ase ! and toKower,ase ! method/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s>A-achinA4 ?. -ystem.out.println s.toPpper,ase !!499-A,GIO B. -ystem.out.println s.toKower,ase !!499sachin C. -ystem.out.println s!499-achin no change in original! .D. 7

... 7
Output:1A)/-4 sachin 1achin

trim+) method
.. 99/b1/i1)xample o" trim ! method/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s>A -achin A4 ?. -ystem.out.println s!499 -achin B. -ystem.out.println s.trim !!499-achin C. 7 .D. 7
Output: 1achin 1achin

starts$ith+) and ends$ith+) method


.. 99/b1/i1)xample o" starts8ith ! and ends8ith ! method/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s>A-achinA4 ?. -ystem.out.println s.starts8ith A-aA!!499true B. -ystem.out.println s.starts8ith AnA!!499true C. 7 .D. 7
Output:true true

char!t+) method
.. 99/b1/i1)xample o" charAt ! method/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s>A-achinA4 ?. -ystem.out.println s.charAt D!!499-

B. -ystem.out.println s.charAt 5!!499h C. 7 .D. 7


Output:1 h

len"th+) method
.. 99/b1/i1)xample o" length ! method/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s>A-achinA4 ?. -ystem.out.println s.length !!499= B. 7 C. 7
Output:5

intern+) method
A pool o" strings, initially empty, is maintained privately by the class -tring. 8hen the intern method is invoked, i" the pool already contains a string e$ual to this -tring object as determined by the e$uals #bject! method, then the string "rom the pool is returned. #therwise, this -tring object is added to the pool and a re"erence to this -tring object is returned. .. 99/b1/i1)xample o" length ! method/9i1/9b1 3. 5. class -imple2 6. public static void main -tring args;<!2 :. =. -tring s>new -tring A-achinA!4 ?. -tring s3>s.intern !4 B. -ystem.out.println s3!499-achin C. 7 .D. 7
Output:1achin

Strin"8uffer class:
&he -tringJu""er class is used to created mutable modi"iable! string. &he -tringJu""er class is same as -tring except it is mutable i.e. it can be changed.

9ote: Strin"8uffer class is thread4safe i.e. multiple threads cannot access it simultaneously .So it is safe and #ill result in an order.

Commonly used Constructors of Strin"8uffer class:


.. Strin"8uffer+): creates an empty string bu""er with the initial capacity o" .=. 3. Strin"8uffer+Strin" str): creates a string bu""er with the speci"ied string. 5. Strin"8uffer+int capacity): creates an empty string bu""er with the speci"ied capacity as length.

Commonly used methods of Strin"8uffer class:


.. public synchroni/ed Strin"8uffer append+Strin" s): is used to append the speci"ied string with this string. &he append ! method is overloaded like append char!, append boolean!, append int!, append "loat!, append double! etc. 3. public synchroni/ed Strin"8uffer insert+int offset' Strin" s): is used to insert the speci"ied string with this string at the speci"ied position. &he insert ! method is overloaded like insert int, char!, insert int, boolean!, insert int, int!, insert int, "loat!, insert int, double! etc. 5. public synchroni/ed Strin"8uffer replace+int startIndex' int endIndex' Strin" str): is used to replace the string "rom speci"ied startIndex and endIndex. 6. public synchroni/ed Strin"8uffer delete+int startIndex' int endIndex): is used to delete the string "rom speci"ied startIndex and endIndex. :. public synchroni/ed Strin"8uffer reverse+): is used to reverse the string. =. public int capacity+): is used to return the current capacity. ?. public void ensureCapacity+int minimumCapacity): is used to ensure the capacity at least e$ual to the given minimum. B. public char char!t+int index): is used to return the character at the speci"ied position. C. public int len"th+): is used to return the length o" the string i.e. total number o" characters. .D. public Strin" substrin"+int be"inIndex): is used to return the substring "rom the speci"ied beginIndex. ... public Strin" substrin"+int be"inIndex' int endIndex): is used to return the substring "rom the speci"ied beginIndex and endIndex.

$hat is mutable strin"%


A string that can be modi"ied or changed is known as mutable string. -tringJu""er and -tringJuilder classes are used "or creating mutable string.

simple example of Strin"8uffer class by append+) method


&he append ! method concatenates the given argument with this string.

.. 3. 5. 6. :. =. ?. B. C.

class A2 public static void main -tring args;<!2 -tringJu""er sb>new -tringJu""er AGello A!4 sb.append AJavaA!499now original string is changed -ystem.out.println sb!499prints Gello Java 7 7

Example of insert+) method of Strin"8uffer class


&he insert ! method inserts the given string with this string at the given position. .. 3. 5. 6. :. =. ?. B. C. class A2 public static void main -tring args;<!2 -tringJu""er sb>new -tringJu""er AGello A!4 sb.insert .,AJavaA!499now original string is changed -ystem.out.println sb!499prints GJavaello 7 7

Example of replace+) method of Strin"8uffer class


&he replace ! method replaces the given string "rom the speci"ied beginIndex and endIndex. .. 3. 5. 6. :. =. ?. B. C. class A2 public static void main -tring args;<!2 -tringJu""er sb>new -tringJu""er AGelloA!4 sb.replace .,5,AJavaA!4 -ystem.out.println sb!499prints GJavalo 7 7

Example of delete+) method of Strin"8uffer class


&he delete ! method o" -tringJu""er class deletes the string "rom the speci"ied beginIndex to endIndex. .. class A2

3. 5. 6. :. =. ?. B. C.

public static void main -tring args;<!2 -tringJu""er sb>new -tringJu""er AGelloA!4 sb.delete .,5!4 -ystem.out.println sb!499prints Glo 7 7

Example of reverse+) method of Strin"8uffer class


&he reverse ! method o" -tringJuilder class reverses the current string. .. 3. 5. 6. :. =. ?. B. C. class A2 public static void main -tring args;<!2 -tringJu""er sb>new -tringJu""er AGelloA!4 sb.reverse !4 -ystem.out.println sb!499prints olleG 7 7

Example of capacity+) method of Strin"8uffer class


&he capacity ! method o" -tringJu""er class returns the current capacity o" the bu""er. &he de"ault capacity o" the bu""er is .=. I" the number o" character increases "rom its current capacity, it increases the capacity by oldcapacityI3!@3. For example i" your current capacity is .=, it will be .=I3!@3>56. .. class A2 3. public static void main -tring args;<!2 5. 6. -tringJu""er sb>new -tringJu""er !4 :. -ystem.out.println sb.capacity !!499de"ault .= =. ?. sb.append AGelloA!4 B. -ystem.out.println sb.capacity !!499now .= C. .D. sb.append Ajava is my "avourite languageA!4 ... -ystem.out.println sb.capacity !!499now .=I3!@3>56 i.e oldcapacityI3!@3 .3. 7 .5. 7

Strin"8uilder class:

&he -tringJuilder class is used to create mutable modi"iable! string. &he -tringJuilder class is same as -tringJu""er class except that it is nonMsynchroniFed. It is available since J%H..:.

Commonly used Constructors of Strin"8uilder class:


.. Strin"8uilder+): creates an empty string Juilder with the initial capacity o" .=. 3. Strin"8uilder+Strin" str): creates a string Juilder with the speci"ied string. 5. Strin"8uilder+int len"th): creates an empty string Juilder with the speci"ied capacity as length.

Commonly used methods of Strin"8uilder class:


.. public Strin"8uilder append+Strin" s): is used to append the speci"ied string with this string. &he append ! method is overloaded like append char!, append boolean!, append int!, append "loat!, append double! etc. 3. public Strin"8uilder insert+int offset' Strin" s): is used to insert the speci"ied string with this string at the speci"ied position. &he insert ! method is overloaded like insert int, char!, insert int, boolean!, insert int, int!, insert int, "loat!, insert int, double! etc. 5. public Strin"8uilder replace+int startIndex' int endIndex' Strin" str): is used to replace the string "rom speci"ied startIndex and endIndex. 6. public Strin"8uilder delete+int startIndex' int endIndex): is used to delete the string "rom speci"ied startIndex and endIndex. :. public Strin"8uilder reverse+): is used to reverse the string. =. public int capacity+): is used to return the current capacity. ?. public void ensureCapacity+int minimumCapacity): is used to ensure the capacity at least e$ual to the given minimum. B. public char char!t+int index): is used to return the character at the speci"ied position. C. public int len"th+): is used to return the length o" the string i.e. total number o" characters. .D. public Strin" substrin"+int be"inIndex): is used to return the substring "rom the speci"ied beginIndex. ... public Strin" substrin"+int be"inIndex' int endIndex): is used to return the substring "rom the speci"ied beginIndex and endIndex.

simple pro"ram of Strin"8uilder class by append+) method


&he append ! method concatenates the given argument with this string. .. 3. 5. 6. :. class A2 public static void main -tring args;<!2 -tringJuilder sb>new -tringJuilder AGello A!4 sb.append AJavaA!499now original string is changed

=. ?. -ystem.out.println sb!499prints Gello Java B. 7 C. 7

Example of insert+) method of Strin"8uilder class


&he insert ! method inserts the given string with this string at the given position. .. 3. 5. 6. :. =. ?. B. C. class A2 public static void main -tring args;<!2 -tringJuilder sb>new -tringJuilder AGello A!4 sb.insert .,AJavaA!499now original string is changed -ystem.out.println sb!499prints GJavaello 7 7

Example of replace+) method of Strin"8uilder class


&he replace ! method replaces the given string "rom the speci"ied beginIndex and endIndex. .. 3. 5. 6. :. =. ?. B. C. class A2 public static void main -tring args;<!2 -tringJuilder sb>new -tringJuilder AGelloA!4 sb.replace .,5,AJavaA!4 -ystem.out.println sb!499prints GJavalo 7 7

Example of delete+) method of Strin"8uilder class


&he delete ! method o" -tringJuilder class deletes the string "rom the speci"ied beginIndex to endIndex. .. 3. 5. 6. :. =. ?. class A2 public static void main -tring args;<!2 -tringJuilder sb>new -tringJuilder AGelloA!4 sb.delete .,5!4 -ystem.out.println sb!499prints Glo

B. 7 C. 7

Example of reverse+) method of Strin"8uilder class


&he reverse ! method o" -tringJuilder class reverses the current string. .. 3. 5. 6. :. =. ?. B. C. class A2 public static void main -tring args;<!2 -tringJuilder sb>new -tringJuilder AGelloA!4 sb.reverse !4 -ystem.out.println sb!499prints olleG 7 7

Example of capacity+) method of Strin"8uilder class


&he capacity ! method o" -tringJuilder class returns the current capacity o" the Juilder. &he de"ault capacity o" the Juilder is .=. I" the number o" character increases "rom its current capacity, it increases the capacity by oldcapacityI3!@3. For example i" your current capacity is .=, it will be .=I3!@3>56. .. class A2 3. public static void main -tring args;<!2 5. 6. -tringJuilder sb>new -tringJuilder !4 :. -ystem.out.println sb.capacity !!499de"ault .= =. ?. sb.append AGelloA!4 B. -ystem.out.println sb.capacity !!499now .= C. .D. sb.append Ajava is my "avourite languageA!4 ... -ystem.out.println sb.capacity !!499now .=I3!@3>56 i.e oldcapacityI3!@3 .3. 7 .5. 7

Example of ensureCapacity+) method of Strin"8uilder class


&he ensure,apacity ! method o" -tringJuilder class ensures that the given capacity is the minimum to the current capacity. I" it is greater than the current capacity, it increases the capacity by oldcapacityI3!@3. For example i" your current capacity is .=, it will be .=I3!@3>56. .. class A2

3. public static void main -tring args;<!2 5. 6. -tringJuilder sb>new -tringJuilder !4 :. -ystem.out.println sb.capacity !!499de"ault .= =. ?. sb.append AGelloA!4 B. -ystem.out.println sb.capacity !!499now .= C. .D. sb.append Ajava is my "avourite languageA!4 ... -ystem.out.println sb.capacity !!499now .=I3!@3>56 i.e oldcapacityI3!@3 .3. .5. sb.ensure,apacity .D!499now no change .6. -ystem.out.println sb.capacity !!499now 56 .:. .=. sb.ensure,apacity :D!499now 56I3!@3 .?. -ystem.out.println sb.capacity !!499now ?D .B. .C. 7 3D. 7

1nderstandin" toStrin"+) method


I" you want to represent any object as a string, toStrin"+) method comes into existence. &he to-tring ! method returns the string representation o" the object. I" you print any object, java compiler internally invokes the to-tring ! method on the object. -o overriding the to-tring ! method, returns the desired output, it can be the state o" an object etc. depends on your implementation.

Advantage of the toString$" method


Jy overriding the to-tring ! method o" the #bject class, we can return values o" the object, so we donEt need to write much code.

1nderstandin" problem #ithout toStrin"+) method


KetEs see the simple code that prints re"erence. .. class -tudent2 3. int rollno4 5. -tring name4 6. -tring city4 :. =. -tudent int rollno, -tring name, -tring city!2 ?. this.rollno>rollno4 B. this.name>name4

C. this.city>city4 .D. 7 ... .3. public static void main -tring args;<!2 .5. -tudent s.>new -tudent .D.,A+ajA,AlucknowA!4 .6. -tudent s3>new -tudent .D3,A'ijayA,AghaFiabadA!4 .:. .=. -ystem.out.println s.!499compiler writes here s..to-tring ! .?. -ystem.out.println s3!499compiler writes here s3.to-tring ! .B. 7 .C. 7
Output:1tudent61#ee5#c 1tudent61eed,35

As you can see in the above example, printing s. and s3 prints the hashcode values o" the objects but I want to print the values o" these objects. -ince java compiler internally calls to-tring ! method, overriding this method will return the speci"ied values. KetEs understand it with the example given below:

Example of toStrin"+) method


Oow letEs see the real example o" to-tring ! method. .. class -tudent2 3. int rollno4 5. -tring name4 6. -tring city4 :. =. -tudent int rollno, -tring name, -tring city!2 ?. this.rollno>rollno4 B. this.name>name4 C. this.city>city4 .D. 7 ... .3. public -tring to-tring !299overriding the to-tring ! method .5. return rollno@A A@name@A A@city4 .6. 7 .:. public static void main -tring args;<!2 .=. -tudent s.>new -tudent .D.,A+ajA,AlucknowA!4 .?. -tudent s3>new -tudent .D3,A'ijayA,AghaFiabadA!4 .B. .C. -ystem.out.println s.!499compiler writes here s..to-tring ! 3D. -ystem.out.println s3!499compiler writes here s3.to-tring ! 3.. 7 33. 7

Strin"-okeni/er in Java

.. -tring&okeniFer 3. (ethods o" -tring&okeniFer 5. )xample o" -tring&okeniFer &he java.util.Strin"-okeni/er class allows you to break a string into tokens. It is simple way to break string. It doesnEt provide the "acility to di""erentiate numbers, $uoted strings, identi"iers etc. like -tream&okeniFer class. 8e will discuss about the -tream&okeniFer class in I9# chapter. Constructors of Strin"-okeni/er class &here are 5 constructors de"ined in the -tring&okeniFer class. Constructor -tring&okeniFer -tring str! -tring&okeniFer -tring str, -tring delim! -tring&okeniFer -tring str, -tring delim, boolean return'alue! &escription creates -tring&okeniFer with speci"ied string. creates -tring&okeniFer with speci"ied string and delimeter. creates -tring&okeniFer with speci"ied string, delimeter and return'alue. I" return value is true, delimiter characters are considered to be tokens. I" it is "alse, delimiter characters serve to separate tokens.

ethods of Strin"-okeni/er class &he = use"ul methods o" -tring&okeniFer class are as "ollows: .ublic method boolean has(ore&okens ! &escription checks i" there is more tokens available. returns the next token "rom the -tring&okeniFer -tring next&oken ! object. -tring next&oken -tring delim! returns the next token based on the delimeter. boolean has(ore)lements ! same as has(ore&okens ! method. #bject next)lement ! same as next&oken ! but its return type is #bject. int count&okens ! returns the total number o" tokens.

Simple example of Strin"-okeni/er class


KetEs see the simple example o" -tring&okeniFer class that tokeniFes a string Amy name is khanA on the basis o" whitespace. .. import java.util.-tring&okeniFer4 3. public class -imple2 5. public static void main -tring args;<!2 6. -tring&okeniFer st > new -tring&okeniFer Amy name is khanA,A A!4 :. while st.has(ore&okens !! 2

=. -ystem.out.println st.next&oken !!4 ?. 7 B. 7 C. 7


Output:my name is khan

Example of next-oken+Strin" delim) method of Strin"-okeni/er class


.. import java.util.I4 3. 5. public class &est 2 6. public static void main -tring;< args! 2 :. -tring&okeniFer st > new -tring&okeniFer Amy,name,is,khanA!4 =. ?. 99 printing next token B. -ystem.out.println AOext token is : A @ st.next&oken A,A!!4 C. 7 .D. 7
Output:4e7t token is ! my

Exception Aandlin" in Java


&he exception handling is one o" the power"ul mechanism provided in java. It provides the mechanism to handle the runtime errors so that normal "low o" the application can be maintained. In this page, we will know about exception, its type and the di""erence between checked and unchecked exceptions.

Exception

&ictionary eanin":)xception is an abnormal condition. In java, exception is an event that disrupts the normal "low o" the program. It is an object which is thrown at runtime.

Exception Aandlin"
)xception Gandling is a mechanism to handle runtime errors.

!dvanta"e of Exception Aandlin"

&he core advantage o" exception handling is that normal "low o" the application is maintained. )xception normally disrupts the normal "low o" the application that is why we use exception handling. KetEs take a scenario:

%o Lou Hnow N 8hat is the di""erence between checked and unchecked exceptions N 8hat happens behind the code int data>:D9D4 N 8hy use multiple catch block N Is there any possibility when "inally block is not executed N 8hat is exception propagation N 8hat is the di""erence between throw and throws keyword N

8hat are the 6 rules "or using exception handling with method overriding N

Aierarchy of Exception classes

-ypes of Exception:
&here are mainly two types o" exceptions: checked and unchecked where error is considered as unchecked exception. &he sun microsystem says there are three types o" exceptions:

.. ,hecked )xception 3. Pnchecked )xception 5. )rror

$hat is the difference bet#een checked and unchecked exceptions % ()Checked Exception
&he classes that extend &hrowable class except +untime)xception and )rror are known as checked exceptions e.g.I#)xception, -SK)xception etc. ,hecked exceptions are checked at compileMtime.

3)1nchecked Exception
&he classes that extend +untime)xception are known as unchecked exceptions e.g. Arithmetic)xception, Oull*ointer)xception, ArrayIndex#ut#"Jounds)xception etc. Pnchecked exceptions are not checked at compileMtime rather they are checked at runtime.

6)Error
)rror is irrecoverable e.g. #ut#"(emory)rror, 'irtual(achine)rror, Assertion)rror etc.

Common scenarios of Exception Aandlin" #here exceptions may occur


&here are given some scenarios where unchecked exceptions can occur. &hey are as "ollows:

() Scenario #here !rithmeticException occurs


I" we divide any number by Fero, there occurs an Arithmetic)xception. .. int a>:D9D499Arithmetic)xception

3) Scenario #here 9ull.ointerException occurs


I" we have null value in any variable, per"orming any operation by the variable occurs an Oull*ointer)xception. .. -tring s>null4 3. -ystem.out.println s.length !!499Oull*ointer)xception

6) Scenario #here 9umber7ormatException occurs

&he wrong "ormatting o" any value, may occur OumberFormat)xception. -uppose I have a string variable that have characters, converting this variable into digit will occur OumberFormat)xception. .. -tring s>AabcA4 3. int i>Integer.parseInt s!499OumberFormat)xception

:) Scenario #here !rrayIndexOutOf8oundsException occurs


I" you are inserting any value in the wrong index, it would result ArrayIndex#ut#"Jounds)xception as shown below: .. int a;<>new int;:<4 3. a;.D<>:D4 99ArrayIndex#ut#"Jounds)xception

7ive key#ords used in Exception handlin":


.. 3. 5. 6. try catch "inally throw

:. throws

try block
)nclose the code that might throw an exception in try block. It must be used within the method and must be "ollowed by either catch or "inally block. Syntax of try #ith catch block .. try2 3. ... 5. 7catch )xception0class0Oame re"erence!27 Syntax of try #ith finally block .. try2 3. ... 5. 7"inally27

catch block
,atch block is used to handle the )xception. It must be used a"ter the try block.

.roblem #ithout exception handlin"


.. class -imple2 3. public static void main -tring args;<!2 5. int data>:D9D4 6. :. -ystem.out.println Arest o" the code...A!4 =. 7 ?. 7
Output:+7ce tion in thread main (ava.lan%.Arithmetic+7ce tion!8 .y 9ero

As displayed in the above example, rest o" the code is not executed i.e. rest o" the code... statement is not printed. KetEs see what happens behind the scene:

$hat happens behind the code int a=BCDCE


&he J'( "irstly checks whether the exception is handled or not. I" exception is not handled, J'( provides a de"ault exception handler that per"orms the "ollowing tasks: *rints out exception description. *rints the stack trace Gierarchy o" methods where the exception occurred!. ,auses the program to terminate. Jut i" exception is handled by the application programmer, normal "low o" the application is maintained i.e. rest o" the code is executed.

Solution by exception handlin"


.. class -imple2 3. public static void main -tring args;<!2 5. try2 6. int data>:D9D4 :. =. 7catch Arithmetic)xception e!2-ystem.out.println e!47 ?. B. -ystem.out.println Arest o" the code...A!4 C. 7 .D. 7
Output:+7ce tion in thread main (ava.lan%.Arithmetic+7ce tion!8 .y 9ero rest o# the code...

Oow, as displayed in the above example, rest o" the code is executed i.e. rest o" the code... statement is printed.

ultiple catch block:


I" you have to per"orm di""erent tasks at the occrence o" di""erent )xceptions, use multple catch block. .. /b1/i1)xample o" multiple catch block/9i1/9b1 3. 5. class )xcep62 6. public static void main -tring args;<!2 :. try2 =. int a;<>new int;:<4 ?. a;:<>5D9D4 B. 7 C. catch Arithmetic)xception e!2-ystem.out.println Atask. is completedA!47 .D. catch ArrayIndex#ut#"Jounds)xception e!2-ystem.out.println Atask 3 com pletedA!47 ... catch )xception e!2-ystem.out.println Acommon task completedA!47 .3. .5. -ystem.out.println Arest o" the code...A!4 .6. 7 .:. 7
Output:task1 com leted rest o# the code...

9ested try block:


try block within a try block is known as nested try block.

$hy use nested try block%


-ometimes a situation may arise where a part o" a block may cause one error and the entire block itsel" may cause another error. In such cases, exception handlers have to be nested

Syntax:
.. .... 3. try 5. 2 6. statement .4 :. statement 34 =. try ?. 2 B. statement .4

C. statement 34 .D. 7 ... catch )xception e! .3. 2 .5. 7 .6. 7 .:. catch )xception e! .=. 2 .?. 7 .B. ....

Example:
.. /b1/i1)xample o" nested try block/9i1/9b1 3. 5. class )xcep=2 6. public static void main -tring args;<!2 :. try2 =. try2 ?. -ystem.out.println Agoing to divideA!4 B. int b >5C9D4 C. 7catch Arithmetic)xception e!2-ystem.out.println e!47 .D. ... try2 .3. int a;<>new int;:<4 .5. a;:<>64 .6. 7catch ArrayIndex#ut#"Jounds)xception e!2-ystem.out.println e!47 .:. .=. -ystem.out.println Aother statement!4 .?. 7catch )xception e!2-ystem.out.println AhandeledA!47 .B. .C. -ystem.out.println Anormal "low..A!4 3D. 7 3.. 7

finally block
&he "inally block is a block that is always executed. It is mainly used to per"orm some important tasks such as closing connection, stream etc.

9ote:Je"ore terminating the program, J'( executes "inally block i" any!. 9ote:"inally must be "ollowed by try or catch block.

$hy use finally block%

"inally block can be used to put AcleanupA code such as closing a "ile,closing connection etc.

case (
Program in case exception does not occur .. class -imple2 3. public static void main -tring args;<!2 5. try2 6. int data>3:9:4

:. -ystem.out.println data!4 =. 7 ?. catch Oull*ointer)xception e!2-ystem.out.println e!47 B. C. "inally2-ystem.out.println A"inally block is always executedA!47 .D. ... -ystem.out.println Arest o" the code...A!4 .3. 7 .5. 7
Output:5 #inally .lock is al'ays e7ecuted rest o# the code...

case 3
Program in case exception occured but not handled .. class -imple2 3. public static void main -tring args;<!2 5. try2 6. int data>3:9D4 :. -ystem.out.println data!4 =. 7 ?. catch Oull*ointer)xception e!2-ystem.out.println e!47 B. C. "inally2-ystem.out.println A"inally block is always executedA!47 .D. ... -ystem.out.println Arest o" the code...A!4 .3. 7 .5. 7
Output:#inally .lock is al'ays e7ecuted +7ce tion in thread main (ava.lan%.Arithmetic+7ce tion!8 .y 9ero

case 6
Program in case exception occured and handled .. class -imple2 3. public static void main -tring args;<!2 5. try2 6. int data>3:9D4 :. -ystem.out.println data!4 =. 7 ?. catch Arithmetic)xception e!2-ystem.out.println e!47 B. C. "inally2-ystem.out.println A"inally block is always executedA!47 .D. ... -ystem.out.println Arest o" the code...A!4

.3. 7 .5. 7
Output:+7ce tion in thread main (ava.lan%.Arithmetic+7ce tion!8 .y 9ero #inally .lock is al'ays e7ecuted rest o# the code...

thro# key#ord
&he throw keyword is used to explictily throw an exception. 8e can throw either checked or uncheked exception. &he throw keyword is mainly used to throw custom exception. 8e will see custom exceptions later.

Example of thro# key#ord


In this example, we have created the validate method that takes integer value as a parameter. I" the age is less than .B, we are throwing the Arithmetic)xception otherwise print a message welcome to vote. .. class )xcep.52 3. 5. static void validate int age!2 6. i" age/.B! :. throw new Arithmetic)xception Anot validA!4 =. else ?. -ystem.out.println Awelcome to voteA!4 B. 7 C. .D. public static void main -tring args;<!2 ... validate .5!4 .3. -ystem.out.println Arest o" the code...A!4 .5. 7 .6. 7
Output:+7ce tion in thread main (ava.lan%.Arithmetic+7ce tion!not valid

thro#s key#ord
&he thro#s key#ord is used to declare an exception. It gives an in"ormation to the programmer that there may occur an exception so it is better "or the programmer to provide the exception handling code so that normal "low can be maintained. )xception Gandling is mainly used to handle the checked exceptions. I" there occurs any unchecked exception such as Oull*ointer)xception, it is programmers "ault that he is not per"orming check up be"ore the code being used.

Syntax of thro#s key#ord:


.. void method0name ! throws exception0class0name2 3. ... 5. 7

*ue) $hich exception should #e declare%


!ns) checked exception only, because: unchecked Exception: under your control so correct your code.

error: beyond your control e.g. you are unable to do anything i" there occurs 'irtual(achine)rror or -tack#ver"low)rror.

!dvanta"e of thro#s key#ord:


Oow ,hecked )xception can be propagated "orwarded in call stack!. Program which describes that checked exceptions can be propagated by throws keyword. .. import java.io.I#)xception4 3. class -imple2 5. void m !throws I#)xception2 6. throw new I#)xception Adevice errorA!499checked exception :. 7 =. void n !throws I#)xception2 ?. m !4 B. 7 C. void p !2 .D. try2 ... n !4 .3. 7catch )xception e!2-ystem.out.println Aexception handledA!47 .5. 7 .6. public static void main -tring args;<!2 .:. -imple obj>new -imple !4 .=. obj.p !4 .?. -ystem.out.println Anormal "low...A!4 .B. 7 .C. 7
Output:e7ce tion handled normal #lo'...

,ule: If you are callin" a method that declares an exception' you must either cau"ht or declare the exception.

&here are two cases: .. Case(:Lou caught the exception i.e. handle the exception using try9catch. 3. Case3:Lou declare the exception i.e. speci"ying throws with the method.

Case(: Fou handle the exception

In case you handle the exception, the code will be executed "ine whether exception occurs during the program or not.

.. import java.io.I4 3. class (2 5. void method !throws I#)xception2 6. throw new I#)xception Adevice errorA!4 :. 7 =. 7 ?. B. C. class &est2 .D. public static void main -tring args;<!2 ... try2 .3. &est t>new &est !4 .5. t.method !4 .6. 7catch )xception e!2-ystem.out.println Aexception handledA!47 .:. .=. -ystem.out.println Anormal "low...A!4 .?. 7 .B. 7
Output:e7ce tion handled normal #lo'...

Case3: Fou declare the exception


A!In case you declare the exception, i" exception does not occur, the code will be executed "ine. J!In case you declare the exception i" exception occures, an exception will be thrown at runtime because throws does not handle the exception.

A)Program if exception does not occur .. import java.io.I4 3. class (2 5. void method !throws I#)xception2 6. -ystem.out.println Adevice operation per"ormedA!4 :. 7 =. 7 ?. B.

C. class &est2 .D. public static void main -tring args;<!throws I#)xception299declare exceptio n ... &est t>new &est !4 .3. t.method !4 .5. .6. -ystem.out.println Anormal "low...A!4 .:. 7 .=. 7
Output:device o eration normal #lo'... er#ormed

B)Program if exception occurs .. import java.io.I4 3. class (2 5. void method !throws I#)xception2 6. throw new I#)xception Adevice errorA!4 :. 7 =. 7 ?. B. C. class &est2 .D. public static void main -tring args;<!throws I#)xception299declare exceptio n ... &est t>new &est !4 .3. t.method !4 .5. .6. -ystem.out.println Anormal "low...A!4 .:. 7 .=. 7
Output::untime +7ce tion

&ifference bet#een thro# and thro#s:


thro# key#ord .!throw is used to explicitly throw an exception. 3!checked exception can not be propagated without throws. 5!throw is "ollowed by an instance. 6!throw is used within the method. thro#s key#ord throws is used to declare an exception.

checked exception can be propagated with throws. throws is "ollowed by class. throws is used with the method signature. Lou can declare multiple exception e.g. :!Lou cannot throw multiple exception public void method !throws I#)xception,-SK)xception.

Custom Exception
I" you are creating your own )xception that is known as custom exception or userM de"ined exception. .. class InvalidAge)xception extends )xception2 3. InvalidAge)xception -tring s!2 5. super s!4 6. 7 :. 7 .. class )xcep.52 3. 5. static void validate int age!throws InvalidAge)xception2 6. i" age/.B! :. throw new InvalidAge)xception Anot validA!4 =. else ?. -ystem.out.println Awelcome to voteA!4 B. 7 C. .D. public static void main -tring args;<!2 ... try2 .3. validate .5!4 .5. 7catch )xception m!2-ystem.out.println A)xception occured: A@m!47 .6. .:. -ystem.out.println Arest o" the code...A!4 .=. 7 .?. 7
Output:+7ce tion occured! -nvalidA%e+7ce tion!not valid rest o# the code...

@ife cycle of a -hread +-hread States)


A thread can be in one o" the "ive states in the thread. According to sun, there is only 6 states new, runnable, nonMrunnable and terminated. &here is no running state. Jut "or better understanding the threads, we are explaining it in the : states. &he li"e cycle o" the thread is controlled by J'(. &he thread states are as "ollows: .. Oew 3. +unnable 5. +unning 6. OonM+unnable Jlocked! :. &erminated

()9e#
&he thread is in new state i" you create an instance o" &hread class but be"ore the invocation o" start ! method.

3),unnable
&he thread is in runnable state a"ter invocation o" start ! method, but the thread scheduler has not selected it to be the running thread.

6),unnin"
&he thread is in running state i" the thread scheduler has selected it.

:)9on4,unnable +8locked)
&his is the state when the thread is still alive, but is currently not eligible to run.

B)-erminated

Ao# to create thread:

&here are two ways to create a thread: .. Jy extending &hread class 3. Jy implementing +unnable inter"ace.

-hread class:
&hread class provide constructors and methods to create and per"orm operations on a thread.&hread class extends #bject class and implements +unnable inter"ace.

Commonly used Constructors of -hread class:


&hread ! &hread -tring name! &hread +unnable r! &hread +unnable r,-tring name!

Commonly used methods of -hread class:


.. public void run+): is used to per"orm action "or a thread. 3. public void start+): starts the execution o" the thread.J'( calls the run ! method on the thread. 5. public void sleep+lon" miliseconds): ,auses the currently executing thread to sleep temporarily cease execution! "or the speci"ied number o" milliseconds. 6. public void join+): waits "or a thread to die. :. public void join+lon" miliseconds): waits "or a thread to die "or the speci"ied miliseconds. =. public int "et.riority+): returns the priority o" the thread. ?. public int set.riority+int priority): changes the priority o" the thread. B. public Strin" "et9ame+): returns the name o" the thread. C. public void set9ame+Strin" name): changes the name o" the thread. .D. public -hread current-hread+): returns the re"erence o" currently executing thread. ... public int "etId+): returns the id o" the thread. .3. public -hread.State "etState+): returns the state o" the thread. .5. public boolean is!live+): tests i" the thread is alive. .6. public void yield+): causes the currently executing thread object to temporarily pause and allow other threads to execute. .:. public void suspend+): is used to suspend the thread depricated!. .=. public void resume+): is used to resume the suspended thread depricated!. .?. public void stop+): is used to stop the thread depricated!. .B. public boolean is&aemon+): tests i" the thread is a daemon thread. .C. public void set&aemon+boolean b): marks the thread as daemon or user thread. 3D. public void interrupt+): interrupts the thread. 3.. public boolean isInterrupted+): tests i" the thread has been interrupted. 33. public static boolean interrupted+): tests i" the current thread has been

interrupted.

,unnable interface:
&he +unnable inter"ace should be implemented by any class whose instances are intended to be executed by a thread. +unnable inter"ace have only one method named run !. .. public void run+): is used to per"orm action "or a thread.

Startin" a thread:
start+) method o" &hread class is used to start a newly created thread. It per"orms "ollowing tasks: A new thread starts with new callstack!. &he thread moves "rom Oew state to the +unnable state.

8hen the thread gets a chance to execute, its target run ! method will run.

()8y extendin" -hread class:


.. 3. 5. 6. :. =. ?. B. C. class (ulti extends &hread2 public void run !2 -ystem.out.println Athread is running...A!4 7 public static void main -tring args;<!2 (ulti t.>new (ulti !4 t..start !4 7 7

Output:thread is runnin%...

$ho makes your class object as thread object%


-hread class constructor allocates a new thread object.8hen you create object o" (ulti class,your class constructor is invoked provided by ,ompiler! "romwhere &hread class constructor is invoked by super ! as "irst statement!.-o your (ulti class object is thread object now.

3)8y implementin" the ,unnable interface:


.. 3. 5. 6. :. class (ulti5 implements +unnable2 public void run !2 -ystem.out.println Athread is running...A!4 7

=. public static void main -tring args;<!2 ?. (ulti5 m.>new (ulti5 !4 B. &hread t. >new &hread m.!4 C. t..start !4 .D. 7 ... 7
Output:thread is runnin%...

I" you are not extending the &hread class,your class object would not be treated as a thread object.-o you need to explicitely create &hread class object.8e are passing the object o" your class that implements +unnable so that your class run ! method may execute.

.riority of a -hread +-hread .riority):


)ach thread have a priority. *riorities are represented by a number between . and .D. In most cases, thread schedular schedules the threads according to their priority known as preemptive scheduling!. Jut it is not guaranteed because it depends on J'( speci"i"ication that which sheduling it chooses.

% constants defiend in &hread class'


.. public static int (IO0*+I#+I&L 3. public static int O#+(0*+I#+I&L 5. public static int (AT0*+I#+I&L %e"ault priority o" a thread is : O#+(0*+I#+I&L!. &he value o" (IO0*+I#+I&L is . and the value o" (AT0*+I#+I&L is .D.

Example of priority of a -hread:


.. class (ulti.D extends &hread2 3. public void run !2 5. -ystem.out.println Arunning thread name is:A@&hread.current&hread !.getOa me !!4 6. -ystem.out.println Arunning thread priority is:A@&hread.current&hread !.get* riority !!4 :. =. 7 ?. public static void main -tring args;<!2 B. (ulti.D m.>new (ulti.D !4 C. (ulti.D m3>new (ulti.D !4 .D. m..set*riority &hread.(IO0*+I#+I&L!4 ... m3.set*riority &hread.(AT0*+I#+I&L!4 .3. m..start !4 .5. m3.start !4 .6. .:. 7

.=. 7
Output:runnin% runnin% runnin% runnin% thread name is!*hread20 thread riority is!10 thread name is!*hread21 thread riority is!1

&aemon -hread
&here are two types o" threads user thread and daemon thread. &he daemon thread is a service provider thread. It provides services to the user thread. Its li"e depends on the user threads i.e. when all the user threads dies, J'( termintates this thread automatically.

(oints to remem er for )aemon &hread'


It provides services to user threads "or background supporting tasks. It has no role in li"e than to serve user threads. Its li"e depends on user threads. It is a low priority thread.

$hy JG termintates the daemon thread if there is no user thread remainin"%


&he sole purpose o" the daemon thread is that it provides services to user thread "or background supporting task. I" there is no user thread, why should J'( keep running this thread. &hat is why J'( terminates the daemon thread i" there is no user thread.

ethods for &aemon thread:


&he java.lang.&hread class provides two methods related to daemon thread public void set&aemon+boolean status): is used to mark the current thread as daemon thread or user thread.

public boolean is&aemon+): is used to check that current is daemon.

Simple example of &aemon thread:


.. class (y&hread extends &hread2 3. public void run !2 5. -ystem.out.println AOame: A@&hread.current&hread !.getOame !!4 6. -ystem.out.println A%aemon: A@&hread.current&hread !.is%aemon !!4 :. 7 =. ?. public static void main -tring;< args!2 B. (y&hread t.>new (y&hread !4 C. (y&hread t3>new (y&hread !4

.D. t..set%aemon true!4 ... .3. t..start !4 .5. t3.start !4 .6. 7 .:. 7
Output:4ame! thread20 ;aemon! true 4ame! thread21 ;aemon! #alse

9ote: If you #ant to make a user thread as &aemon' it must not be started other#ise it #ill thro# Ille"al-hreadStateException. .. class (y&hread extends &hread2 3. public void run !2 5. -ystem.out.println AOame: A@&hread.current&hread !.getOame !!4 6. -ystem.out.println A%aemon: A@&hread.current&hread !.is%aemon !!4 :. 7 =. ?. public static void main -tring;< args!2 B. (y&hread t.>new (y&hread !4 C. (y&hread t3>new (y&hread !4 .D. t..start !4 ... t..set%aemon true!499will throw exception here .3. t3.start !4 .5. 7 .6. 7
Output:e7ce tion in thread main! (ava.lan%.-lle%al*hread1tate+7ce tion

Synchroni/ation
-ynchroniFation is the capabilility o" control the access o" multiple threads to any shared resource. -ynchroniFation is better in case we want only one thread can access the shared resource at a time.

$hy use Synchroni/ation%


&he synchroniFation is mainly used to .. &o prevent thread inter"erence. 3. &o prevent consistency problem.

-ypes of Synchroni/ation

&here are two types o" synchroniFation .. *rocess -ynchroniFation 3. &hread -ynchroniFation Gere, we will discuss only thread synchroniFation.

-hread Synchroni/ation
&here are two types o" thread synchroniFation mutual exclusive and interMthread communication.

(utual )xclusive .. -ynchroniFed method. 3. -ynchroniFed block. 5. static synchroniFation. ,ooperation InterMthread communication!

utual Exclusive
(utual )xclusive helps keep threads "rom inter"ering with one another while sharing data. &his can be done by three ways in java: .. by synchroniFed method 3. by synchroniFed block 5. by static synchroniFation

1nderstandin" the concept of @ock


-ynchroniFation is built around an internal entity known as the lock or monitor.)very object has an lock associated with it. Jy convention, a thread that needs consistent access to an objectEs "ields has to ac$uire the objectEs lock be"ore accessing them, and then release the lock when itEs done with them. From Java : the package java.util.concurrent.locks contains several lock implementations.

1nderstandin" the problem #ithout Synchroni/ation


In this example, there is no synchroniFation, so output is inconsistent. KetEs see the example: .. ,lass &able2 3. 5. void print&able int n!299method not synchroniFed 6. "or int i>.4i/>:4i@@!2 :. -ystem.out.println nIi!4 =. try2 ?. &hread.sleep 6DD!4

B. 7catch )xception e!2-ystem.out.println e!47 C. 7 .D. ... 7 .3. 7 .5. .6. class (y&hread. extends &hread2 .:. &able t4 .=. (y&hread. &able t!2 .?. this.t>t4 .B. 7 .C. public void run !2 3D. t.print&able :!4 3.. 7 33. 35. 7 36. class (y&hread3 extends &hread2 3:. &able t4 3=. (y&hread3 &able t!2 3?. this.t>t4 3B. 7 3C. public void run !2 5D. t.print&able .DD!4 5.. 7 53. 7 55. 56. class Pse2 5:. public static void main -tring args;<!2 5=. &able obj > new &able !499only one object 5?. (y&hread. t.>new (y&hread. obj!4 5B. (y&hread3 t3>new (y&hread3 obj!4 5C. t..start !4 6D. t3.start !4 6.. 7 63. 7
Output: 5 100 10 200 15 300 20 400 25 500

Solution by synchroni/ed method

I" you declare any method as synchroniFed, it is known as synchroniFed method.

-ynchroniFed method is used to lock an object "or any shared resource. 8hen a thread invokes a synchroniFed method, it automatically ac$uires the lock "or that object and releases it when the method returns.

.. /b1/i199*rogram o" synchroniFed method/9i1/9b1 3. 5. ,lass &able2 6. :. synchroniFed void print&able int n!299synchroniFed method =. "or int i>.4i/>:4i@@!2 ?. -ystem.out.println nIi!4 B. try2 C. &hread.sleep 6DD!4 .D. 7catch )xception e!2-ystem.out.println e!47 ... 7 .3. .5. 7 .6. 7 .:. .=. class (y&hread. extends &hread2 .?. &able t4 .B. (y&hread. &able t!2 .C. this.t>t4 3D. 7 3.. public void run !2 33. t.print&able :!4 35. 7 36. 3:. 7 3=. class (y&hread3 extends &hread2 3?. &able t4 3B. (y&hread3 &able t!2 3C. this.t>t4 5D. 7 5.. public void run !2 53. t.print&able .DD!4 55. 7 56. 7 5:. 5=. class Pse2 5?. public static void main -tring args;<!2 5B. &able obj > new &able !499only one object 5C. (y&hread. t.>new (y&hread. obj!4 6D. (y&hread3 t3>new (y&hread3 obj!4 6.. t..start !4 63. t3.start !4 65. 7 66. 7

Output: 5 10 15 20 25 100 200 300 400 500

Same Example of synchroni/ed method by usin" annonymous class


In this program, we have created the two threads by annonymous class, so less coding is re$uired. .. /b1/i199*rogram o" synchroniFed method by using annonymous class/9i1/9b 1 3. 5. ,lass &able2 6. :. synchroniFed void print&able int n!299synchroniFed method =. "or int i>.4i/>:4i@@!2 ?. -ystem.out.println nIi!4 B. try2 C. &hread.sleep 6DD!4 .D. 7catch )xception e!2-ystem.out.println e!47 ... 7 .3. .5. 7 .6. 7 .:. .=. class Pse2 .?. public static void main -tring args;<!2 .B. "inal &able obj > new &able !499only one object .C. 3D. (y&hread. t.>new (y&hread. !2 3.. public void run !2 33. obj.print&able :!4 35. 7 36. 74 3:. (y&hread. t3>new (y&hread. !2 3=. public void run !2 3?. obj.print&able .DD!4 3B. 7 3C. 74 5D. 5.. t..start !4 53. t3.start !4 55. 7

56. 7
Output: 5 10 15 20 25 100 200 300 400 500
I9#

OutputStream class
#utput-tream class ia an abstract class.It is the superclass o" all classes representing an output stream o" bytes. An output stream accepts output bytes and sends them to some sink.

Commonly used methods of OutputStream class


ethod () public void #rite+int)thro#s IOException: 3) public void #rite+byteHI)thro#s IOException: 6) public void flush+)thro#s IOException: :) public void close+)thro#s IOException: &escription is used to write a byte to the current output stream. is used to write an array o" byte to the current output stream. "lushes the current output stream. is used to close the current output stream.

InputStream class

Input-tream class ia an abstract class.It is the superclass o" all classes representing an input stream o" bytes.

Commonly used methods of InputStream class


ethod () public abstract int read+)thro#s IOException: 3) public int available+)thro#s IOException: 6) public void close+)thro#s IOException: &escription reads the next byte o" data "rom the input stream.It returns M. at the end o" "ile. returns an estimate o" the number o" bytes that can be read "rom the current input stream. is used to close the current input stream.

7ileOutputStream class:
A File#utput-tream is an output stream "or writing data to a "ile. I" you have to write primitive values then use File#utput-tream.Instead, "or characterM oriented data, pre"er File8riter.Jut you can write byteMoriented as well as characterM oriented data.

Example of 7ileOutputStream class:


.. 99/b1/i1-imple program o" writing data into the "ile/9i1/9b1 3. 5. 6. import java.io.I4 :. class &est2 =. public static void main -tring args;<!2 ?. try2 B. File#utputstream "out>new File#utput-tream Aabc.txtA!4 C. -tring s>A-achin &endulkar is my "avourite playerA4 .D. ... byte b;<>s.getJytes !4 .3. "out.write b!4 .5. .6. "out.close !4 .:. .=. -ystem.out.println Asuccess...A!4 .?. 7catch )xception e!2system.out.println e!47 .B. 7 .C. 7
Output:success...

7ileInputStream class:
A FileInput-tream obtains input bytes "rom a "ile.It is used "or reading streams o" raw bytes such as image data. For reading streams o" characters, consider using File+eader. It should be used to read byteMoriented data.For example, to read image etc.

Example of 7ileInputStream class:


.. 99/b1/i1-imple program o" reading data "rom the "ile/9i1/9b1 3. 5. import java.io.I4 6. class -imple+ead2 :. public static void main -tring args;<!2 =. try2 ?. FileInput-tream "in>new FileInput-tream Aabc.txtA!4 B. int i4 C. while i>"r.read !!U>M.! .D. -ystem.out.println char!i!4 ... .3. "in.close !4 .5. 7catch )xception e!2system.out.println e!47 .6. 7 .:. 7 .. /strong1#utput:/9strong1-achin is my "avourite player.

Example of ,eadin" the data of current java file and #ritin" it into another file
8e can read the data o" any "ile using the FileInput-tream class whether it is java "ile, image "ile, video "ile etc. In this example, we are reading the data o" ,.java "ile and writing it into another "ile (.java. .. import java.io.I4 3. 5. class ,2 6. public static void main -tring args;<!throws )xception2 :. =. FileInput-tream "in>new FileInput-tream A,.javaA!4 ?. File#utput-tream "out>new File#utput-tream A(.javaA!4 B. C. int i>D4 .D. while i>"in.read !!U>M.!2 ... "out.write byte!i!4 .3. 7 .5. .6. "in.close !4 .:. 7 .=. 7

7ile$riter class:
File8riter class is used to write characterMoriented data to the "ile. -un (icrosystem has suggested not to use the FileInput-tream and File#utput-tream classes i" you have to read and write the textual in"ormation.

Example of 7ile$riter class:


In this example, we are writing the data in the "ile abc.txt. .. import java.io.I4 3. class -imple2 5. public static void main -tring args;<!2 6. try2 :. File8riter "w>new File8riter Aabc.txtA!4 =. "w.write Amy name is sachinA!4 ?. "w."lush !4 B. C. "w.close !4 .D. 7catch )xception e!2-ystem.out.println e!47 ... -ystem.out.println AsuccessA!4 .3. 7 .5. 7
Output:success...

7ile,eader class:

File+eader class is used to read data "rom the "ile.

Example of 7ile,eader class:


In this example, we are reading the data "rom the "ile abc.txt "ile. .. import java.io.I4 3. class -imple2 5. public static void main -tring args;<!throws )xception2 6. :. File+eader "r>new File+eader Aabc.txtA!4 =. int i4 ?. while i>"r.read !!U>M.! B. -ystem.out.println char!i!4 C. .D. "r.close !4 ... 7 .3. 7
Output:my name is sachin

,eadin" data from keyboard:


&here are many ways to read data "rom the keyboard. For example: Input-tream+eader ,onsole -canner

%ataInput-tream etc.

InputStream,eader class:
Input-tream+eader class can be used to read data "rom keyboard.It per"orms two tasks: connects to input stream o" keyboard

converts the byteMoriented stream into characterMoriented stream

8uffered,eader class:
Ju""ered+eader class can be used to read data line by line by readKine ! method.

Example of readin" data from keyboard by InputStream,eader and 8ufferd,eader class:


In this example, we are connecting the Ju""ered+eader stream with the

Input-tream+eader stream "or reading the line by line data "rom the keyboard.
88Program of reading data im ort (ava.io.<= class >5? u.lic static void main(1trin% ar%s@A)thro's +7ce tion? -n ut1tream:eader rBne' -n ut1tream:eader(1ystem.in)= "u##ered:eader .rBne' "u##ered:eader(r)= 1ystem.out. rintln(C+nter ur nameC)= 1trin% nameB.r.readDine()= 1ystem.out. rintln(C0elcome CEname)= F F Output:+nter ur name Amit 0elcome Amit

!nother Example of readin" data from keyboard by InputStream,eader and 8ufferd,eader class until the user #rites stop
In this example, we are reading and printing the data until the user prints stop.
im ort (ava.io.<= class >5? u.lic static void main(1trin% ar%s@A)thro's +7ce tion? -n ut1tream:eader rBne' -n ut1tream:eader(1ystem.in)= "u##ered:eader .rBne' "u##ered:eader(r)= 1trin% nameBCC= 'hile(name.eGuals(Csto C))? 1ystem.out. rintln(C+nter data! C)= nameB.r.readDine()= 1ystem.out. rintln(Cdata is! CEname)= F .r.close()= r.close()=

F F Output:+nter data! Amit data is! Amit +nter data! 10 data is! 10 +nter data! sto data is! sto

Example of java.util.Scanner class:


KetEs see the simple example o" the -canner class which reads the int, string and double value as an input: .. import java.util.-canner4 3. class -canner&est2 5. public static void main -tring args;<!2 6. :. -canner sc>new -canner -ystem.in!4 =. ?. -ystem.out.println A)nter your rollnoA!4 B. int rollno>sc.nextInt !4 C. -ystem.out.println A)nter your nameA!4 .D. -tring name>sc.next !4 ... -ystem.out.println A)nter your "eeA!4 .3. double "ee>sc.next%ouble !4 .5. .6. -ystem.out.println A+ollno:A@rollno@A name:A@name@A "ee:A@"ee!4 .:. .=. 7 .?. 7 download this scanner example
Output:+nter your rollno 111 +nter your name :atan +nter 450000 :ollno!111 name!:atan #ee!450000

!pplet
Applet is a special type o" program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side.

!dvanta"e of !pplet
&here are many advantages o" applet. &hey are as "ollows: It works at client side so less response time.

-ecured It can be executed by browsers running under many plate"orms, including Kinux, 8indows, (ac #s etc.

&ra#back of !pplet

*lugin is re$uired at client browser to execute applet.

Aierarchy of !pplet

As displayed in the above diagram, Applet class extends *anel. *anel class extends ,ontainer which is the subclass o" ,omponent.

@ifecycle of an !pplet:
.. 3. 5. 6. Applet is initialiFed. Applet is started. Applet is painted. Applet is stopped.

:. Applet is destroyed.

@ifecycle methods for !pplet:

&he java.applet.Applet class 6 li"e cycle methods and java.awt.,omponent class provides . li"e cycle methods "or an applet.

java.applet.!pplet class:
For creating any applet java.applet.Applet class must be inherited. It provides 6 li"e cycle methods o" applet. .. public void init+): is used to initialiFed the Applet. It is invoked only once. 3. public void start+): is invoked a"ter the init ! method or browser is maximiFed. It is used to start the Applet. 5. public void stop+): is used to stop the Applet. It is invoked when Applet is stop or browser is minimiFed. 6. public void destroy+): is used to destroy the Applet. It is invoked only once.

java.a#t.Component class:
&he ,omponent class provides . li"e cycle method o" applet. .. public void paint+Jraphics "): is used to paint the Applet. It provides Rraphics class object that can be used "or drawing oval, rectangle, arc etc.

$ho is responsible to mana"e the life cycle of an applet%


Java *lugMin so"tware.

Ao# to run an !pplet%


&here are two ways to run an applet .. Jy html "ile. 3. Jy applet'iewer tool "or testing purpose!.

Simple example of !pplet by html file:


&o execute the applet by html "ile, create an applet and compile it. A"ter that create an html "ile and place the applet code in html "ile. Oow click the html "ile. .. 99First.java 3. import java.applet.Applet4 5. import java.awt.Rraphics4 6. public class First extends Applet2 :. =. public void paint Rraphics g!2 ?. g.draw-tring AwelcomeA,.:D,.:D!4 B. 7 C. .D. 7

9ote: class must be public because its object is created by Java .lu"in soft#are that resides on the bro#ser.

myapplet.html
.. 3. 5. 6. :. =. /html1 /body1 /applet code>AFirst.classA width>A5DDA height>A5DDA1 /9applet1 /9body1 /9html1

@ive &emo:

Simple example of !pplet by appletvie#er tool:


&o execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. A"ter that run it by: appletviewer First.java. Oow Gtml "ile is not re$uired but it is "or testing purpose only. .. 99First.java 3. import java.applet.Applet4 5. import java.awt.Rraphics4 6. public class First extends Applet2 :. =. public void paint Rraphics g!2 ?. g.draw-tring Awelcome to appletA,.:D,.:D!4 B. 7 C. .D. 7 ... 9I .3. /applet code>AFirst.classA width>A5DDA height>A5DDA1 .5. /9applet1 .6. I9 &o execute the applet by appletviewer tool, write in command prompt:
c:\>(avac First.(ava c:\>a letvie'er First.(ava

&isplayin" Jraphics in !pplet


java.awt.Rraphics class provides many methods "or graphics programming.

*ommonly used methods of +raphics class'


.. public abstract void dra#Strin"+Strin" str' int x' int y): is used to draw the speci"ied string.

3. public void dra#,ect+int x' int y' int #idth' int hei"ht): draws a rectangle with the speci"ed width and height. 5. public abstract void fill,ect+int x' int y' int #idth' int hei"ht): is used to "ill rectangle with the de"ault color and speci"ied width and height. 6. public abstract void dra#Oval+int x' int y' int #idth' int hei"ht): is used to draw oval with the speci"ied width and height. :. public abstract void fillOval+int x' int y' int #idth' int hei"ht): is used to "ill oval with the de"ault color and speci"ied width and height. =. public abstract void dra#@ine+int x(' int y(' int x3' int y3): is used to draw line between the points x., y.! and x3, y3!. ?. public abstract boolean dra#Ima"e+Ima"e im"' int x' int y' Ima"eObserver observer): is used draw the speci"ied image. B. public abstract void dra#!rc+int x' int y' int #idth' int hei"ht' int start!n"le' int arc!n"le): is used draw a circular or elliptical arc. C. public abstract void fill!rc+int x' int y' int #idth' int hei"ht' int start!n"le' int arc!n"le): is used to "ill a circular or elliptical arc. .D. public abstract void setColor+Color c): is used to set the graphics current color to the speci"ied color. ... public abstract void set7ont+7ont font): is used to set the graphics current "ont to the speci"ied "ont.

,xample of +raphics in applet'


.. import java.applet.Applet4 3. import java.awt.I4 5. 6. public class Rraphics%emo extends Applet2 :. =. public void paint Rraphics g!2 ?. g.set,olor ,olor.red!4 B. g.draw-tring A8elcomeA,:D, :D!4 C. g.drawKine 3D,5D,3D,5DD!4 .D. g.draw+ect ?D,.DD,5D,5D!4 ... g."ill+ect .?D,.DD,5D,5D!4 .3. g.draw#val ?D,3DD,5D,5D!4 .5. .6. g.set,olor ,olor.pink!4 .:. g."ill#val .?D,3DD,5D,5D!4 .=. g.drawArc CD,.:D,5D,5D,5D,3?D!4 .?. g."illArc 3?D,.:D,5D,5D,D,.BD!4 .B. .C. 7 3D. 7

myapplet.html
.. /html1

3. 5. 6. :. =.

/body1 /applet code>ARraphics%emo.classA width>A5DDA height>A5DDA1 /9applet1 /9body1 /9html1

!nimation in !pplet
Applet is mostly used in games and animation. For this purpose image is re$uired to be moved.

,xample of animation in applet'


.. import java.awt.I4 3. import java.applet.I4 5. public class Animation)xample extends Applet 2 6. :. Image picture4 =. ?. public void init ! 2 B. picture >getImage get%ocumentJase !,Abike0..gi"A!4 C. 7 .D. ... public void paint Rraphics g! 2 .3. "or int i>D4i/:DD4i@@!2 .5. g.drawImage picture, i,5D, this!4 .6. .:. try2&hread.sleep .DD!47catch )xception e!27 .=. 7 .?. 7 .B. 7 In the above example, drawImage ! method o" Rraphics class is used to display the image. &he 6th argument o" drawImage ! method o" is Image#bserver object. &he ,omponent class implements Image#bserver inter"ace. -o current class object would also be treated as Image#bserver because Applet class indirectly extends the ,omponent class.

myapplet.html
.. 3. 5. 6. :. =. /html1 /body1 /applet code>A%isplayImage.classA width>A5DDA height>A5DDA1 /9applet1 /9body1 /9html1

EventAandlin" in !pplet
As we per"orm event handling in A8& or -wing, we can per"orm it in applet also. KetEs see the simple example o" event handling in applet that prints a message by click on the button.

,xample of ,vent-andling in applet'


.. import java.applet.I4 3. import java.awt.I4 5. import java.awt.event.I4 6. public class )ventApplet extends Applet implements ActionKistener2 :. Jutton b4 =. &extField t"4 ?. B. public void init !2 C. t">new &extField !4 .D. t".setJounds 5D,6D,.:D,3D!4 ... .3. b>new Jutton A,lickA!4 .5. b.setJounds BD,.:D,=D,:D!4 .6. .:. add b!4add t"!4 .=. b.addActionKistener this!4 .?. .B. setKayout null!4 .C. 7 3D. 3.. public void action*er"ormed Action)vent e!2 33. t".set&ext A8elcomeA!4 35. 7 36. 7 In the above example, we have created all the controls in init ! method because it is invoked only once.

myapplet.html
.. 3. 5. 6. :. =. /html1 /body1 /applet code>A)ventApplet.classA width>A5DDA height>A5DDA1 /9applet1 /9body1 /9html1

.arameter in !pplet

8e can get any in"ormation "rom the G&(K "ile as a parameter. For this purpose, Applet class provides a method named get*arameter !. -yntax: .. public -tring get*arameter -tring parameterOame!

,xample of using parameter in Applet'


.. import java.applet.Applet4 3. import java.awt.Rraphics4 5. 6. public class Pse*aram extends Applet2 :. =. public void paint Rraphics g!2 ?. -tring str>get*arameter AmsgA!4 B. g.draw-tring str,:D, :D!4 C. 7 .D. ... 7

myapplet.html
.. 3. 5. 6. :. =. ?. /html1 /body1 /applet code>APse*aram.classA width>A5DDA height>A5DDA1 /param name>AmsgA value>A8elcome to appletA1 /9applet1 /9body1 /9html1

Example of !rray@ist:
.. import java.util.I4 3. class -imple2 5. public static void main -tring args;<!2 6. :. ArrayKist al>new ArrayKist !4 =. al.add A+aviA!4 ?. al.add A'ijayA!4 B. al.add A+aviA!4 C. al.add AAjayA!4 .D. ... Iterator itr>al.iterator !4 .3. while itr.hasOext !!2 .5. -ystem.out.println itr.next !!4 .6. 7 .:. 7

.=. 7
Output::avi &i(ay :avi A(ay

-#o #ays to iterate the elements of collection:


.. Jy Iterator inter"ace. 3. Jy "orMeach loop.

Iteratin" the elements of Collection by for4each loop:


.. import java.util.I4 3. class -imple2 5. public static void main -tring args;<!2 6. :. ArrayKist al>new ArrayKist !4 =. al.add A+aviA!4 ?. al.add A'ijayA!4 B. al.add A+aviA!4 C. al.add AAjayA!4 .D. ... "or #bject obj:al! .3. -ystem.out.println obj!4 .5. 7 .6. 7
Output::avi &i(ay :avi A(ay

Storin" user4defined class objects:


.. class -tudent2 3. int rollno4 5. -tring name4 6. int age4 :. -tudent int rollno,-tring name,int age!2 =. this.rollno>rollno4 ?. this.name>name4 B. this.age>age4 C. 7 .D. 7 .. import java.util.I4

3. class -imple2 5. public static void main -tring args;<!2 6. :. -tudent s.>new -tudent .D.,A-onooA,35!4 =. -tudent s3>new -tudent .D3,A+aviA,3.!4 ?. -tudent s3>new -tudent .D5,AGanumatA,3:!4 B. C. ArrayKist al>new ArrayKist !4 .D. al.add s.!4 ... al.add s3!4 .3. al.add s5!4 .5. .6. Iterator itr>al.iterator !4 .:. while itr.hasOext !!2 .=. -tudent st> -tudent!itr.next !4 .?. -ystem.out.println st.rollno@A A@st.name@A A@st.age!4 .B. 7 .C. 7 3D. 7
Output:101 1onoo 23 102 :avi 21 103 /anumat 25

Example of add!ll+Collection c) method:


.. import java.util.I4 3. class -imple2 5. public static void main -tring args;<!2 6. :. ArrayKist al>new ArrayKist !4 =. al.add A+aviA!4 ?. al.add A'ijayA!4 B. al.add AAjayA!4 C. .D. ArrayKist al3>new ArrayKist !4 ... al3.add A-onooA!4 .3. al3.add AGanumatA!4 .5. .6. al.addAll al3!4 .:. .=. Iterator itr>al.iterator !4 .?. while itr.hasOext !!2 .B. -ystem.out.println itr.next !!4 .C. 7 3D. 7 3.. 7
Output::avi &i(ay

A(ay 1onoo /anumat

Example of remove!ll+) method:


.. import java.util.I4 3. class -imple2 5. public static void main -tring args;<!2 6. :. ArrayKist al>new ArrayKist !4 =. al.add A+aviA!4 ?. al.add A'ijayA!4 B. al.add AAjayA!4 C. .D. ArrayKist al3>new ArrayKist !4 ... al3.add A+aviA!4 .3. al3.add AGanumatA!4 .5. .6. al.removeAll al3!4 .:. .=. -ystem.out.println Aiterating the elements a"ter removing the elements o" al3. ..A!4 .?. Iterator itr>al.iterator !4 .B. while itr.hasOext !!2 .C. -ystem.out.println itr.next !!4 3D. 7 3.. 33. 7 35. 7
Output:iteratin% the elements a#ter removin% the elements o# al2... &i(ay A(ay

Example of retain!ll+) method:


.. import java.util.I4 3. class -imple2 5. public static void main -tring args;<!2 6. :. ArrayKist al>new ArrayKist !4 =. al.add A+aviA!4 ?. al.add A'ijayA!4 B. al.add AAjayA!4 C. .D. ArrayKist al3>new ArrayKist !4 ... al3.add A+aviA!4

.3. al3.add AGanumatA!4 .5. .6. al.retainAll al3!4 .:. .=. -ystem.out.println Aiterating the elements a"ter retaining the elements o" al3.. .A!4 .?. Iterator itr>al.iterator !4 .B. while itr.hasOext !!2 .C. -ystem.out.println itr.next !!4 3D. 7 3.. 7 33. 7
Output:iteratin% the elements a#ter retainin% the elements o# al2... :avi

Example of @inked@ist:
.. import java.util.I4 3. class -imple2 5. public static void main -tring args;<!2 6. :. KinkedKist al>new KinkedKist !4 =. al.add A+aviA!4 ?. al.add A'ijayA!4 B. al.add A+aviA!4 C. al.add AAjayA!4 .D. ... Iterator itr>al.iterator !4 .3. while itr.hasOext !!2 .5. -ystem.out.println itr.next !!4 .6. 7 .:. 7 .=. 7
Output::avi &i(ay :avi A(ay

J&8C &river
.. J%J, %rivers .. J%J,M#%J, bridge driver 3. OativeMA*I driver 5. Oetwork *rotocol driver 6. &hin driver

J%J, %river is a so"tware component that enables java application to interact with the database.&here are 6 types o" J%J, drivers: .. J%J,M#%J, bridge driver 3. OativeMA*I driver partially java driver! 5. Oetwork *rotocol driver "ully java driver! 6. &hin driver "ully java driver!

() J&8C4O&8C brid"e driver


&he J%J,M#%J, bridge driver uses #%J, driver to connect to the database. &he J%J,M#%J, bridge driver converts J%J, method calls into the #%J, "unction calls. &his is now discouraged because o" thin driver.

!dvanta"es:

easy to use. can be easily connected to any database.

&isadvanta"es:

*er"ormance degraded because J%J, method call is converted into the #%J, "uncion calls. &he #%J, driver needs to be installed on the client machine.

3) 9ative4!.I driver

&he Oative A*I driver uses the clientMside libraries o" the database. &he driver converts J%J, method calls into native calls o" the database A*I. It is not written entirely in java.

!dvanta"e:

per"ormance upgraded than J%J,M#%J, bridge driver.

&isadvanta"e:

&he Oative driver needs to be installed on the each client machine. &he 'endor client library needs to be installed on client machine.

6) 9et#ork .rotocol driver


&he Oetwork *rotocol driver uses middleware application server! that converts J%J, calls directly or indirectly into the vendorMspeci"ic database protocol. It is "ully written in java.

!dvanta"e:

Oo client side library is re$uired because o" application server that can per"orm many tasks like auditing, load balancing, logging etc.

&isadvanta"es:

Oetwork support is re$uired on client machine. +e$uires databaseMspeci"ic coding to be done in the middle tier. (aintenance o" Oetwork *rotocol driver becomes costly because it re$uires databaseMspeci"ic coding to be done in the middle tier.

:) -hin driver
&he thin driver converts J%J, calls directly into the vendorMspeci"ic database protocol. &hat is why it is known as thin driver. It is "ully written in Java language.

!dvanta"e:

Jetter per"ormance than all other drivers. Oo so"tware is re$uired at client side or server side.

&isadvanta"e:

%rivers depends on the %atabase.

Example to connect to the Oracle database


For connecting java application with the oracle database, you need to "ollow : steps to per"orm database connectivity. In this example we are using #racle.Dg as the database. -o we need to know "ollowing in"ormations "or the oracle database: .. &river class: &he driver class "or the oracle database is oracle.jdbc.driver.Oracle&river. 3. Connection 1,@: &he connection P+K "or the oracle.DR database is jdbc:oracle:thin:Klocalhost:(B3(:xe where jdbc is the A*I, oracle is the database, thin is the driver, localhost is the server name on which oracle is running, we may also use I* address, .:3. is the port number and T) is the #racle service name. Lou may get all these in"ormations "rom the tnsnames.ora "ile.

5. 1sername: &he de"ault username "or the oracle database is system. 6. .ass#ord: *assword is given by the user at the time o" installing the oracle database. KetEs "irst create a table in oracle database. .. create table emp id number .D!,name varchar3 6D!,age number 5!!4

Example to Connect Java !pplication #ith Oracle database


In this example, system is the username and oracle is the password o" the #racle database. .. import java.s$l.I4 3. class #racle,on2 5. public static void main -tring args;<!2 6. try2 :. 99step. load the driver class =. ,lass."orOame Aoracle.jdbc.driver.#racle%riverA!4 ?. B. 99step3 create the connection object C. ,onnection con>%river(anager.get,onnection .D. Ajdbc:oracle:thin:Vlocalhost:.:3.:xeA,AsystemA,AoracleA!4 ... .3. 99step5 create the statement object .5. -tatement stmt>con.create-tatement !4 .6. .:. 99step6 execute $uery .=. +esult-et rs>stmt.executeSuery Aselect I "rom empA!4 .?. while rs.next !! .B. -ystem.out.println rs.getInt .!@A A@rs.get-tring 3!@A A@rs.get-tring 5!!4 .C. 3D. 99step: close the connection object 3.. con.close !4 33. 35. 7catch )xception e!2 -ystem.out.println e!47 36. 3:. 7 3=. 7 Jasics o" Java ##*s ,oncepts -tring Gandling )xception Gandling Oested ,lasses (ultithreading -ynchroniFation I9# -erialiFation Oetworking A8& )vent Gandling -wing Kayout(anager Applet +e"lection A*I ,ollection J%J, J%J, Introduction J%J, %river %J ,onnectivity -teps ,onnectivity with #racle ,onnectivity with (y-SK Access without %-O %river(anager ,onnection -tatement +esult-et *repared-tatement +esult-et(eta%ata %atabase(eta%ata -tore

image +etrieve image -tore "ile +etrieve "ile ,allable-tatement &ransaction (anagement Jatch *rocessing +ow-et Inter"ace J%J, Oew Features Java Oew Features +(I InternationaliFation

Connectivity #ith !ccess #ithout &S9


&here are two ways to connect java application with the access database. .. 8ithout %-O %ata -ource Oame! 3. 8ith %-O

//prev

Java is mostly used with #racle, mys$l, or %J3 database. -o you can learn this topic only "or knowledge.

Example to Connect Java !pplication #ith access #ithout &S9


In this example, we are going to connect the java program with the access database. In such case, we have created the login table in the access database. &here is only one column in the table named name. KetEs get all the name o" the login table. .. import java.s$l.I4 3. class &est2 5. public static void main -tring ar;<!2 6. try2 :. -tring database>Astudent.mdbA499Gere database exists in the current directory =. ?. -tring url>Ajdbc:odbc:%river>2(icroso"t Access %river I.mdb!74 B. %JS>A @ database @ A4%riverI%>334+)A%#OKL>trueA4 C. .D. ,lass."orOame Asun.jdbc.odbc.Jdbc#dbc%riverA!4 ... ,onnection c>%river(anager.get,onnection url!4 .3. -tatement st>c.create-tatement !4 .5. +esult-et rs>st.executeSuery Aselect I "rom loginA!4 .6. .:. while rs.next !!2 .=. -ystem.out.println rs.get-tring .!!4 .?. 7 .B. .C. 7catch )xception ee!2-ystem.out.println ee!47 3D.

3.. 77 download this example

Example to Connect Java !pplication #ith access #ith &S9


,onnectivity with type. driver is not considered good. &o connect java application with type. driver, create %-O "irst, here we are assuming your dsn name is mydsn. .. import java.s$l.I4 3. class &est2 5. public static void main -tring ar;<!2 6. try2 :. -tring url>Ajdbc:odbc:mydsnA4 =. ,lass."orOame Asun.jdbc.odbc.Jdbc#dbc%riverA!4 ?. ,onnection c>%river(anager.get,onnection url!4 B. -tatement st>c.create-tatement !4 C. +esult-et rs>st.executeSuery Aselect I "rom loginA!4 .D. ... while rs.next !!2 .3. -ystem.out.println rs.get-tring .!!4 .5. 7 .6. .:. 7catch )xception ee!2-ystem.out.println ee!47 .=. .?. 77

,esultSet eta&ata:
&he metadata means data about data i.e. we can get "urther in"ormation "rom the data. I" you have to get metadata o" a table like total number o" column, column name, column type etc. , +esult-et(eta%ata inter"ace is use"ul because it provides methods to get metadata "rom the +esult-et object.

*ommonly used methods of .esultSetMeta)ata interface


public int "etColumnCount+)thro#s S*@Exception: it returns the total number o" columns in the +esult-et object. public Strin" "etColumn9ame+int index)thro#s S*@Exception: it returns the column name o" the speci"ied column index. public Strin" "etColumn-ype9ame+int index)thro#s S*@Exception: it returns the column type name "or the speci"ied index. public Strin" "et-able9ame+int index)thro#s S*@Exception: it returns the table name "or the speci"ied column index.

Ao# to "et the object of ,esultSet eta&ata:

&he get(eta%ata ! method o" +esult-et inter"ace returns the object o" +esult-et(eta%ata. -yntax: .. public +esult-et(eta%ata get(eta%ata !throws -SK)xception

Example of ,esultSet eta&ata interface :


.. import java.s$l.I4 3. class +smd2 5. public static void main -tring args;<!2 6. try2 :. ,lass."orOame Aoracle.jdbc.driver.#racle%riverA!4 =. ?. ,onnection con>%river(anager.get,onnection B. Ajdbc:oracle:thin:Vlocalhost:.:3.:xeA,AsystemA,AoracleA!4 C. .D. *repared-tatement ps>con.prepare-tatement Aselect I "rom empA!4 ... +esult-et rs>ps.executeSuery !4 .3. .5. +esult-et(eta%ata rsmd>rs.get(eta%ata !4 .6. .:. -ystem.out.println A&otal columns: A@rsmd.get,olumn,ount !!4 .=. -ystem.out.println A,olumn Oame o" .st column: A@rsmd.get,olumnOame .! !4 .?. -ystem.out.println A,olumn &ype Oame o" .st column: A@rsmd.get,olumn&y peOame .!!4 .B. .C. con.close !4 3D. 3.. 7catch )xception e!2 -ystem.out.println e!47 33. 35. 7 36. 7
Output:*otal columns! 2 )olumn 4ame o# 1st column! -; )olumn *y e 4ame o# 1st column! 4HI"+:

Event and @istener +Event Aandlin"):


,hanging the state o" an object is known as an event. For example, click on button, dragging mouse etc. &he java.awt.event package provides many event classes and Kistener inter"aces "or event handling.

Event classes and @istener interfaces:

Event Classes Action)vent (ouse)vent

@istener Interfaces ActionKistener (ouseKistener and (ouse(otionKistener

(ouse8heel)vent (ouse8heelKistener Hey)vent Item)vent &ext)vent Adjustment)vent 8indow)vent ,omponent)vent ,ontainer)vent Focus)vent HeyKistener ItemKistener &extKistener AdjustmentKistener 8indowKistener ,omponentKistener ,ontainerKistener FocusKistener

Steps to perform EventAandlin":


Following steps are re$uired to per"orm event handling : .. Implement the Kistener inter"ace and overrides its methods 3. +egister the component with the Kistener For registering the component with the Kistener, many classes provide the registration methods. For example: 8utton o public void addActionKistener ActionKistener a!27 enuItem o public void addActionKistener ActionKistener a!27 -ext7ield o public void addActionKistener ActionKistener a!27 o public void add&extKistener &extKistener a!27 -ext!rea o public void add&extKistener &extKistener a!27 Checkbox o public void addItemKistener ItemKistener a!27 Choice o public void addItemKistener ItemKistener a!27 @ist o public void addActionKistener ActionKistener a!27
o

public void addItemKistener ItemKistener a!27

EventAandlin" Codes:
8e can put the event handling code into one o" the "ollowing places: .. -ame class 3. #ther class 5. Annonymous class

Example of event handlin" #ithin class:


.. import java.awt.I4 3. import java.awt.event.I4 5. 6. class A)vent extends Frame implements ActionKistener2 :. &extField t"4 =. A)vent !2 ?. B. t">new &extField !4 C. t".setJounds =D,:D,.?D,3D!4 .D. ... Jutton b>new Jutton Aclick meA!4 .3. b.setJounds .DD,.3D,BD,5D!4 .5. .6. b.addActionKistener this!4 .:. .=. add b!4add t"!4 .?. .B. set-iFe 5DD,5DD!4 .C. setKayout null!4 3D. set'isible true!4 3.. 33. 7 35. 36. public void action*er"ormed Action)vent e!2 3:. t".set&ext A8elcomeA!4 3=. 7 3?. 3B. public static void main -tring args;<!2 3C. new A)vent !4 5D. 7 5.. 7 public void set8ounds+int xaxis' int yaxis' int #idth' int hei"ht)E have been used in the above example that sets the position o" the component it may be button, text"ield etc.

3) Example of event handlin" by Outer class:


.. import java.awt.I4 3. import java.awt.event.I4 5. 6. class A)vent3 extends Frame implements ActionKistener2 :. &extField t"4 =. A)vent3 !2 ?. B. t">new &extField !4 C. t".setJounds =D,:D,.?D,3D!4 .D. ... Jutton b>new Jutton Aclick meA!4 .3. b.setJounds .DD,.3D,BD,5D!4 .5. .6. b.addActionKistener this!4 .:. .=. add b!4add t"!4 .?. .B. set-iFe 5DD,5DD!4 .C. setKayout null!4 3D. set'isible true!4 3.. 33. 7 35. 36. public void action*er"ormed Action)vent e!2 3:. t".set&ext A8elcomeA!4

3=. 7 3?. 3B. public static void main -tring args;<!2 3C. new A)vent3 !4 5D. 7 5.. 7 .. import java.awt.event.I4 3. 5. class #uter implements ActionKistener2 6. A)vent3 obj4 :. #uter A)vent3 obj!2 =. this.obj>obj4 ?. 7 B. C. public void action*er"ormed Action)vent e!2 .D. obj.t".set&ext AwelcomeA!4 ... 7 .3. .5. 7

6) Example of event handlin" by !nnonymous class:


.. import java.awt.I4 3. import java.awt.event.I4 5. 6. class A)vent5 extends Frame2 :. &extField t"4 =. A)vent5 !2 ?. B. t">new &extField !4 C. t".setJounds =D,:D,.?D,3D!4 .D. ... Jutton b>new Jutton Aclick meA!4 .3. b.setJounds :D,.3D,BD,5D!4 .5. .6. b.addActionKistener new ActionKistener !2 .:. public void action*er"ormed !2 .=. t".set&ext AhelloA!4 .?. 7 .B. 7!4 .C. 3D. add b!4add t"!4 3.. 33. set-iFe 5DD,5DD!4 35. setKayout null!4 36. set'isible true!4

3:. 3=. 7 3?. public static void main -tring args;<!2 3B. new A)vent5 !4 3C. 7 5D. 7

S#in" +Jraphics .ro"rammin" in java):


-wing is a part o" JF, Java Foundation ,lasses! that is used to create RPI application. It is built on the top o" A8& and entirely written in java.

!dvanta"e of S#in" over !$-:


&here are many advantages o" -wing over A8&. &hey are as "ollows: -wing components are *late"orm independent. It is lightweight. It supports pluggable look and "eel. It has more power"ul componenets like tables, lists, scroll panes, color chooser, tabbed pane etc.

It "ollows (', (odel 'iew ,ontroller! architecture.

$hat is J7C %
&he Java Foundation ,lasses JF,! are a set o" RPI components which simpli"y the development o" desktop applications.

Aierarchy of s#in":

Commonly used

ethods of Component class:

()public void add+Component c) 3)public void setSi/e+int #idth'int hei"ht) 6)public void set@ayout+@ayout ana"er m) :)public void setGisible+boolean)

Creatin" a 7rame:
&here are two ways to create a "rame: Jy creating the object o" Frame class association!

Jy extending Frame class inheritance!

Simple example of S#in" by !ssociation:

.. import javax.swing.I4 3. public class -imple 2 5. JFrame "4 6. -imple !2 :. =. ">new JFrame !4 ?. B. JJutton b>new JJutton AclickA!4 C. b.setJounds .5D,.DD,.DD, 6D!4 .D. ... ".add b!4 .3. .5. ".set-iFe 6DD,:DD!4 .6. ".setKayout null!4 .:. ".set'isible true!4 .=. 7 .?. .B. public static void main -tring;< args! 2 .C. new -imple !4 3D. 7 3.. 7

example of J,adio8utton class:


.. import javax.swing.I4 3. public class +adio 2 5. JFrame "4 6. :. +adio !2 =. ">new JFrame !4 ?. B. J+adioJutton r.>new J+adioJutton AA! (aleA!4 C. J+adioJutton r3>new J+adioJutton AJ! Fe(aleA!4 .D. r..setJounds :D,.DD,?D,5D!4 ... r3.setJounds :D,.:D,?D,5D!4 .3. .5. JuttonRroup bg>new JuttonRroup !4 .6. bg.add r.!4bg.add r3!4 .:. .=. ".add r.!4".add r3!4

.?. .B. ".set-iFe 5DD,5DD!4 .C. ".setKayout null!4 3D. ".set'isible true!4 3.. 7 33. public static void main -tring;< args! 2 35. new +adio !4 36. 7 3:. 7

Example of J-ext7ield class:


.. import java.awt.,olor4 3. import javax.swing.I4 5. 6. public class &Area 2 :. J&extArea area4 =. JFrame "4 ?. &Area !2 B. ">new JFrame !4 C. .D. area>new J&extArea 5DD,5DD!4 ... area.setJounds .D,5D,5DD,5DD!4 .3. .5. area.setJackground ,olor.black!4 .6. area.setForeground ,olor.white!4 .:. .=. ".add area!4 .?. .B. ".set-iFe 6DD,6DD!4 .C. ".setKayout null!4 3D. ".set'isible true!4 3.. 7 33. public static void main -tring;< args! 2 35. new &Area !4 36. 7 3:. 7

You might also like