Java is a general purpose, object oriented programming language developed by Sun MicroSystems in 1991. Originally called OAK by James gosling , one of t e inventors of t e language. !ut "as renamed as java in 199#. $ e primary motivation of java "as not t e internet. %t "as designed to be embedded in various consumer electronic devices suc as Micro"ave ovens, "as ing mac ines and remote controls etc. $ e trouble "it & and &'' is t at t ey are designed to be compiled for specific target i.e, "e re(uire a full &'' compiler targeted for t e &)* "or+ing in a specific environment. $ e problem is t at compilers are e,pensive and time consuming to create. So -osling and is team began to "or+ on a portable, platform independent language t at could be used to produce code t at "ould run on variety of &)*s under different environments. $ e effort ultimately lead to creation of .java/ & is familiar for its synta,, &'' is familiar for its object oriented features. So java came "it good features of bot t ese languages but not t e en anced version of & or &''. Java Magic (Byte Code) $ e magic of java is t e security and portability. )roblems are just solved by its byte code i.e output of java compiler is byte code not e,ecutable code. Again t is byte code is e,ecuted by java runtime system, " ic is called J0M 1Java 0irtual Mac ine2. J0M is an interpreter for byte code. $ransforming t e java program into byte code ma+es it muc easier to run a program in a "ide variety of environments. Alt oug if J0M differs from platform to platform, all t e mac ines understand t e same byte code. Java Buzzwords(Features) 1S S ) O3 MA& 4552 Simple6 Java "as designed to be easy for professional programmers to learn, if e already +no"s & 7&''. Java includes synta,es from & and object oriented concepts from &''. $ e confusing concepts in bot & 7 &'' are leftover ere. So java is easy to learn and it is simple language. Secure6 Security becomes an important issue for a language t at is used for programming on internet. $ reat of viruses and abuse of resources are every" ere. Java systems not only verify all memory access but also ensure t at no viruses are communicated "it an applet. $ e absence of pointers in java ensures t at programs can/t gain access to memory locations "it out proper aut ori8ation. )ortable6 $ e most significant contribution of java over ot er languages is its portability. Java programs can be easily moved from on computer to anot er, any" ere and anytime. & anges and upgrades in operating systems, processors and system resources "ill not force any c anges in java programs. $ is is t e reason " y java as become popular language for programming on internet " ic interconnects different +inds of systems "orld "ide. ObjectOriented6 java is a true object oriented language. Almost everyt ing in java is an object. All program code and data reside "it in objects 7 classes. Java comes "it an e,tensive set of classes, arranged in pac+ages, t at "e can use in our programs by in eritance. $ e object Model in java is simple and easy to e,tend. 3obust6 Java is a robust language. %t provides many safeguards to ensure reliable code. %t as strict compile time and runtime c ec+ing for data types. %t is designed as a garbage collected language relieving t e programmers virtually all memory management problems. Java also incorporates t e concept of e,ception andling " ic captures serious errors and eliminates any ris+ of cras t e system. Multit readed6 %t means andling multiple tas+s simultaneously. Java supports Multit readed programs. $ is means t at "e need not "ait for t e application to finis one tas+ before anot er. 9or eg, "e can listen to an audio clip " ile scrolling a page and at t e same time do"nload an applet from a distant computer. $ is feature greatly improves t e interactive performance of grap ical applications. 2.1 Prepared by PHANI KISHORE ROMPICHRLA


Arc itectural :eutral6 One of t e problems facing by programmers "as program "ritten today "ill not be run tomorro" even in t e same mac ine or if t e OS or if t e processor upgrades. So java designers made it arc itectural neutral by implementing J0M 1Java 0irtual Mac ine2t roug java runtime environment. $ e main role of java designers to ma+e it arc itecture neutral "rite once, run any" ere, anytime forever. &ompiled 7 %nterpreted6 *sually a computer language is eit er compiled or interpreted. Java combines bot t ese approac es t us ma+ing java a t"o stage system. 9irst java compiler translates source code into " at is +no"n as byte code. !yte codes are not mac ine instructions and t erefore, in second stage java interpreter generates mac ine code t at can be directly e,ecuted by t e mac ine t at is running t e java program. So "e can say t at java is bot compiled and interpreted language. 4ig )erformance6 Java performance is impressive for an interpreted language, mainly due to t e use of intermediate byte code. Java arc itecture is also designed to reduce over eads during runtime. 9urt er, t e incorporation of multit reading en ances t e over all e,ecution speed of java programs. 5ynamic6 java programs carry "it t em substantial amount of runtime information t at is used to access t e objects at runtime. $ is ma+es java 5ynamic. 5istributed6 java is designed for t e distributed environment of t e internet because it andle $&);%) protocols. Java supports t"o computers to support remotely t roug a pac+age called 3emote Met od %nvocation 13M%2

Data types:
<very variable in java as a datatype. 5atatypes specify t e si8e and type of values t at can be stored. Java language is ric in its datatypes. %nteger types6 Java supports = t ypes of integers, t ey are byte s ort , int and long. Java does not support t e concept of unsigned types and t erefore all java values are signed ,meaning t ey can be 've or >ve Type byte s ort int long ize 1 byte @ bytes = bytes !a"ge ?1@A to 1@B ?@1# to @1#?1 ?@C1 to @C1?1

A bytes ?@DC to @DC?1

#yte: $ e smallest integer type is byte. $ is is a signed A?bit type t at as a range from ?1@A to 1@B. 0ariables of type .byte/ are especially useful " en you/re "or+ing "it a stream of data from a n;" or file. byte variables are declared by use of /byte/ +ey"ord. eg6 byte b, cE s$ort: s ort is signed 1D b it type. %t as range from ?@1# to @1#?1. $ e s ort variables are declared by use of s ort +ey"ord. eg6 s ort sE i"t6 $ e most commonly used integer type is int. %t is a signed C@ bit type t at a range from ?@ C1 to @C1?1. %n addition to ot er uses, variables of type int are commonly employed to control loop and to inde, arrays. .int/ type is most versatile 7 efficient type. int variables are declared by use of .int/ +ey"ord. eg6 int aE %o"g: long is a signed D= bit type and is useful for t ose occasions " ere an int type is not large enoug to old t e desired values. $ e range of long is (uite large. %t as range from ?@ DC to @DC?1. long variables are declared by use of .long/ +ey"ord eg6 long aE



