0% found this document useful (0 votes)
98 views59 pages

Unit 1

Java is an object-oriented programming language developed by Sun Microsystems. It is compiled and interpreted, platform independent, robust, secure, distributed, and high performance. The Java development kit includes tools like the Java compiler, interpreter, and debugger. The Java API includes hundreds of classes and methods organized into packages. Arrays allow storing multiple values of the same type. Arrays have a fixed size and hold only one data type. Control statements like if-else and switch change the order of execution based on conditions.

Uploaded by

aadafull
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views59 pages

Unit 1

Java is an object-oriented programming language developed by Sun Microsystems. It is compiled and interpreted, platform independent, robust, secure, distributed, and high performance. The Java development kit includes tools like the Java compiler, interpreter, and debugger. The Java API includes hundreds of classes and methods organized into packages. Arrays allow storing multiple values of the same type. Arrays have a fixed size and hold only one data type. Control statements like if-else and switch change the order of execution based on conditions.

Uploaded by

aadafull
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 59

UNIT-1 Core Java

LECTURE-1 Introduction to Java: Java is a general-purpose Object Oriented progra ing language developed b! "un

#icros!ste s o$ U"% in 1&&1'Originall! called Oa( b! Ja es )osling* one o$ t+e inventors o$ Java' Java $eatures: Co piled and Interpreted ,lat$or independent and portable

Object Oriented Robust and "ecure -istributed .a iliar* "i ple and s all #ultit+readed and Interactive /ig+ ,er$or ance -!na ic and E0tensible Java Environ ent: Java environ ent include a large nu ber o$ develop ent tools and +undreds o$ classes and et+ods' (no1n as Java -evelop ent 2it3J-24 and

T+e develop ent tools are part o$ t+e s!ste t+e classes and

