You are on page 1of 29

UNIT-II JAVA BASICS

UNIT-II

JAVA BASICS

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

UNIT-II JAVA BASICS

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

2.2

Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

F%oati"g poi"t types: 9loating point numbers are used " en evaluating e,pressions t at re(uire fractional precision. $ ere are t"o +inds of floating point types, float and double. F ic represent single and double precision numbers respectively. Type ize !a"ge float s ort = bytes A bytes 1.=e?G=# to C.=e'GCA =.9e?C@= to 1.Ae'CGA

&%oat6 t e type float specifies a single precision value t at uses C@ bits of storage. Single precision is faster on same processors and ta+es alf as muc space as double precision. float variables are declared by use of .float/ +ey"ord. eg6 float aH1.@C=E dou#%e6 double precision, as denoted by t e double +ey"ord, uses D= bits to store a value. All transcendental mat functions suc as sin12, cos12 and s(rt12 return double values. double variables are declared by use of .double/ +ey"ord. eg6 double dE c$ar: %n java, t e datatype used to store c aracters is c ar. Java uses Unicode to represent c aracters. *nicode defines a fully international c aracter set t at can represent all of t e c aracters found in all uman languages. $ us in java c ar is a 1Dbit type. $ e range of c ar is G to D##CD. $ ere are no negative c ars. c ar variables are declared by use of c ar +ey"ord. eg6 c ar cE #oo%ea": Java as a simple type called boolean, for logical values. %t can ave only one of t"o possible values, true or false. $ is is t e type returned by all relational operators suc as aIb. !oolean is also t e type re(uired by conditional e,pressions t at govern t e control statements suc as .if/ and .for/. boolean variables are declared by use of .boolean/ +ey"ord. 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, arc itectural neutral is ac ieved because compiler produces an intermediate code called !yte code, for a mac ine is called J0M

A virtual mac ine code is not mac ine specific. $ e code generated by t e java interpreter by acting as an intermediary bet"een t e virtual mac ine and real mac ine.

2.3

Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

I(p%e(e"ti"g a )ava progra(: %mplementation of java application program involves a series of steps. $ ey include &reating t e program &ompiling t e program 3unning t e program 3emember t at, before "e begin creating t e program, J5K must be properly installed on our system. Creati"g t$e progra(: Fe can create a program using any te,t editor class Sample J public static void main1String argKL2 J System.out.println1M4i friendN2E O O Fe ave to save t is program "it a name li+e prog.java A java Application ave any no of classes, but only one main class. 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, "it t e name of t e source file on command line as s o"n belo" &6PQ javac prog.java %f everyt ing is OK, java compiler1javac2 creates a file called Sample.class 1Iclassname.classQ2 containing t e bytecodes of t e program prog.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, typeR &6PQ java Sample :o", t e interpreter loo+s for t e main met od in t e program and begins e,ecution from t ere. F en e,ecuted our program displays t e follo"ing o;p6 Hi friend

Java *!+,!-M T!UCTU!.: A java program may contain many classes of " ic only one class defines a main met od. &lasses contain datamembers and met ods t at operate on t e data members of t e class. Java program may contain one or more sections as s o"n belo".

2.

Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

Docu(e"tatio" sectio": $ is section comprises of a set of comment lines giving t e name of program, t e aut or 7 ot er details, " ic t e programmer "ould li+e to refer at later stage. %t is suggested one. *ac/age state(e"t: $ e first statement allo"ed in java is a .pac+age/ statement. $ 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. I(port state(e"t: $ is is similar to t e Sinclude statement in & <g6 import java.io.TE %t is optional section. I"ter&ace state(e"t: An interface is li+e a class but includes a group of met od declarations. %t is also optional section and is used only " en "e "is to implement t e multiple in eritance feature in jprogram. C%ass De&i"itio"s: A java program may contain multiple class definitions. &lasses are t e primary 7 essential elements of a java program. Mai" Met$od C%ass: Since every java stand alone program re(uires a main met od as its starting point, t is class is t e essential part of a java program.$ e main met od creates objects of various classes and establis es communications bet"een t em. On reac ing t e end of main, t e program terminates and t e control passes bac+ to t e operating system.
C+MM-ND 0IN. -!,UM.NT :

Sometimes "e "ill need to supply data into a java program " en it runs. $ is type of data "ill be supplied in t e form of command line arguments. $ e command line arguments "ill immediately follo" t e program name on t e command line. $ ese command line arguments "ill be collected into an array of string " ic is supplied as a parameter to main met ods. 2.! Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

Uater t ese command line arguments must be processed and t en accessed. $ e follo"ing program ta+es command line argument and prints t em. <g6 class 5isplay J public static void main1String argsKL2 J for1iHGEiIargs.lengt 12Ei''2 System.out.println1argsKiL2E O O c6PQ javac file.java c6PQ java 5isplay i t is is ur friend o;p-> hi this is ur friend

'-!I-B0. : A variable is an identifier t at denotes a storage location used to store a data value. All variables ave a scope, " ic defines t eir visibility and a lifetime. Dec%ari"g varia#%e: All variables must be declared before t ey can be used. $ e basic form of a variable declaration is , type identifier[=value][, identifier [=value] ]; <g6 int valueE float avgE in t e above e,ample, .value/ is an integer type variable , " ere as .avg/ is float type variable. $o declare more t an one variable of t e specified type, use a comma?separated list. int a,b,cE int dHC,e,fH#E ;; declares t ree integer variables a, b, and c ;; declares C integer variables initiali8ing d and f

*nli+e in &, variable can be declared any " ere in t e program, " ere ever t ey are needed. Dy"a(ic I"itia%izatio": Alt oug t e preceding e,amples ave used only constants as initiali8ers, java allo"s variables to be initiali8ed dynamically, using any e,pression valid at t e time t e variable is declared. 9or e,ample, &lass 5yn%nit J )ublic static void main1String argKL2 J double aHC.G, bH=.GE double cHMat .s(rt1aTa'bTb2E ;; c is dynamically initiali8ed System.out.println1M4ypotenuse is N'c2E O 2." Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

O 4ere, t ree local variables a, b, c are declared. $ e t"o a and b are initiali8ed by constants. 4o"ever c is initiali8ed dynamically. 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.$ ey ta+e different values for eac object. Class variables are global to a class and belong to t e entire set of objects t at class creates. Only one memory location is created for eac class variable. %nstance and class variables are declared inside a class. Local variables are declared and used inside met ods and program bloc+s1defined bet"een opening brace J and a closing braceO 2. $ 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+. 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. As a general rule, variables declared insid a scope are not visible to code t at is defined outside t at scope. Scopes can be nested. 9or e,ample, eac time you create a bloc+ of code, you are creating a ne", nested scope. F en t is occurs, t e outer scope encloses t e inner scope.$ is means t at objects declared in t e outer scope "ill be visible to code "it in t e inner scope. 4o"ever t e reverse is not true. Objects declared "it in t e inner scope "ill not be visible outside it. ;; program to demostarte bloc+ scope class scope J public static void main1String arKL2 J %nt ,E ;; +no"n to all code "it in main ,H1GE if1,HH1G2 J %nt y H@GE ;; +no"n only to t is bloc+ System.out.println1M, and y6 N','N N'y2E ,HyT@E O y H 1GGE ;; <rrorV y not +no"n ere System.out.println1M, is N',2E ;; , is still +no"n ere O O As t e comments indicate, t e variable , is declared at t e start of (ai"()/s scope and is accessible to all subse(uent code "it in main12. y is only visible to t e code in if bloc+ .

Lifetime of variables:

2.#

Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

0araibles are created " en t eir scope is entered, and destroyed " en t eir scope is left. $ is means t at a variable "ill not old its value once it as gone out of scope. $ erefore, 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. $ us, t e lifetime of a variable is confined to its scope. class Uifetime J public static void main1String arKL2 J int ,E for1,HGE ,ICE ,''2 J int yH?1E ;; y is initiali8ed eac time bloc+ is entered System.out.println1My is 6 N'y2E ;; t is al"ays prints ?1 WH1GGE System.out.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. Arrays of anytype can be created and may ave one or more dimensions. A specific element in an array is accessed by its inde,. 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. So t e general form of ne" as it applies to one?dimensional arrays appears as follo"s. type var?nameKLHne" typeKsi8eLE eg6 int mar+sKL H ne" intK@GLE ;;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.$ Prepared by PHANI KISHORE ROMPICHRLA

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.out.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,@A,C1,CG,C1,CG,C1,C1,CG,C1,CG,C1OE System.out.println1MOctober as N'mont XdaysK9L'N daysN2E O O O Two (Multi)-Dimensional Arrays: %n java, multidimensional arrays are actually arrays of arrays. e,ample6 int t"o5KLKL H ne" intK=LK#LE eg program6 class Matri, J public static void main1String arKL2 J int matKLKLHne" intKCLK=LE for1int iHGEiICEi''2 J for1int jHGEjI=Ej''2 J matKiLKjLHiE System.out.print1matKiLKjL'N N2E O System.out.println12E O O O t e above program inserts values into a matri, .mat/ of order C,= and prints

2.%

Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

;; 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.print1tKiLKjL'N N2E O System.out.println12E O O O

+perators
Java supports a ric set of operators. Operators are used in programs to manipulate data and variables. Java operators can be classified into a number of related categories as belo"6 1. -rit metic operators @. Increment 7 5ecrement operators C. !elational operators =. Bit"ise operators #. 0ogical operators D. -ssignment Operator B. Conditional Operator 12Arit metic operators6 $ ese are used in mat ematical e,pressions in t e same "ay t at t ey are used in algebra. $ e follo"ing are t e list of arit metic operators6 +perator Mea"i"g ' Addition ? Subtraction T Multiplication 2.1& Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

; Y 'H ?H TH ;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;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. $ e increment operator increases its operand by one. $ e decrement operator decreases its operand by one. for e,ample, ,H,'1E can be "ritten li+e ,''E using increment operator similarly, ,H,?1E can be "ritten li+e ,??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 outcome of t ese operators is a #oo%ea" value. $ e relational operational operators are most fre(uently used in t e e,pressions t at control t e i& statement and t e various %oop statements. $ 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, t e result produced by a relational operator is a !oolean value. 9or e,ample, int aH=E int bH1E boolean cHaQbE - in t is case, t e result of aIb1" ic is true2 is stored in c if1aQb2 J O in t is case, aQb results true, so if statement "ill be e,ecuted

!it"ise operators6 Java defines several bit"ise operators " ic can be applied to t e integer types, long, int, s ort, c ar, and byte. $ ese operators act upon t e individual bits of t eir operands. $ e follo"ing are t e list of !it"ise operators6 +perator 7 V Z 1 2.11 Mea"i"g bit"ise A:5 bit"ise O3 bit"ise [O3 bit"ise unary :O$

Prepared by PHANI KISHORE ROMPICHRLA

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. $ ey operate on #oo%ea" operands. All of t e binary logical operators combine t"o #oo%ea" values to form a resultant #oo%ea" value. +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. for e,ample, if1 aQb 77 , 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, H . %t as general form6 var =e%pression; 4ere, t e type of var must be compatible "it t e type of e,pression. t e assignment operator allo"s to create a c ain of assignments. 9or e,ample, int ,, y, 8E , H y H 8 H 1GGE ;; set ,, y and 8 to 1GG

&onditional Operator1 6:2


$ e c aracter pair ]6 is a ternary operator available in Java. $ is operator is used to construct conditional e,pressions of t e form

e%p& ' e%p( : e%p)


e%p& is evaluated firt. %t it is non8ero 1true2, t en t e e%p( is evaluated and becomes t e value of t e conditional e,pression. if e%p& is false, e%p) is evaluated and its value becomes t e value of t e conditional e,pression. 9or e,ample, aH1G , bH@GE , H 1 a Q b 2] a 6 b E , "ill be assigned t e value of b. $ is can be ac ieved using t e i&7e%se statement as follo"s6 if1a Q b2 , H aE else , H bE

.8pressio"s
F en operands and operators are combined, an e,pression is formed. $ e e,ecution of an e,pression "ill produce a value. #rit*metic e%pression: %f "e use arit metic operators in an e,pression, t at is treated as an Arit metic e,pression. <g6 a'b?cE Increment or "ecrement +%pression, 2.12 Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

%f "e use %ncrement or 5ecrement operators in an e,pression, t at is treated as %ncrement or 5ecrement e,pression. <g6 a''E b? ?E -elational e%pression: %f "e use 3elational operators in an e,pression, t at is treated as a 3elational e,pression6 <g6 aQbE Lo$ical e%pression: %f "e use !oolean logical operators in an e,pression, t at is treated as a logical e,pression6 a77bE Conditional e%pression: %f "e use arit metic operators in an e,pression, t at is treated as an &onditional e,pression. aQb] a6 bE R li+e t is, "e ave some ot er e,pressions.

<g6

<g6

Co"tro% tate(e"ts
A &ontrol statement is a statement t at controls t e flo" of e,ecution of t e program. 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,pression or t e state of a variable. $ ere are t"o selection statements 6 i& and switc$

1a2 if statement6
.if/ is a selection statement t at is used to c oose t"o c oices in a program.
Synta,6

if1condition2 statement1E else statement@E .condition/ is any e,pression t at returns a !oolean value 1i.e., true;false2. Statement is a single or multiple statements. %f t e condition is true t en t e control goes to t e statement1 and it is e,ecuted. Ot er"ise, t e statement@ is e,ecuted.

1b2 :ested if statement6


%t means an if statement under anot er if statement.
Synta,6

if1condition2 J if1condition2 statementE O

1c2 if?else?if ladder6


if?else?if statement is a se(uence of if?else statements. 2.13 Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

Synta,6

if1condition2 statement1E else if1condition2 statement@E else if1condition2 statementCE . . 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.

1d2 s"itc statement6


%t provides more t an one c oice to c oose. %t/s a better alternative to if?else?if ladder.
Synta,6

s"itc 1e,pression2 J case value16 statement1E brea+E case value@6 statement@E brea+E case valueC6 statementCE brea+E . . . case value:6 statement:E brea+E default 6 O ere, t e e,pression may be of type byte, s ort, int or c ar only. t e case values must be of type e,pression and eac value s ould be uni(ue. " en control comes to t e s"itc statement t en t e value of t e e,pression is compared "it t e case values, if a matc is found t en t e statement1s2 corresponding to t at case is e,ecuted. %f none of t e case is matc ed t en t e default statement is e,ecuted. @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, do-w$i%e and &or statementE

1a2 " ile statement6

2.1

Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

." ile/ is an iteration statement, t at repeats a statement or bloc+ of statements until some condition is true.
Synta,6

" ile1condition2 J ;; body of t e loop O

" ere t e condition may be any boolean e,pression. $ e body of t e loop "ill be e,ecuted as long as t e condition is true. Once t e condition becomes false, t e control passes to t e statement immediately after t e " ile loop.

1b2 do?" ile statement6


.do?" ile/ statement is very muc similar to " ile statement "it little difference. %n " ile statement, if t e condition is initially false t en t e body of loop "ill not be e,ecuted at all. F ere as in do?" ile statement, 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.
Synta,6

do J ;; body of t e loop O " ile1condition2E <ac iteration of do?" ile e,ecutes t e body of loop first and evaluates t e condition later. %f condition is true, t e loop repeats. Ot er"ise, t e loop terminates.

1c2 for statement6


.for/ statement also repeats t e e,ecution of statements " ile its condition is true.
Synta,6

for1initiali8ationE conditionE iteration2 J ;; 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. $ is portion is e,ecuted first " en t e loop starts. And it is e,ecuted only once. " en t e control goes to condition, condition is evaluated. %f condition is true, t e body of loop is e,ecutes. Ot er"ise t e loop terminates.:e,t iteration portion is e,ecuted. $ is elps to increment or decrement t e control variable. $ e loop t en iterates evaluating condition, t en e,ecuting t e body and t en e,ecuting t e iteration portion eac time it iterates. @2 Jump Statements6
Jump statements allo"s t e control to jump to a particular position. $ ere are C types of jump statements.

1a2 brea+ statement6 in java, t ere are C uses of brea+ statement. 1i2 1ii2 1iii2 2.1! %t elps to terminate a statement se(uence in switc$ statement. %t can be used to e,it or ter(i"ate t e loop %t can be used as anot er form of goto Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

<g6 class A J public static void main1String argKL2 J for1int iHGE iI1GGE i''2 J if1iHH1G2 brea+E ;; terminates loop if i is 1G System.out.println1Mi 6N'i2E O O O 1b2 continue statement6
$ e continue statement starts t e ne,t iteration of t e immediately enclosing iteration statements1" ile, do?" ile or for2. F en t e control goes to continue statement, t en it s+ips t e remaining statements and starts t e ne,t iteration of enclosing structure.

<g6 class A J public static void main1String argKL2 J for1int iHGE iI1GGE i''2 J System.out.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 reac es to return statement, it causes t e program control to transfer bac+ to t e caller of t e met od. <g6 class A J public static void main1String argKL2 J boolean tHtrueE if1t2 returnE System.out.println1M4iN2E ;; $ is "on/t e,ecute O O %n t is e,ample, return statement returns to t e java run time system, since t e caller of main12 is runtime system.

Type Co"versio" 4 Costi"g


2.1" Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

Fe can assign a value of a variable of one type to a variable of anot er type. $ is process is +no"n as casting. %f t"o types are compatible "it eac ot er, t en t e type conversion is done implicitly by Java. $ is is +no"n as automatic 1implicit2 type conversion. <g6 int aH1GE double bHaE As s o"n in above e,ample, it is al"ays possible to assign t e value of int variable .a/ to double variable .b/. $ 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.

#utomatic .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. 1i2 $ e types are compatible 1ii2
$ e destination type is larger t an t e source type. A "idening conversion too+ place " en t ese @ rules are satisfied. <,ample, "idening conversion ta+es place bet"een int and byte as int is larger t an byte to old its all valid values.

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, because a byte is smaller t an an int. $ is +ind of conversion is called narro"ing conversion. $o create a conversion bet"een t"o incompatible types, "e must use a cast. A cast is simply an e,plicit type conversion. %t as t is general form6 /tar$et!type0 value 4ere, target?type specifies t e desired type to convert t e specified value to. $ 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.1=@E System.out.println1N&onversion of int to byteN2E bH1byte2 iE System.out.println1Mi and b N'i'N N'b2E System.out.println1N&onversion of double to intN2E iH1int2 dE System.out.println1Mi and b N'i'N N'b2E System.out.println1N&onversion of double to byteN2E bH1byte2 dE System.out.println1Mi and b N'i'N N'b2E O O

2.1#

Prepared by PHANI KISHORE ROMPICHRLA

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.142 Conversion of double to byte d and b 323.142 %n above eg, F en t e value @#B is cast into a byte variable, t e result is t e remainder of t e division of @#B by @#D1range of byte2, " ic is 1 in t is case. F en t e d is converted to an int, its fractional component is lost. F en d is converted to a byte, its fractional component is lost, and t e value is reduces modulo @#D, " ic in t is case is DB.

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. F en "e are creating a class "e are actually creating a ne" datatype. $ is ne" datatype is also called A5$. ??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, a class can be defined t roug t e use of class +ey"ord. $ e general definition of a class is given belo"6 class classname J type instanceXvariable1E type instanceXvariable1E . . . returntype met od name1parameter list2 J ;; body of met od O . . . O 4ere, 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, . . . 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 <,ample6 class sample J 2.1$ Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

int ,, yE set[W12 J ,H1GE yH@GE O O $ e variables defined in t e class are called member variables;data members $ e functions defined in t e class are called member functions;member met ods. !ot data members and member met ods toget er called members of class.

Co"cept o& +#)ects


Objects are instances of a class. Objects are created and t is process is called M%nstantiationN. %n java objects are created t roug t e use of ne" operator. $ e ne" operator creates an object and allocates memory to t at object. Since objects are created at runtime, t ey are called runtime entities. %n java object creation is a t"o step process. 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. 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. <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.

-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 ... 1dot2 operator. Synta,6 ob1ectname, member; <,ample6 class sample J int ,, yE set[W12 J ,H1GE yH@GE O print[W12 J System.out.print1MHN',2E System.out.print1MHN'y2E O O class 5emo J public static void main1String arKL2 J Sample sE sHne" String12E s.set[W12E 2.1% Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

s.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. %t is used to automaticallyl initiali8e an object " en t e object is created. &onstructor gets e,ecuted automatically at t e time of creating t e object. A constructor doesn/t ave any return type. <,ample6 ;; program to demonstrate constructor class Student J int numberE String nameE Student12 ;; default constructor J numberH#D9E nameHNsatyamNE O Student1int no, String s2 ;; parameteri8ed constructor J numberHnoE nameHsE O void s o"Student12 J System.out.println1Mnumber HN'number2E System.out.println1Mname HN'name2E O O class 5emo J public static void main1String arKL2 J Student s1Hne" Student12E Student s@Hne" Student1B@,NrajuN2E s1.s o"Student12E s1.s o"Student12E O O output:nu!ber" 5 # na!e" satya! nu!ber" 72 na!e" ra$u ;; and e,plain about above program

;this< /eyword
.t is/ +ey"ord refers to t e current object. sometimes a member met od of a class needs to refer to t e object in " ic it "as invo+ed. %n order to serve t is purpose java introduces Mt is +ey"ordN. 2.2& Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

!y using .t is/ +ey"ord "e can remove name space conflict. 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, local variables ta+e t e priority over t e instance variable. $ is leads to conflict called .name space conflict/. %t can be resolved t roug use of Mt isN eg6 class Student J int numberE String nameE void setStudent1int number, String name2 J t is.numberHnumberE t is.nameHnameE O void s o"Student12 J System.out.println1MnumberHN'number2E System.out.println1MnameHN'name2E O O class 5isplay J public static void main1String arKL2 J Student sHne" Student12E ;; object creation for class Student s.setStudent11,N3amaN2E s.s o"Student12E O O

*nderstanding static +ey"ord6


%n java , static +ey"ord can be used for t e follo"ing purposes. 1. $o create static data members @. $o define static met ods C. $o define static bloc+s tatic varia#%es: F en a datamember of a class, is declared static only one copy of it is created in memory and is used by all t e objects of t e class. 4ence static variables are essentially global variables. 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. 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; super +ey"ord. tatic B%oc/s: Just li+e static variables and static met ods "e can also create a static bloc+ . t is static bloc+ is used to initiali8e t e static variables. <,ample program6 class *seStatic J 2.21 Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

static int aHCE static int bE static void met 1int ,2 J System.out.println1M,HN ' ,2E System.out.println1MaHN ' a2E System.out.println1MbHN ' b2E O static J System.out.println1Mstatic bloc+ initiali8edN2E O public static void main1String argsKL2 J met 1D92E O O output6 stati% blo%& initiali'ed ( " # a " 3 b " 12 ;; and e,plain about program

-ccess Co"tro%:
Java/s access specifiers are public, private and protected. Java also defines a default access level. protected applies only " en in eritance is involved. F en a member of a class is specified as public, t en t at member can be accessed by anyot er code. F en a member of class is specified as private, t en t at member can only be accessed by ot er members of its class, but not anyot er class members.

,ar#age Co%%ectio"
Objects are dynamically allocated using t e .ne"/ operator and t eir memory must be released after reallocation. %n &'', t ey are manually released by t e use of delete operator. Java deallocates memory automatically and it is called M-arbage &ollectionN. F en no references to an object e,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.

Fi"a%ize() Met$od :
%n some situations an object "ill lead to perform some action " en it is destroyed. Suppose for e,ample an object is olding some non?java resource suc as file? andling. Fe must ave to free t e resources after t e object is destroyed. $o andle t ese situations java provides finali8ation using finali8e12 met od Synta,6 protected void finali8e12 J ;; finali8ation code ere O protected prevents to access finali8e met od by code defined outside t e class.

void is used because it doesn/t return anyt ing. +ver%oadi"g (et$ods


2.22 Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

%n java, it is possible for a class, to contain t"o or more met ods "it t e same name as long as t e met od signatures are different. $ 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.
+%ample:

class Student J int no ,mar+sE String nameE void setStudent12 J noH1E mar+sHA9E nameHNramaNE O void setStudent1int no, int mar+s, String name2 J t is.noHnoE t is.mar+sHmar+sE t is.nameHnameE O void s o"Student12 J System.out.println1MnumberHN'no2E System.out.println1Mmar+sHN'mar+s2E System.out.println1MnameN'name2E O O class Met odOverload J public static void main1String arKL2 J Student sHne" Student12E s.setStudent12E s.s o"Student12E s.setStudent1D9,A1,NramuN2E s.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. t e follo"ing e,ample demonstrates t is, 2.23 Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

class Student J int noE String nameE Student12 J noHBGE nameHNramNE O Student1int n, String s2 J noHnE nameHsE O void s o"12 J System.out.println1M:umberHN'no2E System.out.println1M:ameHN'name2E O O class 5isplay J public static void main1String arKL2 J Student s1H ne" Student12E Student s@H ne" Student1D9,NsatyaN2E s1.s o"12E s@.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. 1. call by value @. call by reference %n t e first "ay, t e c ange made to t e parameter of t e subroutine ave no effect on t e argument. %n t e second "ay, t e c anges made to t e parameter "ill effect t e argument used to call t e subroutine. %n java " en you pass a primitive type it is pass by value. " en you pass an object1reference2 to a met od, it is done t roug pass by reference <,ample6 ;; call by value class $est J void met 1int i , int j2 J 2.2 Prepared by PHANI KISHORE ROMPICHRLA

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 , bH@GE System.out.println1Ma and b before call6 N'a'N N'b2E ob.met 1a,b2E System.out.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 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 met od t at calls itself is said to be recursive met od. $ e classic e,ample of recursion is t e computation of t e factorial of a number. 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.out.println1M9actorial of # isN' f.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. Suc classes are +no"n as nested classes. $ e scope of nested class is bounded by t e scope of its enclosing class. $ us, if class ! is defined "it in class A, t en ! is +no"n to A, but not outside of A. A nested class as access to t e members, including private members, of t e class in " ic it is nested. 4o"ever, t e enclosing class does not ave access to t e members of t e nested class.

2.2!

Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

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

2.2"

Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

tri"g =a"d%i"g
A String is a se(uence of c aracters. %n java , Strings are class objects and implemented using t"o classes, namely, tri"g and tri"gBu&&er> A java string is an instantiated object of t e String class.A java String is not a c aracter array and is not :*UU terminated. 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, it is possible to get t e lengt of string using t e lengt met od of t e String class. int len H name.lengt 12E Java string can be concatenated using t e ' operator. 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. $ e statement, String namesKLHne" StringKCLE "ill create an "a(es array of si8e C to old t ree string constants. 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.

a variety of string

Met$od
s@Hs1.toUo"er&ase12 s@Hs1.to*pper&ase12 s@Hs1.replace1.,/,/y/2E s@Hs1.trim12E s1.e(uals1s@2E s1.e(uals%gnore&ase1s@2 s1.lengt 12 s1.& arAt1n2 s1.compare$o1s@2 s1.concat1s@2 s1.inde,Of1.,/2 s1.inde,Of1.,/,n2

Tas/
converts t e String s1 to all lo"ecase converts t e String s1 to all *ppercase 3eplace all appearances of , "it y 3emove " ite spaces at t e beginning and end of String s1 3eturns .true/ if s1 is e(ual to s@ 3eturns .true/ if s1Hs@, ignoring t e case of c aracters -ives t e lengt of s1 -ives nt c aracter of s1 3eturns >ve if s1Is@, positive if s1Qs@, and 8ero if s1 is e(ual s@ &oncatenates s1 and s@ -ives t e position of t e first occurrence of .,/ in string s1 -ives t e position of .,/ t at occurs after nt position in t e? string s1

;;Alp abetical ordering of strings class StringOrdering


2.2# Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

J public static void main1String argsKL2 J String namesKLHJMindiaN,NusaN,NaustraliaN,NafricaN,NjapanNOE int si8eHnames.lengt E String tempE for1int iHGEiIsi8eEi''2 J for1int jHi'1EjIsi8eEj''2 J if1namesKjL.compare$o1namesKiL2IG2 J tempHnamesKiLE namesKiLHnameKjLE namesKjLHtempE O O O for1int iHGEiIsi8eEi''2 System.out.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. F ile tri"g creates string of fi,ed lengt , tri"gBu&&er creates strings of fle,ible lengt t at can be modified in terms of bot lengt and content. Fe can insert c aracters and substrings in t e middle of a string, or append anot er string to t e end.

!elo", t ere are some of met ods t at are fre(uently used in string manipulations. Met$od
s1.set& arAt1n,/,/2 s1.append1s@2 s1.insert1n,s@2 s1.setUengt 1n2

Tas/
Modifies t e nt c aracter to , 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. if nIs1.lengt 12 s1 is truncated .if nQs1.lengt 12 8eros are added to s1

I(porta"t ?uestio"s i" t$is u"it: 1a2 Fit an e,ample, e,plain scope and lifetime of variables. K1GML b2 5escribe t e met ods to modifying a string. K1GML

2.2$

Prepared by PHANI KISHORE ROMPICHRLA

UNIT-II JAVA BASICS

@.a2 !riefly describe t e type conversion mec anisms.K1GML b2 <,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.K1@ML = a2F at is t e difference bet"een public member and private member of a classK#ML b2<,plain about static +ey"ordK1#ML # a2<,plain about &onstructor overloading]K1GML b2<,plain about Met od OverridingK1GML D a2 <,plain about &ommand line argumentsK1GML b2 !riefly e,plain about classes and objectsK1GML

2.2%

Prepared by PHANI KISHORE ROMPICHRLA

You might also like