Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts: • • • • • • • • •
Polmorphism !nheritance "ncapsulation Abstraction #lasses Objects !nstance $ethod $essage Parsing !n this chapter, we will loo% into the concepts #lasses and Objects.
•
•
Object - Objects have states and behaviors. "&le: A dog has states - color, name, breed as well as behaviors -wagging, bar%ing, eating. An An object is an instance of a class. Class - A class can be defined as a template'blue print template'blue print that that describes the behaviors'states that object of its tpe support.
Objects in Java: Let us now loo% deep into what are objects. !f we consider the real-world we can find man objects around us, #ars #ars,, (ogs, )umans, etc. All these objects have a state and behavior. !f we consider a dog, then its state is - name, breed, color, and the behavior is - bar%ing, wagging, running !f ou ou comp compar aree the the soft softwa ware re obje object ct with with a real real worl world d obje object ct,, the the have have ver ver sim similar ilar characteristics. *oftware objects also have a state and behavior. A software object+s state is stored in fields and behavior is shown via methods. *o in software development, methods operate on the internal state of an object and the object-toobject communication is done via methods. #lasses in Java: A class is a blue print from which individual objects are created. A sample of a class is given below: public class (og (og *tring breed *tring breed int age int age *tring color *tring color
void bar%ing/ void bar%ing / 0 void hungr/ void hungr / 0 void sleeping/ void sleeping / 0 0 A class can contain an of the following variable tpes. •
•
•
Local variables: 1ariables 1ariables defined inside methods, constructors or bloc%s are called local variables. 2he variable will be declared and initiali3ed within the method and the variable will be destroed when the method has completed. !nstance ce variab variables les are variab variables les within within a class class but outside outside an Instance variables: variables: !nstan method. 2hese variables are instantiated when the class is loaded. !nstance variables can be accessed from inside an method, constructor or bloc%s of that particular class. #lass variab variables les are variab variables les declared declared with with in a class, class, outside outside an Class variables: variables: #lass method, with the static %eword.
A class can have an number of methods to access the value of various %inds of methods. !n the above e&le, bar%ing/, hungr/ and sleeping/ are methods. 4elow mentioned mentioned are some of the important important topics that need to be discussed when loo%ing into classes of the Java Language. #onstructors: 5hen discussing about classes, one of the most important sub topic would be constructors. "ver class has a constructor. !f we do not e&plicitl write a constructor for a class the Java compiler builds a default constructor for that class. "ach time a new object is created, at least one constructor will be invo%ed. 2he main rule of constructors is that the should have the same name as the class. A class can have more than one constructor. "&le of a constructor is given below: public class Pupp Pupp public pupp public pupp/ / 0 public pupp*tring public pupp *tring name name/ / '' 2his constructor has one parameter, name name..
0 0 Java also supports *ingleton #lasses where ou would be able to create onl one instance of a class. #reating an Object: As mentioned previousl, a class provides the blueprints for objects. *o basicall an object is created from a class. !n Java, the new %e word is used to create new objects. 2here are three steps when creating an object from a class: • • •
Declaration: A variable declaration with a variable name with an object tpe. Instantiation: 2he +new+ %e word is used to create the object. Initialization: 2he +new+ %eword is followed b a call to a constructor. 2his call initiali3es the new object.
"&le of creating an object is given below:
public class Pupp public Pupp*tring name/ '' 2his constructor has one parameter, name. *stem.out. println6Passed 7ame is :6 8 name / 0 public static void main*tring 9args/ '' ;ollowing statement would create an object mPupp Pupp mPupp < new Pupp 6tomm6 / 0 0 !f we compile and run the above program, then it would produce the following result: Passed 7ame is :tomm Accessing !nstance 1ariables and $ethods: !nstance variables and methods are accessed via created objects. 2o access an instance variable the full =ualified path should be as follows: '> ;irst create an object >' Object?eference < new #onstructor / '> 7ow call a variable as follows >'
Object?eference.variable7ame '> 7ow ou can call a class method as follows >' Object?eference.$ethod7ame/ "&le: 2his e&le e&plains how to access instance variables and methods of a class:
public class Pupp int puppAge public Pupp*tring name/ '' 2his constructor has one parameter, name. *stem.out. println6Passed 7ame is :6 8 name / 0 public void setAge int age / puppAge < age 0 public int getAge / *stem.out. println6Pupp+s age is :6 8 puppAge / return puppAge 0 public static void main*tring 9args/ '> Object creation >' Pupp mPupp < new Pupp 6tomm6 /
'> #all class method to set pupp+s age >' mPupp.setAge @ /
'> #all another class method to get pupp+s age >' mPupp.getAge / '> ou can access instance variable as follows as well >' *stem.out. println61ariable 1alue :6 8 mPupp. puppAge / 0
0 !f we compile and run the above program, then it would produce the following result:
Passed 7ame is :tomm Pupp+s age is :@ 1ariable 1alue :@ *ource file declaration rules: As the last part of this section let+s now loo% into the source file declaration rules. 2hese rules are essential when declaring classes, import statements and package statements in a source file. •
2here can be onl one public class per source file.
•
A source file can have multiple non public classes.
•
2he public class name should be the name of the source file as well which should be appended b .java at the end. ;or e&le : 2he class name is . public class Employee{} 2hen the source file should be as "mploee.java.
•
!f the class is defined inside a pac%age, then the pac%age statement should be the first statement in the source file.
•
!f import statements are present then the must be written between the pac%age statement and the class declaration. !f there are no pac%age statements then the import statement should be the first line in the source file.
•
!mport and pac%age statements will impl to all the classes present in the source file. !t is not possible to declare different import and'or pac%age statements to different classes in the source file. #lasses have several access levels and there are different tpes of classes abstract classes, final classes, etc. ! will be e&plaining about all these in the access modifiers chapter. Apart from the above mentioned tpes of classes, Java also has some special classes called !nner classes and Anonmous classes. Java Pac%age: !n simple, it is a wa of categori3ing the classes and interfaces. 5hen developing applications in Java, hundreds of classes and interfaces will be written, therefore categori3ing these classes is a must as well as ma%es life much easier. !mport statements: !n Java if a full =ualified name, which includes the pac%age and the class name, is given then the compiler can easil locate the source code or classes. !mport statement is a wa of giving the proper location for the compiler to find that particular class. ;or e&le, the following line would as% compiler to load all the classes available in director javaBinstallation'java'io :
import java.io.> A *imple #ase *tud: ;or our case stud, we will be creating two classes. 2he are "mploee and "mploee2est. ;irst open notepad and add the following code. ?emember this is the "mploee class and the class is a public class. 7ow, save this source file with the name "mploee.java. 2he "mploee class has four instance variables name, age, designation and salar. 2he class has one e&plicitl defined constructor, which ta%es a parameter.
import java.io.> public class "mploee *tring name int age *tring designation double salar '' 2his is the constructor of the class "mploee public "mploee*tring name/ this.name < name 0 '' Assign the age of the "mploee to the variable age. public void empAgeint empAge/ age < empAge 0 '> Assign the designation to the variable designation.>' public void emp(esignation*tring emp(esig/ designation < emp(esig 0 '> Assign the salar to the variable salar.>' public void emp*alardouble emp*alar/ salar < emp*alar 0 '> Print the "mploee details >' public void print"mploee/ *stem.out. println67ame:68 name / *stem.out. println6Age:6 8 age / *stem.out. println6(esignation:6 8 designation / *stem.out. println6*alar:6 8 salar/ 0
0 As mentioned previousl in this tutorial, processing starts from the main method. 2herefore inorder for us to run this "mploee class there should be main method and objects should be created. 5e will be creating a separate class for these tas%s. Civen below is the EmployeeTest class, which creates two instances of the class "mploee and invo%es the methods for each object to assign values for each variable. *ave the following code in "mploee2est.java file import java.io.> public class "mploee2est public static void main*tring args9/ '> #reate two objects using constructor >' "mploee empOne < new "mploee6James *mith6/ "mploee emp2wo < new "mploee6$ar Anne6/
'' !nvo%ing methods for each object created empOne.empAge@D/ empOne.emp(esignation6*enior *oftware "ngineer6/ empOne.emp*alarEFFF/ empOne. print"mploee/
emp2wo.empAge@E/ emp2wo.emp(esignation6*oftware "ngineer6/ emp2wo.emp*alarGFF/ emp2wo. print"mploee/ 0
0 7ow, compile both the classes and then run EmployeeTest to see the result as follows: # :H javac "mploee. java # :H vi "mploee2est. java # :H javac "mploee2est. java # :H java "mploee2est 7ame:James *mith Age:@D (esignation:*enior *oftware "ngineer *alar:EFFF.F 7ame:$ar Anne Age:@E (esignation:*oftware "ngineer *alar:GFF.F
1ariables are nothing but reserved memor locations to store values. 2his means that when ou create a variable ou reserve some space in memor. 2here are two data tpes available in Java: Primitive (ata 2pes ?eference'Object (ata 2pes Primitive (ata 2pes: bte: 4te data tpe is an I-bit signed two+s complement integer. (efault value is F short: *hort data tpe is a ED-bit signed two+s complement integer. (efault value is F. "&le: short s < EFFFF, short r < -@FFFF int: !nt data tpe is a @-bit signed two+s complement integer.
2he default value is F. "&le: int a < EFFFFF, int b < -@FFFFF long: Long data tpe is a DK-bit signed two+s complement integer. float: ;loat data tpe is a single-precision @-bit !""" GK floating point. ;loat is mainl used to save memor in large arras of floating point numbers. (efault value is F.Ff. double: double data tpe is a double-precision DK-bit !""" GK floating point.
(efault value is F.Fd. "&le: double dE < E@.K boolean: boolean data tpe represents one bit of information. 2here are onl two possible values: true and false. 2his data tpe is used for simple flags that trac% true'false conditions. (efault value is false. "&le: boolean one < true char: ?eference (ata 2pes: ?eference variables are created using defined constructors of the classes. 2he are used to access objects. 2hese variables are declared to be of a specific tpe that cannot be changed. ;or e&le, "mploee, Pupp etc. #lass objects, and various tpe of arra variables come under reference data tpe. (efault value of an reference variable is null. A reference variable can be used to refer to an object of the declared tpe or an compatible tpe. "&le: Animal animal < new Animal6giraffe6/ Java Literals: A literal is a source code representation of a fi&ed value. 2he are represented directl in the code without an computation. Literals can be assigned to an primitive tpe variable. ;or e&le: bte a < DI char a < +A+ int decimal < EFF int octal < FEKK int he&a < F&DK
Ac c es sCont r ol Modi fi er s : J av apr o v i d esanumbe rofac c es smodi fi er st ose tac c es sl e v el sf orc l as s es ,v ar i abl e s,me t hodsan d c ons t r uc t or s .Thef ourac c es sl ev el sar e: •
Vi s i bl et ot h epac k age ,t hed ef aul t .Nomodi fi er sar eneeded.
•
Vi s i bl et ot hec l as sonl y( p r i v at e) .
•
Vi s i bl et ot hewor l d( publ i c ) .
•
Vi s i bl et ot hepac kageandal l s ubc l as s es( pr ot ec t ed) .
NonAcc essModi fier s: J a v ap r o v i d esan umbe ro fn on a cc es smo di fi er st oa ch i e v ema nyot h erf u nc t i o na l i t y . • • • •
Thes t at i c modi fi erf orc r e at i ngc l as sme t ho dsandv ar i ab l es Thefinal modi fi erf orfi nal i z i ngt hei mpl ement at i onsofc l as s es ,met hods ,andvar i abl es . Theabs t r ac t modi fi erf orc r ea t i nga bs t r a ctc l as s esandme t hod s. Thes y nc hr oni z ed andv ol at i l e mod i fi er s ,whi c har eus edf ort hr ea ds .
I nJ a v a,a l lv a r i a bl e s mu s tb ed ec l ar e db ef o r et h eyc an b eu se d.Th eb as i cf o r mo fav a r i ab l e dec l ar at i oni ss ho wnher e : type identifier [ = value][, identifier [= value] ...] ;
Thet y p e i soneofJ av a' sdat at y pes .Th ei dent i fi er i st hen ameoft h ev a r i abl e.T odec l a r emor et h an onev a r i a bl eoft hes pec i fi edt y pe ,us eac ommas epar at e dl i s t . He r ea r es e v er a le x ampl e so fv a r i a bl ed ec l ar a t i o nso fv a r i o ust y pe s.No t et h ats o mei n cl u dea n i ni t i al i z at i on. int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing // d and f. byte z = ; // initializes z. double pi = 3.!"!5#; // declares an appro$imation of pi. char $ = %$%; // the variable $ has the value %$%.
Thi schapt erwi l le xpl ai nv ar i ousv ar i abl et y pesav ai l abl ei nJ av aLanguage.Ther ear et hr eek i ndsof v ar i abl esi nJ av a:
•
Loc al v ar i abl es
•
I ns t anc ev ar i abl es
•
Cl as s / s t at i cv ar i abl es
Loc al v ar i abl es : Loc al v ar i abl esar edec l ar edi nmet hods ,c ons t r uc t or s ,orbl oc k s.
•
•
L oc a lv a r i a bl e sa r ec r e at e d wh en t h e me t h od ,c o ns t r u c t o rorb l o c ki se nt e r e da nd t h e v ar i abl ewi l l bedes t r o yedonc ei te xi t st hemet hod,c ons t r uc t ororbl oc k.
•
Ac c es smodi fi er sc anno tb eus edf orl oc al v a r i a bl e s.
•
Loc al v ar i abl esar ev i s i bl eonl ywi t hi nt hedec l ar edmet hod,c ons t r uc t ororbl oc k.
•
Loc al v ar i abl esar ei mpl ement edats t ac kl ev el i nt er nal l y .
•
The r ei snodef aul tv al uef orl oc alv ar i abl ess ol oc alv ar i ab l ess houl dbedec l ar e d an d an i ni t i al v al ues houl dbeas si gnedbef or et hefi r s tus e.
Ex ampl e: He r e,age i sal oc alv ar i abl e.Thi si sd efi nedi n si d epupAge( ) me t hodandi t ss copei sl i mi t edt ot hi s me t h odon l y . public class &est' public void pup(ge)*' int age = +; age = age -; ystem.out.println)0uppy age is 1 age*; 2
public static void main)tring args[]*' &est test = ne &est)*; test.pup(ge)*; 2
2
Thi swoul dpr oduc et hef ol l o wi ngr es ul t : 0uppy age is1 -
Ex ampl e: Fo l l o wi n ge x a mp l eu s esage wi t houti ni t i al i z i ngi t ,s oi twoul dgi v eaner r oratt het i meofc ompi l at i on.
public class &est' public void pup(ge)*' int age; age = age -; ystem.out.println)0uppy age is 1 age*; 2
public static void main)tring args[]*' &est test = ne &est)*; test.pup(ge)*; 2
2
Thi swoul dpr oduc et hef ol l owi nger r orwhi l ecompi l i ngi t : &est.4ava1"1variable number might not have been initialized age = age -; ! error
I ns t anc ev ar i abl es : •
•
•
•
I ns t anc ev ar i abl esar edec l ar edi nac l as s,butout s i deame t hod,c ons t r uc t ororan ybl oc k. Whenas pac ei sal l oc at edf oranobj ec ti nt heheap,as l otf oreac hi ns t anc ev ar i abl ev al uei s c r eat ed. I n s t a nc ev a r i ab l e sa r ec r e at e dwh ena no bj e cti sc r e at e dwi t ht h eu seo ft h ek e y wo r d' n ew' a ndd es t r o y edwh ent h eo bj e cti sde s t r o y ed . I nst ance var i abl es hol d val ues t hatmustbe r ef er enced by mor et han one met hod, c ons t r uc t ororbl oc k,ores sent i al par t sofanobj ec t ' sst at et hatmus tbepr es entt hr oughoutt hec l as s.
•
I ns t anc ev ar i abl esc anbedec l ar edi nc l as sl e vel bef or eoraf t erus e.
•
Ac c es smodi fi er sc anbegi v e nf o ri ns t anc ev ar i abl es .
•
•
The i ns t anc ev ar i ab l es a r ev i s i bl ef o ral lme t ho ds ,c o ns t r uc t or s and bl oc ki nt h ec l as s . Nor mal l y ,i ti sr ec ommendedt omak et hes ev ar i abl espr i v at e( ac ces sl e vel ) .Howev erv i s i bi l i t yf or s ub cl as s esc anbegi v enf ort hes ev a r i abl e swi t ht heus eofa cc es smo di fi er s . I ns t anc ev ar i abl esha vedef aul tv al ues .Fornumber st hedef aul tv al uei s0,f orBool eansi ti s f al s eandf orobj ec tr ef er enc esi ti snul l .Val uescanbeas si gneddur i ngt hedec l ar at i onorwi t hi nt he c o n s t r u c t o r .
•
I ns t a nc ev a r i a bl e sc anbea cc es s eddi r e ct l yb yc al l i ngt h ev ar i ab l ena mei n si det hec l as s . Ho we v erwi t h i ns t at i cme t hodsanddi ff er entc l a ss(wheni ns t an cev ar i ab l esar egi v enac c es s i bi l i t y ) s houl dbec al l edus i ngt hef ul l yqual i fi edname.Ob j e ct Re f er en c e. Va r i a bl e Na me .
Ex ampl e: import 4ava.io.6; public class 7mployee' // this instance variable is visible for any child class. public tring name; // salary variable is visible in 7mployee class only. private double salary;
// &he name variable is assigned in the constructor. public 7mployee )tring emp8ame*' name = emp8ame; 2 // &he salary variable is assigned a value. public void setalary)double empal*' salary = empal; 2 // &his method prints the employee details. public void print7mp)*' ystem.out.println)name 1 name *; ystem.out.println)salary 1 salary*; 2
public static void main)tring args[]*' 7mployee emp9ne = ne 7mployee):ansia*; emp9ne.setalary)!+++*; emp9ne.print7mp)*; 2
2
Thi swoul dpr oduc et hef ol l o wi ngr es ul t : name 1 :ansia salary 1!+++.+
Cl as s / s t at i cv ar i abl es : •
•
Cl as sv ar i abl esal s ok no wnass t at i cv ar i abl esar edec l ar edwi t ht he s t at i c k e y wo r di nac l a ss , butout s i deame t h od,c on st r u ct oro rabl o ck . Th er ewo ul do nl ybeo nec o pyofe ac hc l a s sv a r i a bl ep erc l a s s ,r e ga r d l e s so fh ow ma ny obj ec t sar ec r eat edf r om i t .
•
•
St a t i cv a r i a bl e sa r er a r el yu se do t h ert h an b ei n g de c l a r e da sc o ns t a nt s .Co ns t an t sa r e v ar i abl est hatar edec l ar edaspubl i c / pr i v at e,fi nalands t at i c .Cons t antv ar i abl esne verc hangef r om t hei ri ni t i al v al ue. St at i cv ar i abl esar es t or ed i ns t at i cmemor y .I ti sr ar et o us es t at i cv ar i abl esot hert han dec l ar edfi nal andus edasei t herpubl i corpr i v at ec ons t ant s . St a t i cv ar i ab l e sa r ec r e at e dwh ent h ep r o gr am s t a r t san dd es t r o y edwh ent h ep r o gr a ms t o ps .
•
•
•
Vi s i bi l i t yi ss i mi l art oi ns t anc ev ar i abl es .Howev er ,mos ts t at i cv ar i abl esar edec l ar edpubl i c s i nc et he ymus tbea vai l abl ef orus er soft hec l as s. De f au l tv a l u esa r es ame a si n st a nc ev a r i a bl e s.Fo rnu mb er s ,t h ed ef a ul tv a l u ei s0 ;f o r Bool ean s,i ti sf al s e;a nd f orobj ec tr ef er en ces ,i ti s nu l l .Val ues c an b ea ss i gned dur i ng t he dec l ar at i onorwi t hi nt hec ons t r uc t or .Addi t i onal l yv al uesc anbeas si gnedi ns pec i als t at i ci ni t i al i z er bl oc k s . St at i cv ar i abl escanbeac c es s edb yc al l i ngwi t ht hec l as sname.Cl assName. Var i abl eName .
•
•
Whendec l ar i ngc l as sv ar i abl esaspubl i cst at i cfinal ,t henv ar i abl esnames( c ons t ant s )ar eal l i nup pe rc as e.I ft h es t a t i cv a r i a bl e sa r eno tp u bl i ca ndfi na lt h en ami n gs y nt a xi st h es amea s i ns t anc eandl oc al v ar i abl es .
Ex ampl e: import 4ava.io.6; public class 7mployee' // salary variable is a private static variable private static double salary; // <70(:&78& is a constant public static final tring <70(:&78& =
public static void main)tring args[]*' salary = !+++; ystem.out.println)<70(:&78& average salary1salary*; 2
2
Thi swoul dpr oduc et hef ol l o wi ngr es ul t :
Not e:I ft h ev a r i a bl e sa r ea c c es sf r o m a no ut s i d ec l a s st h ec o ns t a nts h ou l db ea c c es s e da s Empl oy ee . DEPARTMENT
Modi fier s ar e keywor ds t hat you add t ot hose defini t i ons t o change t hei r meani ngs. The J a v al a ng ua gehasawi dev ar i et yofmodi fi er s ,i nc l udi ngt hef ol l owi ng: •
J a v aAc c e s sMo di fi e r s
•
NonAcc essModi fier s Touseamodi fier ,y oui nc l udei t sk e ywor di nt hede fini t i onofac l as s ,me t h od,o rv ar i a bl e.Th e modi fi erpr ec edest her es toft hes t at ement ,asi nt hef ol l o wi nge xampl es( I t al i cones ) : public class class8ame '
// ... 2 private boolean my>lag; static final double ees = #.5; protected static final int ?9@AB<&C = "; public static void main)tring[] arguments* '
// body of method 2
Ac c es sCont r ol Modi fi er s : J av apr o v i d esanumbe rofac c es smodi fi er st ose tac c es sl e v el sf orc l as s es ,v ar i abl e s,me t hodsan d c ons t r uc t or s .Thef ourac c es sl ev el sar e: •
Vi s i bl et ot h epac k age ,t hed ef aul t .Nomodi fi er sar eneeded.
•
Vi s i bl et ot hec l as sonl y( p r i v at e) .
•
Vi s i bl et ot hewor l d( publ i c ) .
•
Vi s i bl et ot hepac kageandal l s ubc l as s es( pr ot ec t ed) .
NonAcc essModi fier s: J a v ap r o v i d esan umbe ro fn on a cc es smo di fi er st oa ch i e v ema nyot h erf u nc t i o na l i t y . •
Thes t at i c modi fi erf orc r e at i ngc l as sme t ho dsandv ar i ab l es
•
Thefinal modi fi erf orfi nal i z i ngt hei mpl ement at i onsofc l as s es ,met hods ,andvar i abl es .
•
Theabs t r ac t modi fi erf orc r ea t i nga bs t r a ctc l as s esandme t hod s.
•
Thes y nc hr oni z ed andv ol at i l e mod i fi er s ,whi c har eus edf ort hr ea ds .
OPERATORSI NJAVA
J av apr o vi desar i c hs etofoper at or s t omani p ul a t ev ar i abl es .Wec andi v i dea l lt heJ a vaope r at or s i nt ot hef ol l owi nggr oups : •
Ar i t hmet i cOper at or s
•
Rel at i onal Oper at or s
•
Bi t wi s eOpe r at o r s
•
Lo gi c al Oper at or s
•
As s i g nme ntOp er a t o r s
•
Mi s cOp er a t o r s Th er ema ybeas i t u at i o nwh enwen ee dt oe x e c ut eab l o c ko fc o des ev e r a ln umb ero ft i me s ,a ndi s of t enr ef er r edt oasal oop. LOOP J a v ah asv er yfl ex i b l et h r eel o op i n gme ch an i s ms .Yo uc a nu s eo neo ft hef o l l o wi n gt hr e el o op s:
•
wh i l eLo op
•
do. . . whi l eLoop
•
f o rL oop AsofJ a v a5 ,t h ee nh an ce df o rl o op wasi nt r oduc ed.Thi si smai nl yus edf orAr r a ys .
Th ewh i l eL oo p:
Awhi l el oopi sac ont r ol s t r uc t ur et hatal l owsyout or epeatat as kac er t ai nnumberoft i mes .
Sy nt ax : Thes y nt a xo fawhi l el oopi s : hile)?ooleanDe$pression * ' //tatements 2
Wh ene x ec u t i ng ,i ft h eb oo l e an _e x pr e ss i o nr es ul ti st r ue,t hent heac t i onsi ns i det hel oopwi l lbe ex ec ut ed.Thi swi l l c ont i nueasl ongast heex pr es si onr es ul ti st r ue. Her e,k e ypo i ntoft hewhi l e l o opi st h att hel oopmi gh tno te v err u n.Whent hee xpr es s i oni st es t ed andt her es ul ti sf al s e,t hel oopbodywi l lbes k i ppedandt hefi r s ts t at ementaf t ert hewhi l el oopwi l l b ee x e c u t e d.
Ex ampl e: public class &est ' public static void main)tring args[]* ' int $ = !+; hile) $ E + * ' ystem.out.print)value of $ 1 $ *; $; ystem.out.print)Fn*; 2 2 2
Thedo. . . whi l eLoop: Ado. . . whi l el oopi ss i mi l art oawhi l el oop,e x ceptt hatado. . . whi l el oopi sguar ant eedt oe x ec ut eat l eas tonet i me.
Sy nt ax : Thes ynt axofado. . . whi l el oopi s : do ' //tatements 2hile)?ooleanDe$pression *;
No t i c et h att heBo ol e ane x pr e ss i o na pp ear sa tt hee ndo ft h el oo p,s ot h es t at e men t si nt hel o op e x ec ut eon cebef or et heBoo l ea ni st es t ed. I ft heBool eane xpr es s i oni st r ue,t hefl ow o fc ont r olj umpsbac ku pt od o,andt hes t at emen t si nt he l oope x ec ut eagai n.Thi spr oc es sr e peat sunt i l t heBool eane xpr es si oni sf al s e.
Ex ampl e: public class &est ' public static void main)tring args[]*' int $ = !+; do' ystem.out.print)value of $ 1 $ *; $; ystem.out.print)Fn*; 2hile) $ E + *; 2 2
Thef orLoop: Af orl oopi sar epe t i t i onc ont r ols t r uc t ur et hatal l owsy out oeffic i ent l ywr i t eal oopt hatneedst o e x e c ut eas p ec i fi cnu mb ero ft i me s . Af o rl o opi su s ef u lwh eny ouk n owh owma nyt i me sat a s ki st ob er e pe at e d.
Sy nt ax : Thes y nt axofaf orl oopi s : for)initialization ; ?ooleanDe$pression ; update* ' //tatements 2
Her ei st hefl owofc ont r ol i naf orl oop: •
•
Thei ni t i al i z at i ons t epi se xec ut edfi r s t ,andonl yonc e.Thi ss t epal l owsy out odec l ar eand i ni t i al i z e an yl oopc on t r olv ar i abl es .Y ouar eno tr equi r edt op utas t a t ementh er e,a sl o ngasa s e mi c o l o nap pe ar s . Nex t ,t heBool eanex pr es si oni sev al uat ed.I fi ti st r ue,t hebodyoft hel oopi sex ec ut ed.I fi ti s f al s e,t h ebodyoft hel oopdoesno te x ec ut ea ndfl owofc ont r ol j umpst ot hene x ts t at ementpas tt he f orl oop.
•
•
Af t e rt h eb od yo ft h ef o rl o ope x ec ut e s,t h efl o wo fc on t r o lj u mp sb ac ku pt ot heu pd at e s t at ement .Thi ss t at emental l o wsy out oupdat ean yl oopcont r ol v ar i abl es .Thi ss t at ementc anbel ef t b l a nk ,a sl o nga sas emi c ol ona pp ea r saf t e rt h eBo ol e ane x pr e ss i o n. TheBo ol e an e x pr e ss i o ni sn ow e v al u at e d ag ai n .I fi ti st r ue ,t h el o op e x ec ut e sa nd t h e pr oc es sr epeat si t s el f( bodyofl oop,t henupdat es t ep,t henBool eane xpr es si on) .Af t ert heBool ean e x pr es si oni sf al s e,t hef orl oopt er mi nat es .
Ex ampl e: public class &est ' public static void main)tring args[]* ' for)int $ = !+; $ E +; $ = $!* ' ystem.out.print)value of $ 1 $ *; ystem.out.print)Fn*; 2 2 2
Enhanc edf orl oopi nJ av a: AsofJ a va5,t h eenhan cedf orl oopwasi nt r od uc ed.Thi si smai nl yus edf orAr r a y s.
Sy nt ax : Th es y nt a xo fe nh an ce df o rl o opi s : for)declaration 1 e$pression* ' //tatements 2 •
•
De cl a r a t i on:Th e ne wl yd ec l a r e db l o ckv a r i a bl e ,wh i c hi so fa t y pe c ompa t i b l e wi t ht h e
el ement soft hear r a yy ouar eac ces si ng.Thev ar i abl ewi l lbea vai l abl ewi t hi nt hef orbl oc kandi t s v a l u ewo ul dbet h es ameast h ec u r r e nta r r a yel e me nt . Thi se val uat est ot hear r a yy oune edt ol oopt hr o ug h.Theex pr es s i oncanbean Expr essi on: ar r ayvar i abl eormet hodc al l t hatr et ur nsanar r ay .
Ex ampl e: public class &est ' public static void main)tring args[]*' int [] numbers = '!+, +, 3+, "+, 5+2;
for)int $ 1 numbers *' ystem.out.print) $ *; ystem.out.print),*; 2 ystem.out.print)Fn*; tring [] names ='Games, Harry, &om, Hacy2; for) tring name 1 names * ' ystem.out.print) name *; ystem.out.print),*; 2 2 2
Thi swoul dpr oduc et hef ol l o wi ngr es ul t : !+,+,3+,"+,5+, Games,Harry,&om,Hacy,
Thebr eakKeywor d: Theb r e a k k e y wo r di sus e dt os t o pt hee nt i r el o op .Th eb r e akk e y wo r dmu s tb eu se di n si d ea nyl oo p oras wi t c hs t at emen t . Theb r eakk e ywo r dwi l ls t opt hee x ec ut i onoft hei nne r mos tl o opands t a r te x ec ut i ngt hen ex tl i neof c odeaf t ert hebl oc k.
Sy nt ax : Thes y nt a xo fabr eaki sas i ng l es t at ementi ns i dean yl oop: brea;
Ex ampl e: public class &est ' public static void main)tring args[]* ' int [] numbers = '!+, +, 3+, "+, 5+2; for)int $ 1 numbers * ' if) $ == 3+ * ' brea; 2 ystem.out.print) $ *; ystem.out.print)Fn*; 2 2 2
Th ec o nt i n ueKe y wo r d : Thec ont i nuek e y wo r dc an b eu se di n an yo ft h el oo pc on t r o ls t r u ct u r e s .I tc au s est h el o op t o i mmedi at el yj umpt ot hene xti t er at i onoft hel oop. •
I naf orl oo p,t hec ont i nu ek e ywor dc au sesfl ow ofc on t r olt oi mmedi at el yj umpt ot heupda t e s t at e men t . I nawhi l el oo pordo/ whi l el oop ,fl owofc ont r ol i mmedi at e l yj u mpst ot heBoo l eane xpr es s i on .
•
Sy nt ax : Thes y nt a xo fac on t i nu ei sas i ngl es t at eme nti n si dean yl oop : continue;
Ex ampl e: public class &est ' public static void main)tring args[]* ' int [] numbers = '!+, +, 3+, "+, 5+2; for)int $ 1 numbers * ' if) $ == 3+ * ' continue; 2 ystem.out.print) $ *; ystem.out.print)Fn*; 2 2 2
St r i n gs ,wh i c ha r ewi d el yu s edi nJ a v ap r o gr a mmi n g,a r eas e qu en c eo fc h a r a c t e r s .I nt h eJ a v a pr ogr ammi n gl an gu age ,s t r i ng sa r eob j ec t s . TheJ av apl at f or m pr o vi dest heSt r i ngc l as st oc r eat eandmani pul at es t r i ngs .
Cr eat i ngSt r i ngs :
Themos tdi r ec twayt oc r eat eas t r i ngi st owr i t e: tring greeting = Cello orldI;
Wh en e v e ri te nc o u nt e r sas t r i ngl i t er a li ny ourc o de,t hec ompi l erc r eat esaSt r i ngobj ec twi t hi t s v al uei nt hi scas e," Hel l owor l d! ' . Aswi t han yo t he ro bj ec t ,y ouc anc r eat eSt r i ngobj ec t sbyus i ngt hene wk e ywo r da ndac ons t r uc t or . TheSt r i ngc l as shasel ev enc ons t r uc t or st hatal l owy out opr ov i det hei ni t i alv al ueoft hes t r i ngus i ng di ff er en ts our c es ,s uc hasanar r a yofc har ac t er s . public class tring
Thi swoul dpr oduc et hef ol l o wi ngr es ul t : hello.
Not e: TheSt r i ngc l as si si mmut abl e,s ot hatonc ei ti scr eat edaSt r i ngobj ec tc anno tbec hanged.I f t h er ei s a ne c es s i t yt o ma k e al o to fmo di fi c at i o ns t o St r i n gs o fc h ar a ct e r s ,t h en y o us ho ul d useSt r i ngBuff er&St r i ngBui l der Cl a s s es .
St r i ngLengt h: Me t h od sus e dt oob t a i ni n f o r ma t i o na bo uta no bj e c ta r ek no wnasa c c es s o rme t h od s .On ea c c es s o r me t ho dt haty ouc anu sewi t hs t r i ngsi st hel engt h( )me t hod ,wh i c hr e t ur n st henumbero fc har a ct er s c ont ai nedi nt hes t r i ngobj ec t . Af t ert hef ol l owi ngt wol i nesofc ode h av ebe ene x e c ut e d,l e ne qu al s17 : public class tring
ystem.out.println) tring Hength is 1 len *; 2 2
Thi swoul dpr oduc et hef ol l o wi ngr es ul t : tring Hength is 1 !-
Conc at enat i ngSt r i ngs : TheSt r i ngc l a ssi n cl ud esame t h odf orc on cat ena t i ngt wos t r i n gs : string!.concat)string*;
Thi sr e t ur nsane ws t r i ngt ha ti ss t r i ng 1wi t hs t r i ng2addedt oi tatt heen d.Yo uc anal s ous et he c onc at ( )met hodwi t hs t r i ngl i t er al s ,asi n: y name is .concat)Jara*;
St r i ng sa r emo r ec ommo nl yc on ca t e na t e dwi t ht h e+o pe r a t o r ,a si n : Cello, orld I
whi c hr es ul t si n: Cello, orldI
Letusl ookatt hef ol l owi ngex ampl e: public class tring
Thi swoul dpr oduc et hef ol l o wi ngr es ul t :
Cr eat i ngFor matSt r i ngs : Youh av epr i n t f ( )andf or ma t ( )me t ho dst opr i ntout pu twi t hf or mat t e dnumb er s .TheSt r i ngc l as sha s anequi v al entc l as smet hod,f or mat ( ) ,t hatr et ur nsaSt r i ngobj ec tr at hert hanaPr i nt St r eam obj ec t . Us i ngSt r i ng' sst at i cf or mat ( )me t hodal l owsyout oc r eat eaf or mat t eds t r i ngt haty ouc anr eus e,as oppo sedt oaon et i mepr i nts t at eme nt .Fore x ampl e ,i n st eado f : ystem.out.printf)&he value of the float variable is Kf, hile the value of the integer variable is Kd, and the string is Ks, floatLar, intLar, stringLar*;
y oucanwr i t e: tring fs; fs = tring.format)&he value of the float variable is Kf, hile the value of the integer variable is Kd, and the string is Ks, floatLar, intLar, stringLar*; ystem.out.println)fs*;