et+ods are part o$ Java "tandard Librar!3J"L4*also (no1n as t+e ing Inter$ace3%,I4'

application ,rogra

Java -evelop ent 2it 3J-24: T+e Java -evelop ent 2it co es 1it+ a collection o$ tools t+at are used $or developing and running Java progra s' T+e! include appletvie1er 3$or vie1ing Java applet4 javac3Java Co piler4 java3Java Interpreter4 jdb3Java debugger4 javadoc3$or creating /T#L docu ents4 java+3$or C +eader $ile4 %pplication ,rogra ing Inter$ace3%,I4: et+ods grouped into

T+e java standard librar! or %,I includes +undred o$ classes and several $unctional pac(ages* ost co on pac(ages are

Language support pac(age3java'lang'54 Utilities pac(age3java'util'54 Input6Output pac(age3java'io'54 Net1or(ing pac(age3java'net'54 -atabases pac(age3java's7l'54

,rocess o$ 8uilding 9 running java application progra : Te0t editor

java source code

javadoc

/T#L $ile

javac

java class $ile

java+

+eader $ile

java

jdb

java progra

output

T!pes o$ java progra : Java progra can be developed in t1o 1a!s as $ollo1s

stand alone application 1eb applets "tand alone application can be e0ecuted b! java interpreter and 1e applets can be e0ecuted b! java enabled 1eb bro1ser $or e0a ple internet e0plorer' .or at o$ Java progra : class classna e : public static void ain3"tring args; <4

: "!ste 'out'println 3=java is better t+an C>>?4@ A A Java Birtual #ac+ine 3JB#4: Java co piler produces an inter ediate code (no1n as b!te code $or a not e0ist' T+is t+e co puter ac+ine is called t+e java virtual e or!' ajor $unctions o$ a real co puter' ac+ine t+at does

ac+ine3JB#4 and it e0ists onl! inside

It is a si ulated co puter and does all ,rocess o$ Co pilation:

java source code

java co piler

b!te code Birtual ac+ine

,rocess o$ converting b!te code into

ac+ine code:

b!te code

java interpreter

ac+ine code real ac+ine

T+e virtual

ac+ine code is not

ac+ine speci$ic'

Data types in Java:


-ata t!pe speci$! t+e siCe and t!pe o$ values t+at can be stored' Ever! variable in java +as a data t!pe' -ata t!pe can be divided into t1o t!pes as $ollo1s pri itive data t!pe

non-pri itive data ,ri itive data t!pe can be divided into t1o t!pes as $ollo1s Nu eric Non Nu eric Nu eric is divided into integer and $loating point' Integer is divided into b!te* s+ort* int* long .loating point is divided into $loat and double' Non-nu eric can be divided into c+ar3c+aracter4 and 8oolean' Non-pri itive data t!pe can be divided into D t!pes as $ollo1s classes inter$aces arra!s

-i$$erent t!pes can be described in table as $ollo1s: -ata T!pe b!te s+ort int long $loat double c+ar boolean "iCe 1 b!te E b!te I b!te F b!te I b!te F b!te E b!te 1 bit D'Ie-JDF 1'Ge-DJF D'Ie>JDF 1'Ge>DJF #ini u -1EF -DE*GHF -E*1IG*IFD*HIF value #a0i u 1EG DE*GHG E*1IG*IFD*HIG value

Bariables: % variable is an identi$ier t+at denotes a storage location used to store a data value' % variable a! ta(e di$$erent values at di$$erent ti es during t+e e0ecution o$ t+e progra ' a! consist o$ alp+abets* digits* underscore 3K4 and dollar c+aracter*

Bariable na es

"ubject to t+e $ollo1ing conditions: T+e! ust not begin 1it+ a digit'

Upper case and lo1er case are distinct' It s+ould not be a (e!1ord' L+ite space is not allo1ed' Bariable na es can be o$ an! lengt+' Operators: T+e! are used to % unar! operator anipulate pri itive data t!pes' Java operators can be classi$ied as a! appear be$ore 3pre$i04 its argu ent or a$ter 3post$i04 its argu ent'

unar!* binar!* or ternar!M eaning ta(ing one* t1o* or t+ree argu ents* respectivel!' % binar! or ternar! operator appears bet1een its argu ents' Java operators $all into eig+t di$$erent categories: %ssign ent arit+ etic* relational* logical* bit1ise* co pound assign ent* conditional* and t!pe' %ssign ent Operators %rit+ etic Operators Relational Operators Logical Operators 8it 1ise Operator &
= + * / % ++ --

N 99
|

O RR
^ +=

NP 9

OP R
>>

PP Q
>>> /=

QP S

Co pound %ssign ent Operators OOP NNP Conditional Operator NNNP


?:

-=

*=

%=

Lecture-2
Arrays:

%n arra! is a group o$ +o ogeneous data ite s s+are a co

on na e' T+e java arra! e or! allocations'

enables t+e user to store t+e values o$ t+e sa e t!pe in contiguous

%rra!s are al1a!s a $i0ed lengt+ abstracted data structure 1+ic+ can not be altered 1+en re7uired' T+e Array class i plicitl! e0tends java.lang.Object so an arra! is an instance o$ Object' Advantages of Java Array: 1' %n arra! can +old pri itive t!pes data' E' %n arra! +as its siCe t+at is (no1n as arra! lengt+' D' %n arra! (no1s onl! its t!pe t+at it contains' %rra! t!pe is c+ec(ed at t+e co pile-ti e' Disadvantages of Java Array: 1' %n arra! +as $i0ed siCe' E' %n arra! +olds onl! one t!pe o$ data 3including pri itive t!pes4' Declaring an array: -eclaring an arra! is t+e sa e as declaring a nor al variable e0cept t+at !ou ust put a

set o$ s7uare brac(ets a$ter t+e variable t!pe' /ere is an e0a ple o$ +o1 to declare an arra! o$ integers called a' public class %rra! : public static void : int;< a@ A A

ain3"tring;< args4

%n arra! is

ore co ple0 t+an a nor al variable so 1e +ave to assign

e or! to t+e

arra! 1+en 1e declare it' L+en !ou assign

e or! to an arra! !ou also set its siCe' /ere

is an e0a ple o$ +o1 to create an arra! t+at +as T ele ents' public class %rra! : public static void ain3"tring;< args4 : int;< a P ne1 int;T<@ A A Instead o$ assigning e or! to t+e arra! !ou can assign values to it instead' T+is is called initialiCing t+e arra! because it is giving t+e arra! initial values' public class %rra! : public static void ain3"tring;< args4 : int;< a P :1E* ED* DI* IT* THA@ A A Using an array: Uou can access t+e values in an arra! using t+e nu ber o$ t+e ele ent !ou 1ant to access bet1een s7uare brac(ets a$ter t+e arra!Vs na e' T+ere is one i portant t+ing !ou ust

re e ber about arra!s 1+ic+ is t+e! al1a!s start at J and not 1' /ere is an e0a ple o$ +o1 to set t+e values $or an arra! o$ T ele ents' public class %rra! : public static void ain3"tring;< args4 : int;< a P ne1 int;T<@ a;J< P 1E@ a;1< P ED@ a;E< P DI@ a;D< P IT@

a;I< P TH@ A A % uc+ ore use$ul 1a! o$ using an arra! is in a loop' /ere is an e0a ple o$ +o1 to use uc+ easier t+an setting

a loop to set all t+e values o$ an arra! to J 1+ic+ !ou 1ill see is all t+e values to J seperatel!' public class %rra! : public static void ain3"tring;< args4 : int;< a P ne1 int;T<@ $or 3int i P J@ i O T@ i>>4 a;i< P J@ A A Sorting an array

"o eti es !ou 1ill 1ant to sort t+e ele ents o$ an arra! so t+at t+e! go $ro value to t+e +ig+est value or t+e ot+er 1a! around' To do t+is 1e sort' % bubble sort uses an outer loop to go $ro and an inner loop 1+ic+ goes $ro

t+e lo1est

ust use t+e bubble

t+e last ele ent o$ t+e arra! to t+e $irst

t+e $irst to t+e last' Eac+ value is co pared inside t+e

inner loop against t+e value in $ront o$ it in t+e arra! and i$ it is greater t+an t+at value t+en it is s1apped' /ere is an e0a ple' public class %rra! : public static void ain3"tring;< args4 : int;< a P :D* T* 1* E* IA@ int i* j* te p@ $or 3i P I@ i NP J@ i--4 $or 3j P J@ j O i@ j>>4 i$ 3a;j< N a;j > 1<4 :

te p P a;j<@ a;j< P a;j > 1<@ a;j > 1< P te p@ A A A 2D arrays: "o $ar 1e +ave been using 1-di ensional or 1- arra!s' % E- arra! can +ave values t+at go not onl! do1n but also across' /ere are so e pictures t+at 1ill e0plain t+e di$$erence bet1een t+e E in a better 1a!' %ll t+at !ou need to do to create and use a E- arra! is use E s7uare brac(ets instead o$ 1' public class %rra! : public static void ain3"tring;< args4 : int;<;< a P ne1 int;D<;D<@ a;J<;J< P 1@ A A

Control Statements:
Java Control statements control t+e order o$ e0ecution in a java progra * based on data values and conditional logic' T+ere are t+ree Selection statements: i$* i$-else and s1itc+' Loop statements: 1+ile* do-1+ile and $or' ransfer statements: brea(* continue* return* tr!-catc+-$inall! and assert' Le use control state ents 1+en 1e 1ant to c+ange t+e de$ault se7uential order o$ e0ecution ain categories o$ control $lo1 state ents@

Selection Statements !e "f Statement T+e i$ state ent e0ecutes a bloc( o$ code onl! i$ t+e speci$ied e0pression is true' I$ t+e value is $alse* t+en t+e i$ bloc( is s(ipped and e0ecution continues 1it+ t+e rest o$ t+e progra ' Uou can eit+er +ave a single state ent or a bloc( o$ code 1it+in an i$ state ent' Note t+at t+e conditional e0pression ust be a 8oolean e0pression'

T+e si ple i$ state ent +as t+e $ollo1ing s!nta0: if (<conditional expression>) <statement action> !e "f#else Statement T+e i$6else state ent is an e0tension o$ t+e i$ state ent' I$ t+e state ents in t+e i$ state ent $ails* t+e state ents in t+e else bloc( are e0ecuted' Uou can eit+er +ave a single state ent or a bloc( o$ code 1it+in i$-else bloc(s' Note t+at t+e conditional e0pression ust be a 8oolean e0pression' T+e i$-else state ent +as t+e $ollo1ing s!nta0: if (<conditional expression>) <statement action> else <statement action> S$itc! Case Statement T+e s1itc+ case state ent* also called a case state ent is a ulti-1a! branc+ 1it+

several c+oices' % s1itc+ is easier to i ple ent t+an a series o$ i$6else state ents' T+e s1itc+ state ent begins 1it+ a (e!1ord* $ollo1ed b! an e0pression t+at e7uates to a no

long integral value' .ollo1ing t+e controlling e0pression is a code bloc( t+at contains Cero or ore labeled cases' Eac+ label ust e7uate to an integer constant and eac+ ust

be uni7ue' L+en t+e s1itc+ state ent e0ecutes* it co pares t+e value o$ t+e controlling e0pression to t+e values o$ eac+ case label' T+e progra 1ill select t+e value o$ t+e case

label t+at e7uals t+e value o$ t+e controlling e0pression and branc+ do1n t+at pat+ to t+e end o$ t+e code bloc(' I$ none o$ t+e case label values atc+* t+en none o$ t+e codes

1it+in t+e s1itc+ state ent code bloc( 1ill be e0ecuted' Java includes a de$ault label to use in cases 1+ere t+ere are no o$ an outer s1itc+' Its general $or is as $ollo1s: atc+es' Le can +ave a nested s1itc+ 1it+in a case bloc(

switch (<non-long integral expression>) { case label1: <statement1> case label2: <statement2> ... case labeln: <statementn> default: <statement> !! end switch L+en e0ecuting a s1itc+ state ent* t+e progra T+ere$ore* i$ !ou 1ant to e0it in t+e $alls t+roug+ to t+e ne0t case' ust

iddle o$ t+e s1itc+ state ent code bloc(* !ou

insert a brea( state ent* 1+ic+ causes t+e progra code bloc('

to continue e0ecuting a$ter t+e current

"teration Statements %!ile Statement T+e 1+ile state ent is a looping construct control state ent t+at e0ecutes a bloc( o$ code 1+ile a condition is true' Uou can eit+er +ave a single state ent or a bloc( o$ code 1it+in t+e 1+ile loop' T+e loop 1ill never be e0ecuted i$ t+e testing e0pression evaluates to $alse' T+e loop condition ust be a boolean e0pression'

T+e s!nta0 o$ t+e 1+ile loop is $!ile &'loop condition() 'statements( Do#$!ile Loop Statement T+e do-1+ile loop is si ilar to t+e 1+ile loop* e0cept t+at t+e test is per$or ed at t+e end o$ t+e loop instead o$ at t+e beginning' T+is ensures t+at t+e loop 1ill be e0ecuted at least once' % do-1+ile loop begins 1it+ t+e (e!1ord do* $ollo1ed b! t+e state ents t+at a(e

up t+e bod! o$ t+e loop' .inall!* t+e (e!1ord 1+ile and t+e test e0pression co pletes t+e do-1+ile loop' L+en t+e loop condition beco es $alse* t+e loop is ter inated and e0ecution continues 1it+ t+e state ent i ediatel! $ollo1ing t+e loop' Uou can eit+er

+ave a single state ent or a bloc( o$ code 1it+in t+e do-1+ile loop' T+e s!nta0 o$ t+e do-1+ile loop is do 'loop body( $!ile &'loop condition()*

+elo$ is an e,ample t!at creates A -ibonacci se./ence controlled by a do#$!ile loop public class .ibonacci : public static void ain3"tring args;<4 : "!ste 'out'println3W,rinting Li ited set o$ .ibonacci "e7uenceW4@ double $ib1 P J@ double $ibE P 1@ double te p P J@ "!ste 'out'println3$ib14@ "!ste 'out'println3$ibE4@ do : te p P $ib1 > $ibE@ "!ste 'out'println3te p4@ $ib1 P $ibE@ 66Replace End 1it+ $irst nu ber $ibE P te p@ 66Replace te p nu ber 1it+ End nu ber A 1+ile 3$ibE O TJJJ4@ A 0

-or Loops T+e $or loop is a looping construct 1+ic+ can e0ecute a set o$ instructions a speci$ied nu ber o$ ti es' ItXs a counter controlled loop' T+e s!nta0 o$ t+e loop is as $ollo1s: for &'initiali1ation(* 'loop condition(* 'increment e,pression() 'loop body( T+e $irst part o$ a $or state ent is a starting initialiCation* 1+ic+ e0ecutes once be$ore t+e loop begins' T+e OinitialiCationN section can also be a co a-separated list o$ e0pression

state ents' T+e second part o$ a $or state ent is a test e0pression' %s long as t+e e0pression is true* t+e loop 1ill continue' I$ t+is e0pression is evaluated as $alse t+e $irst ti e* t+e loop 1ill never be e0ecuted' T+e t+ird part o$ t+e $or state ent is t+e bod! o$ t+e loop' T+ese are t+e instructions t+at are repeated eac+ ti e t+e progra e0ecutes t+e

loop' T+e $inal part o$ t+e $or state ent is an incre ent e0pression t+at auto aticall! e0ecutes a$ter eac+ repetition o$ t+e loop bod!' T!picall!* t+is state ent c+anges t+e value o$ t+e counter* 1+ic+ is t+en tested to see i$ t+e loop s+ould continue' %ll t+e sections in t+e $or-+eader are optional' %n! one o$ t+e t1o se icolons are can be le$t e pt!* but t+e

andator!' In particular* leaving out t+e Oloop conditionN signi$ies o$ $or loop is co onl! used to construct an

t+at t+e loop condition is true' T+e 3@@4 $or in$inite loop'

Classes:
% class is not+ing but a blueprint or a te plate $or creating di$$erent objects 1+ic+ de$ines its properties and be+aviors' Java class objects e0+ibit t+e properties and be+aviors de$ined b! its class' % class can contain $ields and be+avior o$ an object' % class +as t+e $ollo1ing general s!nta0: Oclass odi$iersNclassOclass na eN Oe0tends clauseN Oi ple ents clauseN: et+ods to describe t+e

66 -ealing 1it+ Classes 3Class bod!4 O$ield declarations 3"tatic and Non-"tatic4N O et+od declarations 3"tatic and Non-"tatic4N OInner class declarationsN Onested inter$ace declarationsN Oconstructor declarationsN O"tatic initialiCer bloc(sN A 8elo1 is an e0a ple s+o1ing t+e Objects and Classes o$ t+e Cube class t+at de$ines D $ields na el! lengt+* breadt+ and +eig+t' %lso t+e class contains a e ber $unction getBolu e34'

public class Cube : int lengt+@ int breadt+@ int +eig+t@ public int getBolu e34 : return 3lengt+ 5 breadt+ 5 +eig+t4@ A A

2et!ods:
#et+ods are not+ing but per$or e bers o$ a class t+at provide a service $or an object or e ber $unctions na es are case sensitive'

so e business logic' Java $ields and

Current states o$ a classVs corresponding object are stored in t+e objectVs instance variables' #et+ods de$ine t+e operations t+at can be per$or ed in java progra % et+od +as t+e $ollo1ing general s!anta0: et+od-na e3 argu ents 4 ing'

return t!pe :

66 code state ents A

Lect/re#3:
"n!eritance: Java In+eritance de$ines an is-a relations+ip bet1een a superclass and its subclasses' T+is eans t+at an object o$ a subclass can be used 1+erever an object o$ t+e superclass can be used' Class "n!eritance in java ec+anis is used to build ne1 classes $ro e0isting

classes' T+e in+eritance relations+ip is transitive: i$ class 0 e0tends class !* t+en a class C* 1+ic+ e0tends class 0* 1ill also in+erit $ro T+e ec+anis o$ deriving a ne1 class $ro class !' an old class is called in+eritance' et+ods o$ t+eir parent

T+e in+eritance allo1s subclasses to in+erit all t+e variables and classes' Defining a S/b#class: % sub-class is de$ined as $ollo1s: class sub-class-na e e,tends super-class-na e : variables declarations@ et+ods declarations@ A

T+e (e!1ord e0tends signi$ies t+at t+e properties o$ t+e super-class-na e are e0tended to t+e sub-class-na e' ypes of in!eritance: "ingle in+eritance 3onl! one super-class4 #ultiple in+eritance 3several super-class4 /ierarc+ical in+eritance 3one super class* #ultilevel in+eritance 3derived $ro an! subclasses4

a derived class4

Single in!eritance: It is an in+eritance in 1+ic+ t+ere is one super-class and one sub-class' %

E0a ple: class roo : int lengt+@ int breadt+@ roo 3int 0*int !4 : lengt+P0@ breadt+P!@ A int area3 4 : return 3lengt+ 5 breadt+4@ A A

class bedroo : int +eig+t@

e0tends roo

bedroo 3int 0*int !*int C4 : super30*!4@ +eig+tPC@ A int volu e3 4 : return3 lengt+ 5 breadt+ 5 +eig+t4@ A A class in+ertest : public static void : bedroo roo 1Pne1 bedroo 31I*1E*1J4@ ain3"tring args; < 4

int area1Proo 1'area3 4@ int volu e1Proo 1'volu e3 4@ "!ste 'out'println3area14@ "!ste 'out'println3volu e14@ A

A 2/ltiple in!eritance: In t+is t!pe ore t+an one super-class +aving single sub-class derived' % 8

4ierarc!ical in!eritance: In t+is t!pe one super-class is +aving ore t+an one sub-class'

2/lti#level in!eritance: In t+is t!pe derived class is derived $ro % a derived class'

Lect/re#5:

6,ception 4andling:
Definition: %n exception is an event* 1+ic+ occurs during t+e e0ecution o$ a progra * t+at disrupts t+e nor al $lo1 o$ t+e progra Vs instructions' T+e purpose o$ e0ception +andling ec+anis is to provide a eans to detect and report ec+anis

an e0ceptional circu stance so t+at appropriate action can be ta(en' T+e

suggests incorporation o$ a separate error +andling code t+at per$or s t+e $ollo1ing tas(s' .ind t+e proble 3/it t+e e0ception4 In$or t+at an error +as occurred3T+ro1 t+e e0ception4

Receive t+e error in$or ation3catc+ t+e e0ception4 Ta(e corrective actions3/andle t+e e0ception4 -iagra and "!nta0 o$ e0ception +andling code: try bloc( "tate ent t+at cause an e0ception 3E0ception object creater4

T+ro1s e0ception object

Catc! bloc( "tate ent t+at +andle t+e e0ception 3E0ception +andler4

Synta,: tr! : state ent@ 66generates an e0ception A catc+3E0ception-t!pe e4 : state ent@ 66processes t+e e0ception A 6,ample: class error1 : public static void : int a P 1J @ int b P T @ int c PT @ int 0 * !@ tr! : 0 P a 6 3b-c4 @ 66E0ception +ere ain3"tring args; <4

catc+3 %rit+ aticE0ception e 4 : "!ste 'out'println3=division b! Cero =4@ A ! P a 6 3b>c4@ "!ste 'out'println3 =! P = > !4@ AA 2/ltiple catc! statements : tr! : state ent @ A catc+ 3 E0ception-T!pe-1 e4 : state ent @ A catc+ 3 E0ception-T!pe-E e4 : state ent @ A catc+ 3 E0ception-T!pe-N e4

: state ent@ A Using -inally Statement tr! : state ent @ A $inall! : state ent@ A tr! : state ent@ A catc+ 3 4 : state ent A catc+3 4 : state ent@ A

$inall! : state ents@ A

!ro$ing o/r o$n 6,ceptions

T+is can be done using (e!1ord t+ro1 as $ollo1s: t!ro$ ne1 "hrowable#subclass @ E0a ple : i port java'i port'E0ception@ class #!E0ception e0tends E0ception : #!Ec0eption3"tring : super3 essage4 @ A A class Test#!E0ception : public static void : int 0PT*!P1JJJ@ tr! : $loat C P3$loat4 0 6 3$loat4 !@ i$3COJ'J14 : t+ro1 ne1 #!E0ception 3=Nu ber is too s all?4@ A ain3"tring args;<4 essage4

A catc+ 3#!E0ception e4 : "!ste 'out'println3=Caug+t ! e0ception?4@

"!ste 'out'println3e'get#essage344@ A $inall! : "!ste 'out'println3=I a A A A al1a!s +ere?4@

Lect/re#7: 2/ltit!reading: #ultit+reading is a conceptual progra divided into t1o or ing paradig 1+ere a progra 3 process 4 is

ore subprogra s 3 processes 4* 1+ic+ can be i ple ented can displa! an ani ation on t+e screen 1+ile

concurrentl!' .or e0a ple* one subprogra anot+er

a! build t+e ne0t ani ation to be displa!ed' T+is is so et+ing si ilar to to di$$erent people $or e0ecution

dividing a tas( into subtas(s and assigning t+e independentl! and si ultaneousl!'

class %8C :

8eginning

"ingle-T+readed bod! o$ e0ecution

End

Single# !readed 8rogram Once initiated b! t+e ain t+read* t+e t+reads %*8 and C run concurrentl! and s+are t+e

resources jointl!' It is li(e people living in joint $a ilies and s+aring certain resources a ong all o$ t+e ' T+e abilit! o$ a language to support concurrenc!' "ince t+reads in Java are subprogra s o$ a ultit+reads is re$erred to as ain application progra and

s+are t+e sa e processes'

e or! space* t+e! are (no1n as lig+t1eig+t t+reads or lig+t1eig+t 2ain !read

2ain 2et!od mod/le

"tart

"tart

"tart

!read A

!read + 2/lti# !readed 8rogram

!read C

!read States T+reads can be in one o$ $our states: Y Ne1 Y Runnable Y 8loc(ed Y -ead Eac+ o$ t+ese states is e0plained in t+e sections t+at $ollo1' 9e$ !reads

L+en !ou create a t+read 1it+ t+e ne1 operator$or e0a ple* ne1 T/Read3r4t+e t+read is not !et running' T+is eans t+at it is in t+e new state' L+en a t+read is in t+e ne1 state* t+e progra +as

not started e0ecuting code inside o$ it' % certain a ount o$ boo((eeping needs to be done be$ore a t+read can run' :/nnable !reads Once !ou invo(e t+e start not actuall! be running' It is up to t+e operating s!ste speci$ication does not call this a separate state, though. A running thread is still in the runnable state.) +loc;ed !reads % t+read enters t+e bloc$ed state 1+en one o$ t+e $ollo1ing actions occurs: Y T+e t+read goes to sleep b! calling t+e sleep et+od' to give t+e t+read ti e to run' 3T+e Java et+od* t+e t+read is runnable' % runnable t+read a! or a!

Y T+e t+read calls an operation t+at is bloc$ing on input!output* t+at is* an operation t+at 1ill not return to its caller until input and output operations are co plete' Y T+e t+read tries to ac7uire a loc( t+at is currentl! +eld b! anot+er t+read' Le discuss loc(s on page

Figure Thread states

A thread moves out of the blocked state and back into the runnable state by one of the following pathways.

Dead !reads
% t+read is dead $or one o$ t1o reasons:
Y It Y It

dies a natural deat+ because t+e run

et+od e0its nor all!' et+od' et+od t+ro1s a

dies abruptl! because an uncaug+t e0ception ter inates t+e run et+od' T+at

In particular* !ou can (ill a t+read b! invo(ing its stop T+read-eat+ error

object t+at (ills t+e t+read' /o1ever* t+e stop !our o1n

et+od is deprecated* and !ou s+ould not call it in

Declaring a t!read:
T+e t+read class can be e0tended as $ollo1s: class : ZZZZ'' ZZZZ' A "mplementing t!e r/n& ) met!od public void run3 4 : ZZZZ' ZZZZZ A Starting a ne$ t!read: #!t+read at+read P ne1 #!t+read3 4@ at+read'start3 4 !t+read e0tends T+read

6,ample: class % e0tends T+read : public void run3 4 :

$or 3 int iP1 @ iO PT @I>>4 : "!ste 'out'println3=$ro A "!ste 'out'println3:E0it $ro AA class 8 e0tends T+read : public void run3 4 : $or 3 int iP1 @ iO PT @I>>4 : "!ste 'out'println3=$ro A "!ste 'out'println3:E0it $ro AA class C e0tends T+read : public void run3 4 : 8?4@ t+read 8? > i4@ %?4@ t+read %? > i4@

$or 3 int iP1 @ iO PT @I>>4 : "!ste 'out'println3=$ro A "!ste 'out'println3:E0it $ro AA class t+readtest : public static void : ne1 %3 4'start3 4@ ne1 83 4'start3 4@ ne1 C3 4'start3 4@ AA ain3"tring args; <4 C?4@ t+read C? > i4@

Lect/re#<: Collections: Collection classes and inter$aces provides ec+anis to deal 1it+

collection o$ objects'%ll collections classes i ports java'util'5 pac(age' T+e di$$erent concrete collection classes in java are as $ollo1s:

ArrayList: It is an inde0ed se7uence t+at gro1s and s+rin(s d!na icall!' Lin;edList: %n ordered se7uence t+at allo1s e$$icient insertions and re oval at an! position' 4as!Set: It is an unordered collection t+at rejects duplicates' reeSet: It is a sorted set' 4as!2ap: It is a data structure t+at stores 2e!6value associations' ree2ap: It is a ap in 1+ic+ (e!s are sorted'

6,ample to implement ArrayList: I port java'util'5@ ,ublic class arra!listde o : ,ublic static void ain3"tring args; < 4

: %rra!ListOIntegerN a1 P ne1 %rra!ListOIntegerN 3 4 @ a1'add31J 4@ a1'add3 EJ4@ a1'add3 DJ4@ a1'add3 IJ4@ "!ste 'out'println3=%rra! list [s @ siCe:[d? a1'tostring3 4 * a1'siCe3 4 4@ a1're ove3ne1 Integer3DJ4 4@ a1're ove3J4@ "!ste 'out'println3=%rra! list [s @ siCe:[d? a1'tostring3 4 * a1'siCe3 4 4@ A A

Lect/re#=: ">O Streams: % strea in java is a pat+ along 1+ic+ data $lo1s'It +as a source and a

destination' Input "trea reads t+e data $ro source and pass t+e data to progra '

Output "trea

1rites t+e data $ro

progra

to destination'

Java Stream Classes: Java strea classes is divided into t1o t!pes classes classes

1' 8!te "trea

E' C+aracter strea 8!te strea 8!te strea creating and 8!te strea classes:

classes +ave been designed to provide $unctional $eatures $or anipulating strea s and $iles $or reading and 1riting b!tes' classes is divided into t1o t!pes classes classes classes are

1' Input"trea E' Output"trea

-i$$erent Input"trea .ileInput"trea -ataInput"trea ObjectInput"trea 8u$$eredInput"trea

-i$$erent output "trea s classes are .ileOutput"trea -ataOutput"trea ObjectOutput"trea

8u$$eredoutput"trea C+aracter strea classes is divided into t1o t!pes

1' Reader classes E' Lriter classes ,rogra to displa! contents o$ a $ile:

I port java'io5@ ,ublic class t!pe$ile : ,ublic static void : int i @ .ileInput"trea Tr! : .in Pne1 .ileInput"trea 3args; J< 4@ A Catc+3 .ileNot.oundE0ception e 4 : "!ste 'out'println3=$ile not $ound?4@ Return@ $in@ ain3"tring args; < 4 t+ro1s IOE0ception

A Catc+3%rra!Inde0OutO$8oundE0ception e4 : "!ste 'out'println3=java $ilena e?4@ Return@ A L+ile3I P$in'read3 4 4 Q P -14 "!ste 'out'print3 3c+ar4i4@ .in'close3 4@ A A

Lect/re#?: Abstract %indo$s ool;it&A% ): %bstract 1indo1s tool(it contains all t+e classes $or creating user inter$aces and $or painting grap+ics and i ages' % user inter$ace object suc+ as button or a scrollbar is called in %LT ter inolog! * a co ponent' Component class is t+e root o$ all %LT co ponents' T+e di$$erent co ponent classes are

8utton Label Te0t.ield C+ec(bo0 Co bobo0 )ridLa!out Te0t%rea "crolbar ,rogra to describe Label * Te0t.ield and 8utton:

I port java'a1t'5@ I port java'a1t'event'5@ I port java'applet'5@ 65 O%pplet code P =te p'class? 1idt+PEJJ +eig+tPEJJN 56 ,ublic class te p e0tends %pplet i ple ents %ctionListener : Te0t.ield tc*t$@ 8utton cal@ ,ublic void init3 4 : Label lc P ne1 Label3 = enter celcius = Label'LE.T4@

Label l$ P ne1 Label3 = .ar+en+it is = Label'LE.T4@ tcP ne1 Te0t.ield3T4@ t$Pne1 Te0t.ield3T4@ tc'setTe0t3=J?4@ t$'setTe0t3=J?4@ calPne1 8utton3=calculate?4@ add3lc4@ add3tc4@ add3l$4@ add3t$4@ add3cal4@ cal'add%ctionListener3t+is4@ A ,ublic void action,er$or ed3%ctionEvent ae4 : I$3ae'get"ource3 4 P P cal4 : -ouble celP-ouble'parse-ouble3tc'getTe0t3 4 4@ T$'setTe0t3 "tring'valueO$3&'J6T6J5cel>DE'J4 4@ A

A A

Lect/re#@: Applet 8rogramming: %pplets are s all java progra s t+at are pri aril! used in internet progra ing' T+e! can be transported over t+e internet $ro one co puter

to anot+er and run using t+e %pplet vie1er or an! 1eb bro1ser t+at supports Java' %pplet does not contain ain34 et+od'

.or at o$ %pplet progra :

I port java'a1t'5@ I port java'applet'5@ ,ublic class appletclassna e e0tends %pplet : ZZZZZZ'' ZZZZZZ'' ,ublic void paint3)rap+ics g4 : ZZZZZZ''66%ppletsoperations code ZZZZZZZ A A Applet Life cycle: T+e di$$erent states o$ applet li$e c!cles are 8orn state or initialiCation state Running state Idle state -ead state InitialiCation state: %pplet enters initialiCation state 1+en it is $irst loaded

Init3 4 $unction is used' "!nta0 ,ublic void init3 4 : ZZZZ66%ction ZZZZZ'' A Running "tate: %pplet enters running state 1+en t+e s!ste "!nta0 ,ublic void start3 4 : ZZZZZZZZ'66%ction ZZZZZZZZ' A Idle or stopped state: %n applet beco es idle 1+en it is stopped $ro "!nta0 ,ublic void stop3 4 : running' calls t+e start et+od'

ZZZZZZ'66action ZZZZZZ' A -ead state: %n applet is said to be dead 1+en it is re oved $ro "!nta0 ,ublic void destro!3 4 : ZZZZZZ66%ction ZZZZZZ' A e or!'

AB.%!at is m/ltit!readingC 6,plain t!e life cycle of a t!read. SOLUTION:


#ultit+reading is a conceptual progra divided into t1o or ing paradig 1+ere a progra 3 process 4 is

ore subprogra s 3 processes 4* 1+ic+ can be i ple ented can displa! an ani ation on t+e screen 1+ile

concurrentl!' .or e0a ple* one subprogra anot+er

a! build t+e ne0t ani ation to be displa!ed' T+is is so et+ing si ilar to to di$$erent people $or e0ecution

dividing a tas( into subtas(s and assigning t+e independentl! and si ultaneousl!'

class %8C :

8eginning "ingle-T+readed bod! o$ e0ecution

End A

Single# !readed 8rogram Once initiated b! t+e ain t+read* t+e t+reads %*8 and C run concurrentl! and s+are t+e

resources jointl!' It is li(e people living in joint $a ilies and s+aring certain resources a ong all o$ t+e ' T+e abilit! o$ a language to support concurrenc!' "ince t+reads in Java are subprogra s o$ a ultit+reads is re$erred to as ain application progra and

s+are t+e sa e processes'

e or! space* t+e! are (no1n as lig+t1eig+t t+reads or lig+t1eig+t

2ain !read

2ain 2et!od mod/le

"tart

"tart

"tart

!read A

!read +

!read C

2/lti# !readed 8rogram Life cycle of a !read : Li$e c!cle o$ a T+read can +ave $our states: Y Ne1 Y Runnable Y 8loc(ed Y -ead

Diagram for Life cycle of a t!read:

9e$ state of !read: L+en !ou create a t+read 1it+ t+e ne1 operator $or e0a ple* ne1 T+read3 4 t+e t+read is not !et running' T+is t+e progra eans t+at it is in t+e new state' L+en a t+read is in t+e ne1 state*

+as not started e0ecuting code inside o$ it' % certain a ount o$ boo((eeping

needs to be done be$ore a t+read can run' :/nnable state of a !read:

Once !ou invo(e t+e start

et+od* t+e t+read is runnable' % runnable t+read

a! or

a!

not actuall! be running' It is up to t+e operating s!ste +loc;ed state of a !read

to give t+e t+read ti e to run'

% t+read enters t+e bloc$ed state 1+en one o$ t+e $ollo1ing actions occurs: Y T+e t+read goes to sleep b! calling t+e sleep et+od'

Y T+e t+read calls an operation t+at is bloc$ing on input!output* t+at is* an operation t+at 1ill not return to its caller until input and output operations are co plete' Y T+e t+read tries to ac7uire a loc( t+at is currentl! +eld b! anot+er t+read' Le discuss loc(s on page' % t+read oves out o$ t+e bloc(ed state and bac( into t+e runnable state b! one o$ t+e $ollo1ing pat+1a!s'

Dead state of a !read:


% t+read is dead $or one o$ t1o reasons: Y It dies a natural deat+ because t+e run et+od e0its nor all!' et+od' et+od t+ro1s a

Y It dies abruptl! because an uncaug+t e0ception ter inates t+e run In particular* !ou can (ill a t+read b! invo(ing its stop T+read-eat+ error object t+at (ills t+e t+read' et+od' T+at

A2.%rite a program to create a /ser defined 6,ception called D9o 2atc! ,ceptionE
t!at t!ro$s an arbitrary message $!en a string is not e./al to D"9D"AE. SOLUTION: i port java'i port'E0ception@ class No#atc+E0ception e0tends E0ception

: No#atc+E0ception3"tring : super3 essage4 @ A A class TestNo#atc+E0ception : public static void : "tring @ ain3"tring args;<4 essage4

"canner sPne1 "canner3"!ste 'in4@ "!ste 'out'println3=enter a string?4@ Ps'ne0t3 4@ tr! : I$3 QP?IN-I%?4 : t+ro1 ne1 No#atc+E0ception 3="tring is not india?4@ A A catc+ 3No#atc+E0ception e4 :

"!ste 'out'println3=Caug+t No#atc+E0ception?4@ "!ste 'out'println3e'get#essage344@ A A A

A3.%!at are applets C 6,plain t!eir /sage. 4o$ are t!ey different from java programs.
SOLUTION:

%pplets are s all java progra s t+at are pri aril! used in internet progra ing' T+e! can be transported over t+e internet $ro one co puter

to anot+er and run using t+e %pplet vie1er or an! 1eb bro1ser t+at supports Java' %pplet does not contain Usage o$ %pplet: %pplets can be used $or internet progra ing' ain34 et+od'

It can be used to e0tend t+e capabilities o$ +t l 1eb-pages' Difference bet$een java applet and Java programs: ---Java applets are s all java progra used in internet progra ing b! e bedding inside +t l docu ents' ---Java applets are e bedded inside +t l docu ent and en+ance capabilities o$ +t l 1ebpages --Java applets cannot +ave et+od' --Java applets can onl! be e0ecuted in 1eb bro1ser or appletvie1er' ain34 ----Java progra s are progra s used $or applications develop ent' --Java progra s cannot e bedded inside +t l docu ent'

--Java progra s 34 et+od'

ust +ave

ain

---Java progra s can be e0ecuted b! java interpreter'

A.5. %!at is an interface C 6,plain $it! a s/itable e,ample. 4o$ m/ltiple


"n!eritance is implemented in java. SOLUTION: Inter$ace is a class 1+ic+ consists o$ constant variables and unde$ined et+ods' Inter$ace

can be treated as te plates used b! di$$erent classes b! in+erit t+e inter$ace' Inter$ace cant create an! objects' It is onl! used b! ot+er classes t+ose in+erit it' Inter$ace can be used to i ple ent "!nta0 o$ Inter$ace: Inter$ace inter$ace-na e : 66.inal or constant variables@ 66Unde$ined A E0a ple o$ Inter$ace: Inter$ace product : .inal int productno@ ,ublic void getdescription3 4@ A Using interface for m/ltiple in!eritance: Inter$ace is used to i ple ent inter$aces as belo1' Inter$ace % Inter$ace 8 ultiple in+eritances b! in+eriting a class $ro ultiple et+ods@ ultiple in+eritances'

Class C 6,ample of interface to implement m/ltiple in!eritance: Inter$ace % : .inal Int a@ Boid getdata34@ A Inter$ace 8 : .inal int b@ Boid putdata34@ A Class C i ple ents % * 8 : Int c@ Boid getdata34 : aPI@ "!ste 'out'println3a4@ A Boid putdata34 : bPT@ "!ste 'out'println3b4@ AA Class test :

,ublic static void test t1@ t1'getdata34@ t1'putdata34@ A

ain3"tring args;<4

A.7. %!y is java more s/itable as compared to ot!er lang/age.


SOLUTION: Java is ore suitable as co pared to ot+er languages because o$ t+e $ollo1ing $eatures independent and portable

,lat$or

Object Oriented Robust and "ecure -istributed .a iliar* "i ple and s all #ultit+readed and Interactive /ig+ ,er$or ance -!na ic and E0tensible Co piled and Interpreted 8latform independent and 8ortable Java is plat$or independent because o$ b!te code 1+ic+ can be interpreted b! an! independent java is portable'

s!ste ' 8ecause o$ plat$or Object Oriented:

Java is purel! object oriented progra

ing language'-ata +iding*

encapsulation*pol! orp+is *in+eritance properties are present' :ob/st and Sec/re:

Java is robust because Java 1or(s as usual 1+en an! e0tension is secure because o$ its b!te code and case sensitiveness' -amiliarF Simple and small Java is eas! to understandable *s all and $a ilier' 2/ltit!readed and "nteractive: Java support concurrentl!' Dynamic and 6,tensible Java 1or(s d!na icall! and can be easil! e0tensible'

ade in java'Java is

ultit+reading because in java di$$erent parts o$ a progra

can e0ecute

A.<. %!at do yo/ mean by byte code .6,plain its $or;ing..


SOLUTION:

8!te code is a code $or ed b! co piler in java +aving 'class e0tension Java bytecode is t+e $or o$ instructions t+at t+e Java virtual ulti-b!te instructions' ac+ine

e0ecutes' Eac+ b!te code opcode is one b!te in lengt+* alt+oug+ so e re7uire para eters* resulting in so e

To understand t+e details o$ t+e b!tecode* 1e need to discuss +o1 a Java Birtual #ac+ine 3JB#4 1or(s regarding t+e e0ecution o$ t+e b!tecode' % JB# is a stac(-based ac+ine' Eac+ t+read +as a JB# stac( 1+ic+ stores et+od is invo(ed* and consists o$ an et+od' Conceptuall!* it ig+t loo(

frames' % $ra e is created eac+ ti e a constant pool o$ t+e class o$ t+e current li(e t+is:

operand stac(* an arra! o$ local variables* and a re$erence to t+e runti e

-ig/re . A frame

T+e arra! o$ local variables* also called t+e local variable table* contains t+e para eters o$ t+e et+od and is also used to +old t+e values o$ t+e local et+od* t+e re$erence is stored at location et+od para eter is stored in variables' T+e para eters are stored $irst* beginning at inde0 J' I$ t+e $ra e is $or a constructor or an instance and so on' .or a static J' T+en location 1 contains t+e $irst $or al para eter* location E t+e second* et+od* t+e $irst $or al location J* t+e second in location 1* and so on'

A.=.4o$ is platform independent feat/re of java implemented. 6,plain role of main & ) met!od in e,ec/tion of java program.

SOLUTION: Java is plat$or independent because o$ its b!te code creation b! co piler t+at is +andled b! Java Birtual #ac+ine' 8!te code is o$ 'class e0tension and t+at can be e0ecuted b! an! plat$or t+eir o1n interpreter' -iagra $or plat$or independence:
Java "ource $ile3'java $ile4

b!

8!te code 3'class $ile4

Lindo1s s!ste 3+aving JB#4

Uni0 s!ste 3+aving JB#4

"olaris s!ste 3+aving JB#4

Lindo1s interpreter

Uni0 interpreter

"olaris interpreter

E0e $ile

E0e $ile

E0e $ile

:ole of main&) met!od:

2ain& ) met!od is a static met!od t!at can a/tomatically called $it!o/t /se of any objects creation. 2ain &) met!od is t!e first met!od e,ec/ted by C8U after t!at any met!ods are e,ec/ted. All objects are created inside t!e main& ) met!od and met!ods are called inside main& ) met!od. %it!o/t main & ) met!od no program is created in java application.

A.=.%!y e,ceptional errors occ/rs d/ring e,ec/tion of program. Disc/ss /sage of finally bloc;.
SOLUTION:

6,ceptional errors occ/rs d/ring e,ec/tion of program beca/se in t!e time of program e,ec/tion some /n/s/al condition occ/rs and disr/pts t!e normal flo$ of e,ec/tion. s/c! as a n/mber division by 1eroF file not fo/nd F array inde, o/t of bo/nd F arit!metic e,ception etc. An exception is an eventF $!ic! occ/rs d/ring t!e e,ec/tion of a programF t!at disr/pts t!e normal flo$ of t!e programGs instr/ctions. !e p/rpose of e,ception !andling mec!anism is to provide a means to detect and report an e,ceptional circ/mstance so t!at appropriate action can be ta;en. !e mec!anism s/ggests incorporation of a separate error !andling code t!at performs t!e follo$ing tas;s. -ind t!e problem&4it t!e e,ception)

"nform t!at an error !as occ/rred& !ro$ t!e e,ception) :eceive t!e error information&catc! t!e e,ception) a;e corrective actions&4andle t!e e,ception) Diagram and Synta, of e,ception !andling code:

try bloc( "tate ent t+at cause an e0ception 3E0ception object creater4

T+ro1s e0ception object

Catc! bloc( "tate ent t+at +andle t+e e0ception 3E0ception +andler4

Usage of finally bloc;. .inall! is a (e!1ord used in e0ception +andling ec+anis \ .inall! is

Lritten a$ter tr! and catc+ state ent 'T+e state ents 1ritten inside $inall! is ust e0ecute 1+et+er t+ere is e0ception $ound or not'
Synta, of -inally Statement tr! : state ent @ A $inall! : state ent@ A tr! : state ent@ A catc+ 3 4 : state ent A .inall! : "tate ent

You might also like