Professional Documents
Culture Documents
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
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
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.
...
.=. .?.
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
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.
...
.=. .?.
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
.. 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.
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.
.. 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:
:. =. ?.
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
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.
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.
-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.
.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.
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.
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
.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
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.
() -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
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.
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.
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:
&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
!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.
*roblem is that I have to provide a speci"ic implementation o" run ! method in subclass that is why we use method overriding.
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.
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
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
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.
.. 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
() final variable
I" you make any variable as "inal, you cannot change the value o" "inal variable It will be constant!.
3) final method
I" you make any method as "inal, you cannot override it.
6) final class
I" you make any class as "inal, you cannot extend it.
Out ut!runnin%...
:. ... =. 7
:. 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
,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.
&ynamic bindin"
8hen type o" the object is determined at runMtime, it is known as dynamic binding.
=. 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.
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.
.. 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
!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.
!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.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
?. 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
.. 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.
.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.
-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.
.. 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.
.. 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.
.. 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.
.. 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.
:. 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
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
() 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
&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!.
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:
... 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
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-
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.
.. 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
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
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..:.
B. 7 C. 7
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
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:
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.
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.
&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
-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:
$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.
&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
:. 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.
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:
Oow, as displayed in the above example, rest o" the code is executed i.e. rest o" the code... statement is printed.
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.
"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.
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.
error: beyond your control e.g. you are unable to do anything i" there occurs 'irtual(achine)rror or -tack#ver"low)rror.
,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.
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'...
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
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...
()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
&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.
&hread ! &hread -tring name! &hread +unnable r! &hread +unnable r,-tring name!
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.
Output:thread is runnin%...
=. 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.
.=. 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.
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.
.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.
-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
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
-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
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.
InputStream class
Input-tream class ia an abstract class.It is the superclass o" all classes representing an input stream o" bytes.
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.
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 ,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.
7ile,eader class:
%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
8uffered,eader class:
Ju""ered+eader class can be used to read data line by line by readKine ! method.
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
!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
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.
&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.
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:
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.
myapplet.html
.. /html1
3. 5. 6. :. =.
!nimation in !pplet
Applet is mostly used in games and animation. For this purpose image is re$uired to be moved.
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.
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!
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
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
.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!
!dvanta"es:
&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:
&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.
!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:
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
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
//prev
Java is mostly used with #racle, mys$l, or %J3 database. -o you can learn this topic only "or knowledge.
,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.
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.
&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
(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
EventAandlin" Codes:
8e can put the event handling code into one o" the "ollowing places: .. -ame class 3. #ther class 5. Annonymous class
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
3:. 3=. 7 3?. public static void main -tring args;<!2 3B. new A)vent5 !4 3C. 7 5D. 7
$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
()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!
.. 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
.?. .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