t e datatype used to store c aracters is c ar. $ ere are t"o +inds of floating point types.=e'GCA =.3 Prepared by PHANI KISHORE ROMPICHRLA . %t can ave only one of t"o possible values. uses D= bits to store a value. c ar variables are declared by use of c ar +ey"ord. 2. F ic represent single and double precision numbers respectively. float and double.Ae'CGA &%oat6 t e type float specifies a single precision value t at uses C@ bits of storage.boolean/ +ey"ord. eg6 float aH1.pressions t at re(uire fractional precision. $ e code generated by t e java interpreter by acting as an intermediary bet"een t e virtual mac ine and real mac ine.9e?C@= to 1. Single precision is faster on same processors and ta+es alf as muc space as double precision. !oolean is also t e type re(uired by conditional e. All transcendental mat functions suc as sin12. double variables are declared by use of . eg6 boolean bE bHfalseE Java 'irtua% Mac$i"e: -enerally all language compilers translate source code into mac ine code for a specific computer. %n java.@C=E dou#%e6 double precision. true or false. float variables are declared by use of . Java uses Unicode to represent c aracters.pressions t at govern t e control statements suc as . eg6 c ar cE #oo%ea": Java as a simple type called boolean.UNIT-II JAVA BASICS F%oati"g poi"t types: 9loating point numbers are used " en evaluating e. $ us in java c ar is a 1Dbit type.=e?G=# to C.float/ +ey"ord. for a mac ine is called J0M A virtual mac ine code is not mac ine specific. as denoted by t e double +ey"ord. boolean variables are declared by use of . for logical values. *nicode defines a fully international c aracter set t at can represent all of t e c aracters found in all uman languages. Type ize !a"ge float s ort = bytes A bytes 1. $ ere are no negative c ars. eg6 double dE c$ar: %n java.double/ +ey"ord. arc itectural neutral is ac ieved because compiler produces an intermediate code called !yte code. $ is is t e type returned by all relational operators suc as aIb.if/ and .for/. $ e range of c ar is G to D##CD. cos12 and s(rt12 return double values.

out. "it t e name of t e source file on command line as s o"n belo" &6PQ javac prog.java A java Application ave any no of classes.!-M T!UCTU!.java %f everyt ing is OK. Creati"g t$e progra(: Fe can create a program using any te. J5K must be properly installed on our system.java !u""i"g t$e progra(: Fe need to use t e java interpreter to run stand alone applications. At t e command prompt. F en e.p6 Hi friend Java *!+.: A java program may contain many classes of " ic only one class defines a main met od. java compiler1javac2 creates a file called Sample. $ ey include  &reating t e program  &ompiling t e program  3unning t e program 3emember t at.ecution from t ere.UNIT-II JAVA BASICS I(p%e(e"ti"g a )ava progra(: %mplementation of java application program involves a series of steps. Java program may contain one or more sections as s o"n belo". t e interpreter loo+s for t e main met od in t e program and begins e. Main class is not ing but class " ic contains main12 met od Co(pi%i"g t$e progra(: $o compile t e program "e must run t e java compiler javac.t editor class Sample J public static void main1String argKL2 J System. before "e begin creating t e program. Prepared by PHANI KISHORE ROMPICHRLA .ecuted our program displays t e follo"ing o.class 1Iclassname.println1M4i friendN2E O O Fe ave to save t is program "it a name li+e prog. 2. &lasses contain datamembers and met ods t at operate on t e data members of t e class. typeR &6PQ java Sample :o". but only one main class.classQ2 containing t e bytecodes of t e program prog.

$ is statement declares a pac+age name and informs t e compiler t at t e classes defined ere belong to t is pac+age. <g6 pac+age studentE %t is optional section. $ ese command line arguments "ill be collected into an array of string " ic is supplied as a parameter to main met ods. -!. %t is suggested one. I(port state(e"t: $ is is similar to t e Sinclude statement in & <g6 import java. &lasses are t e primary 7 essential elements of a java program. $ e command line arguments "ill immediately follo" t e program name on t e command line.! Prepared by PHANI KISHORE ROMPICHRLA . I"ter&ace state(e"t: An interface is li+e a class but includes a group of met od declarations.$ e main met od creates objects of various classes and establis es communications bet"een t em.TE %t is optional section. Mai" Met$od C%ass: Since every java stand alone program re(uires a main met od as its starting point.UNIT-II JAVA BASICS Docu(e"tatio" sectio": $ is section comprises of a set of comment lines giving t e name of program. " ic t e programmer "ould li+e to refer at later stage. *ac/age state(e"t: $ e first statement allo"ed in java is a . 2. C+MM-ND 0IN. C%ass De&i"itio"s: A java program may contain multiple class definitions.NT : Sometimes "e "ill need to supply data into a java program " en it runs.pac+age/ statement. $ is type of data "ill be supplied in t e form of command line arguments. t is class is t e essential part of a java program.UM. On reac ing t e end of main. %t is also optional section and is used only " en "e "is to implement t e multiple in eritance feature in jprogram. t e program terminates and t e control passes bac+ to t e operating system. t e aut or 7 ot er details.io.

" Prepared by PHANI KISHORE ROMPICHRLA . c is dynamically initiali8ed System. declares t ree integer variables a. java allo"s variables to be initiali8ed dynamically. type identifier[=value][.amples ave used only constants as initiali8ers. bH=.UNIT-II JAVA BASICS Uater t ese command line arguments must be processed and t en accessed. Dy"a(ic I"itia%izatio": Alt oug t e preceding e.pression valid at t e time t e variable is declared.lengt 12Ei''2 System. int a.java c6PQ java 5isplay i t is is ur friend o.. <g6 class 5isplay J public static void main1String argsKL2 J for1iHGEiIargs. " ic defines t eir visibility and a lifetime. $o declare more t an one variable of t e specified type.println1argsKiL2E O O c6PQ javac file.cE int dHC. b..b. declares C integer variables initiali8ing d and f *nli+e in &. variable can be declared any " ere in t e program. Dec%ari"g varia#%e: All variables must be declared before t ey can be used. and c .G.out.avg/ is float type variable.out.value/ is an integer type variable . <g6 int valueE float avgE in t e above e. : A variable is an identifier t at denotes a storage location used to store a data value.GE double cHMat .ample.e.s(rt1aTa'bTb2E . " ere ever t ey are needed.ample. " ere as . $ e follo"ing program ta+es command line argument and prints t em. identifier [=value]… ]. All variables ave a scope.p-> hi this is ur friend '-!I-B0. $ e basic form of a variable declaration is .println1M4ypotenuse is N'c2E O 2. using any e.fH#E . . 9or e.. use a comma?separated list. &lass 5yn%nit J )ublic static void main1String argKL2 J double aHC.

+no"n to all code "it in main . eac time you create a bloc+ of code.$ is means t at objects declared in t e outer scope "ill be visible to code "it in t e inner scope.HH1G2 J %nt y H@GE .HyT@E O y H 1GGE . is still +no"n ere O O As t e comments indicate.. +no"n only to t is bloc+ System. is declared at t e start of (ai"()/s scope and is accessible to all subse(uent code "it in main12. Only one memory location is created for eac class variable.println1M. program to demostarte bloc+ scope class scope J public static void main1String arKL2 J %nt . F en t is occurs. C%assi&icatio" o& varia#%es: Java variables are actually classified into t ree +inds6  %nstance variables  &lass variables  Uocal variables Instance variables are created " en t e objects are instantiated and t erefore t ey are associated "it t e objects. Local variables are declared and used inside met ods and program bloc+s1defined bet"een opening brace J and a closing braceO 2. t e outer scope encloses t e inner scope.'N N'y2E .$ ey ta+e different values for eac object. t ree local variables a. cope a"d %i&eti(e o& varia#%es: Scope of variables: Scope is defined as an area of t e program " ere t e variable is accessible. .out. you are creating a ne". and y6 N'. b. t e variable . %nstance and class variables are declared inside a class. nested scope. As a general rule. 9or e. Scopes can be nested. $ ese variables are visible to t e program only from t e beginning of its program bloc+ to t e end of t e program bloc+.. y is only visible to t e code in if bloc+ . c are declared. Lifetime of variables: 2. variables declared insid a scope are not visible to code t at is defined outside t at scope. Class variables are global to a class and belong to t e entire set of objects t at class creates.H1GE if1. is N'.E ..out. <rrorV y not +no"n ere System. 4o"ever c is initiali8ed dynamically. 4o"ever t e reverse is not true.2E .UNIT-II JAVA BASICS O 4ere.ample. Objects declared "it in t e inner scope "ill not be visible outside it...# Prepared by PHANI KISHORE ROMPICHRLA . $ e t"o a and b are initiali8ed by constants.println1M. .

A specific element in an array is accessed by its inde. $ us.5emonstrate a o"e-di(e"sio"a% array class Array J public static void main1String arKL2 J int mont XdaysKLHne" intK1@LE mont XdaysKGL H C1E mont XdaysK1L H @AE mont XdaysK@L H C1E 2. and destroyed " en t eir scope is left. variables declared "it in a met od "ill not old t eir values bet"een calls to t at met od. Also a variable declared "it in a bloc+ "ill lose its values " en t e bloc+ is left.println1My is no" 6 N'y2E O O O $ e output of above program is 6 y is : -1 y is now: 100 y is : -1 y is now: 100 y is : -1 y is now: 100 -rrays An array is a collection of omogeneous data items t at s are a common name.ICE . t e lifetime of a variable is confined to its scope. y is initiali8ed eac time bloc+ is entered System.HGE ... $ is means t at a variable "ill not old its value once it as gone out of scope.println1My is 6 N'y2E . So t e general form of ne" as it applies to one?dimensional arrays appears as follo"s. $ erefore. type var?nameKLHne" typeKsi8eLE eg6 int mar+sKL H ne" intK@GLE ..out. Arrays of anytype can be created and may ave one or more dimensions.UNIT-II JAVA BASICS 0araibles are created " en t eir scope is entered.. t is al"ays prints ?1 WH1GGE System.$ Prepared by PHANI KISHORE ROMPICHRLA .E for1. ne!"imensional #rrays: general form of a one?dimensional array declaration is type var?nameKLE eg6 int mar+sKLE and "e must use "ew operator to allocate memory.out. class Uifetime J public static void main1String arKL2 J int .''2 J int yH?1E .

UNIT-II JAVA BASICS mont XdaysKCL H CGE mont XdaysK=L H C1E mont XdaysK#L H CGE mont XdaysKDL H C1E mont XdaysKBL H C1E mont XdaysKAL H CGE mont XdaysK9L H C1E mont XdaysK1GL H CGE mont XdaysK11LH C1E System.C1.% Prepared by PHANI KISHORE ROMPICHRLA .@A.C1.C1.CG. J public static void main1String arKL2 J int matKLKLHne" intKCLK=LE for1int iHGEiICEi''2 J for1int jHGEjI=Ej''2 J matKiLKjLHiE System.out.C1OE System.CG.CG. multidimensional arrays are actually arrays of arrays.CG.println12E O O O t e above program inserts values into a matri.println1MOctober as N'mont XdaysK9L'N daysN2E O O O Two (Multi)-Dimensional Arrays: %n java. e.println1MOctober as N'mont XdaysK9L2E O O Fe can also "rite above program as belo"R class Array J public static void main1String arKL2 J int mont XdaysKLHJC1.print1matKiLKjL'N N2E O System. .C1.= and prints 2.out.C1.out.ample6 int t"o5KLKL H ne" intK=LK#LE eg program6 class Matri.mat/ of order C.out.

print1tKiLKjL'N N2E O System. Increment 7 5ecrement operators C.UNIT-II JAVA BASICS . !elational operators =. Manually allocate differing si8e second dimensions class $raingle J public static void main1String arKL2 J int tKLKL H ne" intK=LKLE tKGL H ne" intK1LE tK1L H ne" intK@LE tK@L H ne" intKCLE tKCL H ne" intK=LE for1int iHGEiI=Ei''2 J for1int jHGEjIi'1Ej''2 J tKiLKjLHiE System.out.println12E O O O +perators Java supports a ric set of operators. -ssignment Operator B..pressions in t e same "ay t at t ey are used in algebra. 0ogical operators D. $ e follo"ing are t e list of arit metic operators6 +perator Mea"i"g ' Addition ? Subtraction T Multiplication 2. Java operators can be classified into a number of related categories as belo"6 1. Bit"ise operators #. Operators are used in programs to manipulate data and variables.out. Conditional Operator 12Arit metic operators6 $ ese are used in mat ematical e. -rit metic operators @.1& Prepared by PHANI KISHORE ROMPICHRLA .

11 Mea"i"g bit"ise A:5 bit"ise O3 bit"ise [O3 bit"ise unary :O$ Prepared by PHANI KISHORE ROMPICHRLA .H.ample. $ e follo"ing are t e list of !it"ise operators6 +perator 7 V Z 1 2.H YH 5ivision Modulo division 13emainder2 Addition assignment Subtraction assignment Multiplication assignment 5ivision assignment Modulus assignment Arit metic operators are used as s o"n belo"6 a?b a'b aTb a. t e result produced by a relational operator is a !oolean value.ecuted - !it"ise operators6 Java defines several bit"ise operators " ic can be applied to t e integer types.''E using increment operator similarly.pressions t at control t e i& statement and t e various %oop statements.?1E can be "ritten li+e . c ar. . $ e follo"ing are t e list of 3elational operators6 +perator Mea"i"g HH <(ual to VH :ot e(ual to Q -reater t an I Uess t an QH -reater t an or e(ual to IH Uess t an or e(ual to As stated. and byte.H. aQb results true. Y 'H ?H TH .UNIT-II JAVA BASICS .b aYb ?aTb ere a and b are operands @2%ncrement 7 5ecrement operators6 $ e '' and t e > are java/s increment and decrement operators. t e result of aIb1" ic is true2 is stored in c if1aQb2 J O in t is case.'1E can be "ritten li+e . long.??E using decrement operator C23elational operators6 $ e relational operators determine t e relations ip t at one operand as to t e ot er. $ e relational operational operators are most fre(uently used in t e e. s ort. $ e outcome of t ese operators is a #oo%ea" value. . 9or e.ample. $ ese operators act upon t e individual bits of t eir operands. int aH=E int bH1E boolean cHaQbE . for e. $ e decrement operator decreases its operand by one. int.in t is case. $ e increment operator increases its operand by one. so if statement "ill be e.

9or e.pression.pression "ill produce a value. if1 aQb 77 . t en t e e%p( is evaluated and becomes t e value of t e conditional e. aH1G . 4ere. y and 8 to 1GG &onditional Operator1 6:2 $ e c aracter pair ]6 is a ternary operator available in Java.ample.pressions of t e form e%p& ' e%p( : e%p) e%p& is evaluated firt. %t it is non8ero 1true2. "ill be assigned t e value of b. $ is operator is used to construct conditional e. e%p) is evaluated and its value becomes t e value of t e conditional e. t at is treated as an Arit metic e.8pressio"s F en operands and operators are combined. $ is can be ac ieved using t e i&7e%se statement as follo"s6 if1a Q b2 . t e assignment operator allo"s to create a c ain of assignments. +perator Mea"i"g 77 logical A:5 \ logical O3 2 logical [O3 3 logical :O$ $ e logical operators 77 and \ are used " en "e "ant to form compound conditions by combining t"o or more relations..12 Prepared by PHANI KISHORE ROMPICHRLA . $ e e.ample. if e%p& is false.ample. set . H bE . All of t e binary logical operators combine t"o #oo%ea" values to form a resultant #oo%ea" value. H 1 a Q b 2] a 6 b E . 9or e.ecution of an e. an e. int . %t as general form6 var =e%pression. H .pression.. H aE else . bH@GE . 8E . H y H 8 H 1GGE . $ ey operate on #oo%ea" operands. 2. #rit*metic e%pression: %f "e use arit metic operators in an e. t e type of var must be compatible "it t e type of e. <g6 a'b?cE Increment or "ecrement +%pression.UNIT-II JAVA BASICS II QQ QQQ s ift left s ift rig t s ift rig t "it 8ero fill Uogical operators6 Uogical operators are also called as !oolean Uogical operators. y. HH1G2 J O B -44B -55B -2B 3- true true false false true false true false true false false false true true true false false true true false false false true true Assignment Operator 1H26 $ e assi$nment operator is t e single e(ual sign.pression.pression. for e.pression is formed..pression.

if/ is a selection statement t at is used to c oose t"o c oices in a program. $ ere are t"o selection statements 6 i& and switc$ 1a2 if statement6 .pression.pression. Statement is a single or multiple statements.pressions.pression6 <g6 aQbE Lo$ical e%pression: %f "e use !oolean logical operators in an e.pression.false2. t at is treated as a 3elational e. t at is treated as an &onditional e. Java/s program control statements are divided into C categories  Selection Statements  %teration Statements  Jump Statements 12Selection Statements6 Selection statement controls t e flo" of t e program depending on t e result of t e conditional e. Synta.pression. t e statement@ is e. 1b2 :ested if statement6 %t means an if statement under anot er if statement.ecuted. true. <g6 a''E b? ?E -elational e%pression: %f "e use 3elational operators in an e. %f t e condition is true t en t e control goes to t e statement1 and it is e. aQb] a6 bE R li+e t is.pression..pression6 a77bE Conditional e%pression: %f "e use arit metic operators in an e. <g6 <g6 Co"tro% tate(e"ts A &ontrol statement is a statement t at controls t e flo" of e. Ot er"ise.ecution of t e program. Synta. t at is treated as %ncrement or 5ecrement e.13 Prepared by PHANI KISHORE ROMPICHRLA . 2.condition/ is any e.pression.UNIT-II JAVA BASICS %f "e use %ncrement or 5ecrement operators in an e.pression or t e state of a variable. t at is treated as a logical e.pression t at returns a !oolean value 1i. "e ave some ot er e.6 if1condition2 statement1E else statement@E .ecuted.6 if1condition2 J if1condition2 statementE O 1c2 if?else?if ladder6 if?else?if statement is a se(uence of if?else statements.e.

ecuted. . %t/s a better alternative to if?else?if ladder.pression is compared "it t e case values. t e case values must be of type e. %f none of t e case is matc ed t en t e default statement is e.6 if1condition2 statement1E else if1condition2 statement@E else if1condition2 statementCE .UNIT-II JAVA BASICS Synta. .pression2 J case value16 statement1E brea+E case value@6 statement@E brea+E case valueC6 statementCE brea+E . else statement@E %n if?else?if ladder if a condition is not met t en t e control flo"s from top to bottom until t e last if statement. case value:6 statement:E brea+E default 6 O ere. int or c ar only. t e e. " en control comes to t e s"itc statement t en t e value of t e e.6 s"itc 1e.pression and eac value s ould be uni(ue. @2%teration Statements6 $ ese statements allo"s t e part of t e program to repeat one or more times until some condition becomes true. $ ere are C iteration statements6 w$i%e. 1d2 s"itc statement6 %t provides more t an one c oice to c oose. Synta. if a matc is found t en t e statement1s2 corresponding to t at case is e. . do-w$i%e and &or statementE 1a2 " ile statement6 2.pression may be of type byte.1 Prepared by PHANI KISHORE ROMPICHRLA .ecuted. s ort.

pression. " en t e control goes to condition. condition is evaluated. body of t e loop O " ere initiali8ation portion of t e loop sets t e value of t e variable t at acts as a counter. %f condition is true. body of t e loop O " ile1condition2E <ac iteration of do?" ile e.6 do J .. $ e loop t en iterates evaluating condition. Synta.1! %t elps to terminate a statement se(uence in switc$ statement.ecuting t e iteration portion eac time it iterates.ecuting t e body and t en e.ecution of statements " ile its condition is true. Synta. t e control passes to t e statement immediately after t e " ile loop.6 for1initiali8ationE conditionE iteration2 J . body of t e loop "ill be e.ecuted at least once since t e condition of do?" ile is at t e bottom of t e loop. t e loop repeats. t at repeats a statement or bloc+ of statements until some condition is true. t e loop terminates.it or ter(i"ate t e loop %t can be used as anot er form of goto Prepared by PHANI KISHORE ROMPICHRLA .ecuted as long as t e condition is true. Ot er"ise t e loop terminates. %t can be used to e.t iteration portion is e. %f condition is true. t ere are C uses of brea+ statement.ecuted at all. 1a2 brea+ statement6 in java. F ere as in do?" ile statement. Ot er"ise. $ e body of t e loop "ill be e.ecuted only once. 1c2 for statement6 .ecuted. Synta.UNIT-II JAVA BASICS .ecutes. 1i2 1ii2 1iii2 2.6 " ile1condition2 J . $ is elps to increment or decrement t e control variable..for/ statement also repeats t e e. if t e condition is initially false t en t e body of loop "ill not be e. t en e. 1b2 do?" ile statement6 . $ ere are C types of jump statements.:e. Once t e condition becomes false.ecutes t e body of loop first and evaluates t e condition later. @2 Jump Statements6 Jump statements allo"s t e control to jump to a particular position." ile/ is an iteration statement. t e body of loop is e. And it is e. %n " ile statement. $ is portion is e. body of t e loop O " ere t e condition may be any boolean e.ecuted first " en t e loop starts..do?" ile/ statement is very muc similar to " ile statement "it little difference.

t iteration of enclosing structure.. F en t e control reac es to return statement. Type Co"versio" 4 Costi"g 2. t en it s+ips t e remaining statements and starts t e ne.println1Mi 6N'i2E O O O 1b2 continue statement6 $ e continue statement starts t e ne. it causes t e program control to transfer bac+ to t e caller of t e met od.t iteration of t e immediately enclosing iteration statements1" ile..ecute O O %n t is e.out. $ is "on/t e. do?" ile or for2.out.UNIT-II JAVA BASICS <g6 class A J public static void main1String argKL2 J for1int iHGE iI1GGE i''2 J if1iHH1G2 brea+E .out.ample. terminates loop if i is 1G System. since t e caller of main12 is runtime system.println1Mi 6N'i2E if1iY@HHG2 continueE System.out.println1M M2E O O O 1c2 return statement6 $ is is used to return from a met od. F en t e control goes to continue statement.1" Prepared by PHANI KISHORE ROMPICHRLA . <g6 class A J public static void main1String argKL2 J for1int iHGE iI1GGE i''2 J System. return statement returns to t e java run time system.println1M4iN2E . <g6 class A J public static void main1String argKL2 J boolean tHtrueE if1t2 returnE System.

a/ to double variable .UNIT-II JAVA BASICS Fe can assign a value of a variable of one type to a variable of anot er type. it is al"ays possible to assign t e value of int variable .println1N&onversion of int to byteN2E bH1byte2 iE System.println1N&onversion of double to byteN2E bH1byte2 dE System. "idening conversion ta+es place bet"een int and byte as int is larger t an byte to old its all valid values.println1Mi and b N'i'N N'b2E O O 2.out.1# Prepared by PHANI KISHORE ROMPICHRLA .b/.println1N&onversion of double to intN2E iH1int2 dE System.out.println1Mi and b N'i'N N'b2E System.ample. $ e follo"ing program demonstrates some type conversions t at re(uire casts6 class conversion J public static void main1String argKL2 J byte bE int iH @#BE double dHC@C. target?type specifies t e desired type to convert t e specified value to. $ is +ind of conversion is called narro"ing conversion.ype conversion: $ e system performs automatic type conversion " en one type of data is assigned to anot er type of variable only if follo"ing rules are satisfied.println1Mi and b N'i'N N'b2E System. Casti"g i"co(pati#%e types: F at if "e "ant to assign an int value to a byte variable] $ is conversion "ill not be performed automatically. t en t e type conversion is done implicitly by Java. $o create a conversion bet"een t"o incompatible types.out. $ is is +no"n as automatic 1implicit2 type conversion.ample. $ is process is +no"n as casting.out. %t as t is general form6 /tar$et!type0 value 4ere. <. A "idening conversion too+ place " en t ese @ rules are satisfied. %f t"o types are compatible "it eac ot er.1=@E System. "e must use a cast.plicit type conversion. 1i2 $ e types are compatible 1ii2 $ e destination type is larger t an t e source type. #utomatic . <g6 int aH1GE double bHaE As s o"n in above e. $ is is done implicitly by t e system as bot variable/s datatypes are compatible conversion of larger datatype to smaller datatype is +no"n as :arro"ing conversion of smaller datatype to larger datatype is +no"n as Fidening. because a byte is smaller t an an int. A cast is simply an e.out.out.

ample6 class sample J      2. .. $ e general definition of a class is given belo"6 class classname J type instanceXvariable1E type instanceXvariable1E . .1$ Prepared by PHANI KISHORE ROMPICHRLA . its fractional component is lost. F en t e value @#B is cast into a byte variable. C%asses 4 o#)ects: Co"cept o& C%asses A class is defined as an encapsulation of data and met ods t at operate on t e data. " ic in t is case is DB. . . class is a +ey"ord used to define class class name is t e identifier t at specifies t e name of t e class type specifies t e datatype of t e variable instanceXvariable1. .UNIT-II JAVA BASICS t is program generates t e follo"ing result Conversion of int to byte i and b 257 d and i 1 323 7 Conversion of double to int 323. " ic is 1 in t is case. a class can be defined t roug t e use of class +ey"ord. returntype met od name1parameter list2 J . . O 4ere. F en d is converted to a byte. .142 %n above eg. F en t e d is converted to an int. F en "e are creating a class "e are actually creating a ne" datatype. and t e value is reduces modulo @#D. its fractional component is lost.142 Conversion of double to byte d and b 323. ??diagram? F en "e define a class "e can easily create a no of instances of t at class Creatin$ class in 1ava: %n java. body of met od O . $ is ne" datatype is also called A5$. are t e variable defined in t e class met od name is t e met od defined in t e class t at can operate on t e variables in t e class <. t e result is t e remainder of t e division of @#B by @#D1range of byte2.

!ot data members and member met ods toget er called members of class.out.. yE set[W12 J .. %n java objects are created t roug t e use of ne" operator.UNIT-II JAVA BASICS int . <g6 Sample sHne" Sample12E $ e step@ creates t e object p ysically and stores t e address of t e object in t e reference variable.member met ods. Since objects are created at runtime.. -ccessi"g (e(#ers o& a" o#)ect: Once an object of a class is created "e can access t e members of t e class t roug t e use of object name and .data members $ e functions defined in t e class are called member functions.6 ob1ectname. member. Synta. Objects are created and t is process is called M%nstantiationN. t ey are called runtime entities.set[W12E 2.print1MHN'y2E O O class 5emo J public static void main1String arKL2 J Sample sE sHne" String12E s.2E System. <. %n java object creation is a t"o step process.1% Prepared by PHANI KISHORE ROMPICHRLA .ample6 class sample J int . tep9: create a reference variable of t e class <g6 Sample sE F en t is declaration is made a reference variable is created in memory and initiali8ed "it null.H1GE yH@GE O O $ e variables defined in t e class are called member variables. $ e ne" operator creates an object and allocates memory to t at object.. Co"cept o& +#)ects Objects are instances of a class. yE set[W12 J . 1dot2 operator.out. tep:: create t e object using t e ne" operator and assign t e address of t e object to t e reference variable created in step1.H1GE yH@GE O print[W12 J System.print1MHN'.

sometimes a member met od of a class needs to refer to t e object in " ic it "as invo+ed.UNIT-II JAVA BASICS s. String s2 . 2. A constructor doesn/t ave any return type.this< /eyword .s o"Student12E O O output:nu!ber" 5 # na!e" satya! nu!ber" 72 na!e" ra$u . %t is used to automaticallyl initiali8e an object " en t e object is created. %n order to serve t is purpose java introduces Mt is +ey"ordN.NrajuN2E s1.ecuted automatically at t e time of creating t e object. default constructor J numberH#D9E nameHNsatyamNE O Student1int no.out. <.. program to demonstrate constructor class Student J int numberE String nameE Student12 .out..plain about above program . parameteri8ed constructor J numberHnoE nameHsE O void s o"Student12 J System.2& Prepared by PHANI KISHORE ROMPICHRLA .println1Mnumber HN'number2E System.println1Mname HN'name2E O O class 5emo J public static void main1String arKL2 J Student s1Hne" Student12E Student s@Hne" Student1B@.. &onstructor gets e. and e.t is/ +ey"ord refers to t e current object.print[W12E O O Co"structors A constructor is a special +ind of met od t at as t e same name as t at of class in " ic it is defined..s o"Student12E s1.ample6 .

ample program6 class *seStatic J 2. t is static bloc+ is used to initiali8e t e static variables.UNIT-II JAVA BASICS !y using .s o"Student12E O O *nderstanding static +ey"ord6 %n java .numberHnumberE t is. is declared static only one copy of it is created in memory and is used by all t e objects of t e class. F en a modification is performed on a static variable t e c ange "ill be reflected in all objects of t e class for " ic t e static variable is a member.println1MnumberHN'number2E System.nameHnameE O void s o"Student12 J System. <. 4ence static variables are essentially global variables.out. $o define static met ods C.name space conflict/. $o create static data members @.21 Prepared by PHANI KISHORE ROMPICHRLA . 2ame Space Conflict: F en t e parameters of a member met od ave t e same name as t at of instance variables of t e class. $ is leads to conflict called .N3amaN2E s.out.setStudent11.println1MnameHN'name2E O O class 5isplay J public static void main1String arKL2 J Student sHne" Student12E .t is/ +ey"ord "e can remove name space conflict. static +ey"ord can be used for t e follo"ing purposes. %t can be resolved t roug use of Mt isN eg6 class Student J int numberE String nameE void setStudent1int number. 1. $o define static bloc+s tatic varia#%es: F en a datamember of a class.. object creation for class Student s. super +ey"ord. tatic Met$ods:  A static met od can call ot er static met ods only  A static met od can access static variables only  Static met ods cant ave access to t is. String name2 J t is. local variables ta+e t e priority over t e instance variable. tatic B%oc/s: Just li+e static variables and static met ods "e can also create a static bloc+ .

println1MaHN ' a2E System. .2 J System.println1MbHN ' b2E O static J System. finali8ation code ere O protected prevents to access finali8e met od by code defined outside t e class.22 Prepared by PHANI KISHORE ROMPICHRLA . F en a member of class is specified as private.6 protected void finali8e12 J .println1Mstatic bloc+ initiali8edN2E O public static void main1String argsKL2 J met 1D92E O O output6 stati% blo%& initiali'ed ( " # a " 3 b " 12 . %n &''. Java deallocates memory automatically and it is called M-arbage &ollectionN. $o andle t ese situations java provides finali8ation using finali8e12 met od Synta.out. Suppose for e.. t en t at member can only be accessed by ot er members of its class.ar#age Co%%ectio" Objects are dynamically allocated using t e . F en a member of a class is specified as public.out.plain about program -ccess Co"tro%: Java/s access specifiers are public.ample an object is olding some non?java resource suc as file? andling. protected applies only " en in eritance is involved. but not anyot er class members. and e. t en t at member can be accessed by anyot er code.UNIT-II JAVA BASICS static int aHCE static int bE static void met 1int .2E System. private and protected. Java also defines a default access level.ist t e object is assumed to be no longer needed and t e memory occupied by t e object can be reclaimed and t is is o" Mgarbage collectionN is done. +ver%oadi"g (et$ods 2..ne"/ operator and t eir memory must be released after reallocation.out. Fe must ave to free t e resources after t e object is destroyed.println1M. void is used because it doesn/t return anyt ing. Fi"a%ize() Met$od : %n some situations an object "ill lead to perform some action " en it is destroyed. F en no references to an object e.out.HN ' . t ey are manually released by t e use of delete operator.

out.UNIT-II JAVA BASICS %n java. t e follo"ing e.setStudent1D9.23 Prepared by PHANI KISHORE ROMPICHRLA .ample demonstrates t is. int mar+s. to contain t"o or more met ods "it t e same name as long as t e met od signatures are different. 2.mar+sE String nameE void setStudent12 J noH1E mar+sHA9E nameHNramaNE O void setStudent1int no.out.println1MnumberHN'no2E System.noHnoE t is.setStudent12E s. +%ample: class Student J int no . String name2 J t is.A1.NramuN2E s.println1Mmar+sHN'mar+s2E System.println1MnameN'name2E O O class Met odOverload J public static void main1String arKL2 J Student sHne" Student12E s.nameHnameE O void s o"Student12 J System.s o"Student12E O O output6 nu!ber"1 !ar&s")# na!e"ra!a nu!ber" # !ar&s")1 na!e"ra!u +ver%oadi"g Co"structors Just li+e member met ods constructors can also be overloaded.out.mar+sHmar+sE t is. $ at is t e met od s ould ave different number of parameters or different type of parameters " en t is is t e case t e met ods are said to be overloaded and t e mec anism is called met od overloading.s o"Student12E s. it is possible for a class.

%n t e second "ay.out. 1.println1M:umberHN'no2E System.NsatyaN2E s1. int j2 J 2.ample6 .2 Prepared by PHANI KISHORE ROMPICHRLA . %n java " en you pass a primitive type it is pass by value.s o"12E s@. " en you pass an object1reference2 to a met od. it is done t roug pass by reference <.UNIT-II JAVA BASICS class Student J int noE String nameE Student12 J noHBGE nameHNramNE O Student1int n. t e c anges made to t e parameter "ill effect t e argument used to call t e subroutine. t e c ange made to t e parameter of t e subroutine ave no effect on t e argument.out. String s2 J noHnE nameHsE O void s o"12 J System.s o"12E O O output6 nu!ber"70 na!e"ra! nu!ber" # na!e"satya *ara(eter passi"g $ ere are t"o "ays t at a computer language can pass an argument to a subroutine 1met od2. call by reference %n t e first "ay. call by value class $est J void met 1int i . call by value @.println1M:ameHN'name2E O O class 5isplay J public static void main1String arKL2 J Student s1H ne" Student12E Student s@H ne" Student1D9..

including private members. A nested class as access to t e members. t en ! is +no"n to A.b2E System. bH@GE System. 2. if class ! is defined "it in class A. 4o"ever. $ us.out. $ e classic e. but not outside of A.println1Ma and b after call6 N'a'N N'b2E O O output: a and b before %all: 10 20 a and b after %all: 10 20 !ecursio" Java supports recursion. t e enclosing class does not ave access to t e members of t e nested class. $ e met od t at calls itself is said to be recursive met od. Suc classes are +no"n as nested classes.2! Prepared by PHANI KISHORE ROMPICHRLA .println1Ma and b before call6 N'a'N N'b2E ob. of t e class in " ic it is nested. %t is t e process of defining somet ing interms of itself. %t is t e attribute t at allo"s a met od to call itself. $ e scope of nested class is bounded by t e scope of its enclosing class.met 1a.fact1#22E O O output above program6 *a%torial of 5 is 120 Nested 4 i""er c%asses: %t is possible to define a class "it in anot er class.out.UNIT-II JAVA BASICS i'H@E jTH@E O O class &all!y0alue J public static void main1String argKL2 J $est obH ne" $est12E int aH1G .out. class 9actorial J int fact1int n2 J if1nHH12 return 1E return 1fact1n?12Tn2E O O class 3ecursion J public static void main1String arKL2 J 9actorial fHne" 9actorial12E System.println1M9actorial of # isN' f.ample of recursion is t e computation of t e factorial of a number.

<.ample6 class Outer J int outerX. it can not refer to members of its enclosing class directly.innerMet od12E O class %nner J void innerMet od12 J System. %t as access to all of t e variable and met ods of its outer class and may refer to t em directly. $ at is.out. An inner class is a non?static nested class. it must access t e members of its enclosing class t roug an object.out.2" Prepared by PHANI KISHORE ROMPICHRLA . !ecause it is static.println1M%n Outerclass Met odN2E %nner inHne" %nner12E %n.outerMet od12E O O output6 %n Outerclass Met od %n %nnerclass Met od outer class variable6 1G 2. $ e most important type of nested class is t e inner class.UNIT-II JAVA BASICS $ ere are t"o types of nested classes6 static and non!static.H1GE void outerMet od12 J System.println1M%n %nnerclass Met odN2E System.out. A static nested class is one " ic as t e static modifier applied.println1Mouter class variable6N'outerX.2E O O O class 5isplay J public static void main1String arKL2 J Outer outHne" Outer12E Out.

"it y 3emove " ite spaces at t e beginning and end of String s1 3eturns .& arAt1n2 s1. tri"g Met$ods: (Met ods of tri"g class) $ e String class defines a number of met ods t at allo" us to accomplis manipulation tas+s. int len H name.lengt 12 s1. it is possible to get t e lengt of string using t e lengt met od of t e String class. $ e statement../ t at occurs after nt position in t e? string s1 .replace1./ in string s1 -ives t e position of ./2 s1.lengt 12E Java string can be concatenated using t e ' operator..2# Prepared by PHANI KISHORE ROMPICHRLA ../y/2E s@Hs1./.trim12E s1.Alp abetical ordering of strings class StringOrdering 2.toUo"er&ase12 s@Hs1. String namesKLHne" StringKCLE "ill create an "a(es array of si8e C to old t ree string constants. %n java ..to*pper&ase12 s@Hs1.Of1.A java String is not a c aracter array and is not :*UU terminated.e(uals%gnore&ase1s@2 s1... and 8ero if s1 is e(ual s@ &oncatenates s1 and s@ -ives t e position of t e first occurrence of .compare$o1s@2 s1. a variety of string Met$od s@Hs1.true/ if s1Hs@.n2 Tas/ converts t e String s1 to all lo"ecase converts t e String s1 to all *ppercase 3eplace all appearances of .Of1./. Strings may be declared and created as follo"s6 tri"g stringnameH ne" tri"g1MstringN2E String nameHne" String1M+ant N2E is same as String nameHN+ant NE li+e arrays. Strings are class objects and implemented using t"o classes.UNIT-II JAVA BASICS tri"g =a"d%i"g A String is a se(uence of c aracters.concat1s@2 s1. tri"g and tri"gBu&&er> A java string is an instantiated object of t e String class. positive if s1Qs@. ignoring t e case of c aracters -ives t e lengt of s1 -ives nt c aracter of s1 3eturns >ve if s1Is@. namely.e(uals1s@2E s1. eg6 String firstname H NsriNE String lastname H N+ant NE String name H firstname'lastnameE 1 or 2 String name H NsriN'N+ant NE tri"g -rrays: "e can also create an use arrays t at contain strings.inde.inde.true/ if s1 is e(ual to s@ 3eturns .

out.lengt 12 8eros are added to s1 I(porta"t ?uestio"s i" t$is u"it: 1a2 Fit an e. F ile tri"g creates string of fi. K1GML b2 5escribe t e met ods to modifying a string.lengt E String tempE for1int iHGEiIsi8eEi''2 J for1int jHi'1EjIsi8eEj''2 J if1namesKjL.ample.NafricaN.NusaN.lengt 12 s1 is truncated .setUengt 1n2 Tas/ Modifies t e nt c aracter to . e.2$ Prepared by PHANI KISHORE ROMPICHRLA . !elo".s@2 s1.UNIT-II JAVA BASICS J public static void main1String argsKL2 J String namesKLHJMindiaN. or append anot er string to t e end. tri"gBu&&er creates strings of fle. Fe can insert c aracters and substrings in t e middle of a string.println1namesKiL2E O O above program produces t e follo"ing result afri%a australia india $a+an usa tri"gBu&&er &lass : String!uffer is a peer class of String. if nIs1.NjapanNOE int si8eHnames.set& arAt1n.plain scope and lifetime of variables.ed lengt .compare$o1namesKiL2IG2 J tempHnamesKiLE namesKiLHnameKjLE namesKjLHtempE O O O for1int iHGEiIsi8eEi''2 System./.append1s@2 s1./2 s1.ible lengt t at can be modified in terms of bot lengt and content.if nQs1. Met$od s1.NaustraliaN. K1GML 2. t ere are some of met ods t at are fre(uently used in string manipulations. Appends t e string s@ to s1 at t e end %nserts t e string s@ at t e position n of t e string s1 sets t e lengt of t e string s1 to n.insert1n.

plain "it a java program about reference variables] K1GML C2a2 5escribe java garbage collection mec anism] KAML b2 F at is a constructor] 5escribe its special properties.plain about classes and objectsK1GML 2.K1GML b2 <.2% Prepared by PHANI KISHORE ROMPICHRLA .plain about Met od OverridingK1GML D a2 <.plain about static +ey"ordK1#ML # a2<.a2 !riefly describe t e type conversion mec anisms.plain about &ommand line argumentsK1GML b2 !riefly e.plain about &onstructor overloading]K1GML b2<.UNIT-II JAVA BASICS @.K1@ML = a2F at is t e difference bet"een public member and private member of a classK#ML b2<.