Java Tutorial 1. Java - What, Where and Why? 2. What is Java 3. Where Java is used 4. Java Applications Java Tutorial or Core Java Tutorial or Java Prora!!in Tutorial is a "idel y used ro#ust technoloy. $et%s start learnin o& 'ava &ro! #asic (uestions li)e "hat is 'ava tutorial, core 'ava, "here it is used, "hat type o& applications are created in 'ava and "hy use 'ava.
What is Java Java is a programming programming language and a platform . Java is a hih level, ro#ust, secured and o#'ect-oriented prora!!in lanuae. Platform * Any hard"are or so&t"are environ!ent in "hich a prora! runs, is )no"n as a plat&or!. +ince Java has its o"n runti!e environ!ent J/ and AP0, it is called plat&or!.
Java Example $et%s have a (uic) loo) at 'ava prora!!in ea!ple. A detailed description o& hello 'ava ea!ple is iven in net pae. 1. clas classs +i! +i!pl ple e 2.
pu#lic pu#lic static static void void !ain+ !ain+trin trin ars/ ars/
3.
+yste! +yste!.ou .out.p t.prin rintln tln56 56ello ello Java5/7 Java5/7
4.
8
9. 8 Test it :o"
Where it is used?
Accordin to +un, 3 #illion devices run 'ava. There are !any devices "here 'ava is currently used. +o!e o& the! are as &ollo"s* 1. ;es)top ;es)top Applica Applications tions such such as acro#at reader, reader, !edia !edia player, player, antiviru antiviruss etc. 2. We We# # Applica Applications tions such such as irctc.co.in, irctc.co.in, 'avatpoint.c 'avatpoint.co! o! etc. 3. nterprise nterprise Applicati Applications ons such such as #an)in #an)in applications applications.. 4. . o#otics . @a!es etc.
Types of Java Applications There are !ainly 4 type o& applications that can #e created usin 'ava prora!!in* 1) Standalone Application
0t is also )no"n as des)top application or "indo"-#ased application. An application that "e need to install on every !achine such as a s !edia player, antivirus etc. AWT AWT and +"in are used in 'ava &or creatin standalone applications. ) We! Application
An application that runs on the server side and creates dyna!ic pae, is called "e# application. Currently, servlet, 'sp, struts, 's& etc. technoloies are used &or creatin "e# applications in 'ava. ") Enterprise Application Application
An application that is distri#uted in nature, such as #an)in applications etc. 0t has the advantae o& hih level security, load #alancin and clusterin. 0n 'ava, J is used &or creatin enterprise applications. #) $o!ile Application
An application that is created &or !o#ile devices. Currently Android and Java < are used &or creatin !o#ile applications.
%istory of Java 1. rie& history o& Java 2. Java Bersion 6istory Java history is interestin to )no". The The history o& 'ava starts &ro! @reen @ree n Tea!. Tea!. Java tea! !e!#ers also )no"n as &reen Team/, initiated a revolutionary tas) to develop a lanuae &or diital devices such as set-top #oes, televisions etc.
or the reen tea! !e!#ers, it "as an advance concept at that ti!e. ut, it "as suited &or internet prora!!in. $ater, Java technoloy as incorporated #y :etscape.
Currently, Java is used in internet prora!!in, !o#ile devices, a!es, e-#usiness solutions etc. There are iven the !a'or points that descri#es the history o& 'ava. 1/ James &osling, $i'e Sheridan, and Patric' (aughton initiated the Java lanuae pro'ect in June 1DD1. The The s!all tea! o& sun enineers called &reen Team. 2/ Eriinally desined &or s!all, e!#edded syste!s in electronic appliances li)e set-top #oes. 3/ irstly, it "as called &reental' #y Ja!es @oslin and &ile etension "as .t. 4/ A&ter that, it "as called *a' and and "as developed as a part o& the @reen pro'ect. Features of Java 1. Features of Java 1. Simple 2. Object-Oriented 3. Platform Independent 4. secured . !obust ". #rc$itecture %eutral &. Portable '. (i)$ Performance *. +istributed
1,.ulti-t$readed
There is iven !any &eatures o& 'ava. They are also )no"n as 'ava #uFF"ords. The Java eatures iven #elo" are si!ple and easy to understand. 1. Simple 2. Object-Oriented 3. Platform independent 4. Secured . !obust ". #rc$itecture neutral &. Portable '. +namic *. Interpreted 1,.(i)$ Performance 11.ultit$readed 12.+istributed
Simple #ccordin) to Sun/ Java lan)ua)e is simple because0 snta is based on so easier for pro)rammers to learn it after 5. removed man confusin) and6or rarel-used features e.)./ eplicit pointers/ operator overloadin) etc. %o need to remove unreferenced objects because t$ere is #utomatic 7arba)e ollection in java.
Object-oriented Object-oriented means 8e or)ani9e our soft8are as a combination of di:erent tpes of objects t$at incorporates bot$ data and be$aviour. Object-oriented pro)rammin)OOPs5 is a met$odolo) t$at simplif soft8are development and maintenance b providin) some rules. ;asic concepts of OOPs are0
1. Object 2. lass 3. In$eritance 4. Polmorp$ism . #bstraction
".
Platform Independent # platform is t$e $ard8are or soft8are environment in 8$ic$ a pro)ram runs. =$ere are t8o tpes of platforms soft8are-based and $ard8are-based. Java provides soft8are-based platform. =$e Java platform di:ers from most ot$er platforms in t$e sense t$at it>s a soft8are-based platform t$at runs on top of ot$er $ard8are-based platforms.It $as t8o components0 1. !untime
2. #PI#pplication Pro)rammin) Interface5
Java code can be
run on multiple platforms e.).?indo8s/@inu/Sun Solaris/ac6OS etc. Java code is compiled b t$e compiler and converted into btecode.=$is btecode is a platform independent code because it can be run on multiple platforms i.e. ?rite Once and !un #n8$ere?O!#5.
Secured Java is secured because0
•
%o eplicit pointer
•
Pro)rams run inside virtual mac$ine sandbo.
•
•
•
Classloader- adds securit b separatin) t$e pacAa)e for t$e classes of t$e local Ble sstem from t$ose t$at are imported from net8orA sources. Bytecode Verier- c$ecAs t$e code fra)ments for ille)al code t$at can violate access ri)$t to objects. Security Manager- determines 8$at resources a class can access suc$ as readin) and 8ritin) to t$e local disA.
=$ese securit are provided b java lan)ua)e. Some securit can also be provided b application developer t$rou)$ SS@/J##S/crpto)rap$ etc.
Robust !obust simpl means stron). Java uses stron) memor mana)ement. =$ere are lacA of pointers t$at avoids securit problem. =$ere is automatic )arba)e collection in java. =$ere is eception $andlin) and tpe c$ecAin) me c$anism in java. #ll t$ese points maAes java robust.
rc!itecture-neutral =$ere is no implementation dependent features e.). si9e of primitive tpes is set.
Portable ?e ma carr t$e java btecode to an platform.
"ig!-performance Java is faster t$an traditional interpretation since bte code is CcloseC to native code still some8$at slo8er t$an a compiled lan)ua)e e.)./ 5
#istributed ?e can create distributed applications in java. !I and
Multi-t!readed A thread is li)e a separate prora!, eecutin concurrently. We can "rite Java prora!s that deal "ith !any tas)s at once #y de&inin !ultiple threads. The !ain advantae o& !ultithreadin is that it shares the sa!e !e!ory. Threads are i!portant &or !ulti-!edia, We# applications etc. Simple Pro)ram of Java 1. Soft8are !eDuirements 2. reatin) (ello Java <ample 3. !esolvin) javac is not reco)ni9ed problem
0n this pae, "e "ill learn ho" to "rite the si!ple prora! o& 'ava. We can "rite a si!ple hello 'ava prora! easily a&ter installin the J;G. To create a si!ple 'ava prora!, you need to create a class that contains !ain !ethod. $et%s understand the re(uire!ent &irst.
Re$uirement for "ello %a&a '(ample For eecutin) an java pro)ram/ ou need to •
•
install t$e J+E if ou don>t $ave installed it/ do8nload t$e J+E and install it. set pat$ of t$e jdA6bin director. $ttp066888.javatpoint.com6$o8-to-setpat$-in-java
•
create t$e java pro)ram
•
compile and run t$e java pro)ram
Creating !ello ja&a e(ample $et%s create the hello 'ava prora!* 1. class Simple 2.
public static void mainStrin) ar)sGH5
3.
Sstem.out.printlnC(ello JavaC5
4.
. =est it %o8 save this &ile as +i!ple.'ava
)o compile*
javac Simple.java
)o e(ecute*
java Simple
Output:Hello Java
+nderstanding rst ja&a program $et%s see "hat is the !eanin o& class, pu#lic, static, void, !ain, +trin, +yste!.out.println/. •
•
•
class Ae8ord is used to declare a class in java. public Ae8ord is an access modiBer 8$ic$ represents visibilit/ it means it is visible to all. static is a Ae8ord/ if 8e declare an met$od as static/ it is Ano8n as static met$od. =$e core advanta)e of static met$od is t$at t$ere is no need to create object to invoAe t$e static met$od. =$e main met$od is
eecuted b t$e JK/ so it doesn>t reDuire to create object to invoAe t$e main met$od. So it saves memor. •
&oid is t$e return tpe of t$e met$od/ it means it doesn>t return an value.
•
main represents startup of t$e pro)ram.
•
String, args is used for command line ar)ument. ?e 8ill learn it later.
•
System.out.println/0 is used print statement. ?e 8ill learn about t$e internal 8orAin) of Sstem.out.println statement later.
To "rite the si!ple prora!, open notepad #y start menu +, All Programs +, Accessories +, notepad and "rite si!ple prora! as displayed #elo"*
#s displaed in t$e above dia)ram/ 8rite t$e simple pro)ram of java in notepad and saved it as Simple.java. =o compile and run t$is pro)ram/ ou need to open command prompt b start menu -1 ll Programs -1 ccessories -1 command prompt .
=o compile and run t$e above pro)ram/ )o to our current director Brst m current director is c0Lne8 . ?rite $ere0
)o compile*
javac Simple.java
)o e(ecute*
java Simple
(o8 man 8as can 8e 8rite a java pro)ram
There are !any "ays to "rite a 'ava prora!. The !odi&ications that can #e done in a 'ava prora! are iven #elo"* 1) -y changing se.uence of the modifiers/ method prototype is not changed0
$et%s see the si!ple code o& !ain !ethod. 1. static public void mainStrin) ar)sGH5
) su!script notation in ava array can !e used after type/ !efore varia!le or after varia!le0
$et%s see the di&&erent codes to "rite the !ain !ethod. 1. public static void mainStrin)GH ar)s5 2. public static void mainStrin) GHar)s5 3. public static void mainStrin) ar)sGH5
") 2ou can provide var+args support to main method !y passing " ellipses 3dots)
$et%s see the si!ple code o& usin var-ars in !ain !ethod. We "ill learn a#out var-ars later in Java :e" eatures chapter. 1. public static void mainStrin)... ar)s5
#) %aving semicolon at the end of class in ava is optional0
$et%s see the si!ple code. 1. class # 2. static public void mainStrin)... ar)s5 3. Sstem.out.printlnC$ello java4C5 4. .
Kalid java main met$od si)nature 1. public static void mainStrin)GH ar)s5 2. public static void mainStrin) GHar)s5 3. public static void mainStrin) ar)sGH5 4. public static void mainStrin)... ar)s5 . static public void mainStrin)GH ar)s5 ". public static Bnal void mainStrin)GH ar)s5 &. Bnal public static void mainStrin)GH ar)s5 '. Bnal strictfp public static void mainStrin)GH ar)s5
Invalid java main met$od si)nature
1. public void mainStrin)GH ar)s5 2. static void mainStrin)GH ar)s5 3. public void static mainStrin)GH ar)s5 4. abstract public static void mainStrin)GH ar)s5
Resol&ing an error 2ja&ac is not recogni3ed as an internal or e(ternal command2 4 0& there occurs a pro#le! li)e displayed in the #elo" &iure, you need to set path. +ince ;E+ doesn%t )no" 'avac or 'ava, "e need to set path. Path is not re(uired in such a case i& you save your prora! inside the 'd)H#in &older. ut its ood approach to set path. Clic) here &or 6o" to set path in 'ava.
Kariable and +atatpe in Java 1. Kariable 2. =pes of Kariable
3. +ata =pes in Java In t$is pa)e/ 8e 8ill learn about t$e variable and java data tpes. Kariable is a name of memor location. =$ere are t$ree tpes of variables0 local/ instance and static. =$ere are t8o tpes of datatpes in java/ primitive and non-primitive.
Variable Baria#le is na!e o& reserved area allocated in !e!ory.
1. int dataM,66(ere data is variable
)ypes of Variable =$ere are t$ree tpes of variables in java •
local variable
•
instance variable
•
static variable
@ocal Kariable
# variable t$at is declared inside t$e met$od is called local variable. Instance Kariable # variable t$at is declared inside t$e class but outside t$e met$od is called instance variable . It is not declared as static. Static variable # variable t$at is declared as static is called static variable. It cannot be local.
?e 8ill $ave detailed learnin) of t$ese variables in net c$apters. <ample to understand t$e tpes of variables 1. class # 2. int dataM,66instance variable 3. static int mM1,,66static variable 4. void met$od5 . int nM*,66local variable ". &. 66end of class
#ata )ypes in %a&a In java/ t$ere are t8o tpes of data tpes •
primitive data tpes
•
non-primitive data tpes
#ata )ype
#efault Value
#efault si3e
boolean
false
1 bit
c$ar
>Lu,,,,>
2 bte
bte
,
1 bte
s$ort
,
2 bte
int
,
4 bte
lon)
,@
' bte
Noat
,.,f
4 bte
double
,.,d
' bte
5!y c!ar uses 6 byte in ja&a and 7!at is 8u9999 4 #ecause 'ava uses unicode syste! rather than A+C00 code syste!. Iu is the lo"est rane o& unicode syste!.To et detail a#out Knicode see #elo".
Java -rea' Statement
The Java break is used to #rea) loop or s"itch state!ent. 0t #rea)s the current &lo" o& the prora! at speci&ied condition. 0n case o& inner loop, it #rea)s only inner loop. Syntax4
1. 'u!p-state!ent7 2. #rea)7
Java -rea' Statement 5ith 6oop Example4
1. pu#lic class rea)a!ple 2. pu#lic static void !ain+trin ars/ 3.
&orint iL17iML17iNN/
4.
i&iLL9/
9.
#rea)7
=.
8
>.
+yste!.out.printlni/7
. D. 8
8
1. 8 Eutput* 1 2 3 4
Java 7ontinue Statement The Java continue statement is used to continue loop. 0t continues the current &lo" o& the prora! and s)ips the re!ainin code at speci&ied condition. 0n case o& inner loop, it continues only inner loop. Syntax4
1. 'u!p-state!ent7 2. continue7
Java 7ontinue Statement Example Example4
1. pu#lic class Continuea!ple 2. pu#lic static void !ain+trin ars/ 3.
&orint iL17iML17iNN/
4.
i&iLL9/
9. =.
8
>.
+yste!.out.printlni/7
. D. 8 1. 8 Eutput* 1
continue7
8
2 3 4 6 7 8 9 10
Java OOPs oncepts 1. Object Oriented Pro)rammin) 2. #dvanta)e of OOPs over Procedure-oriented pro)rammin) lan)ua)e 3. +i:erence bet8een Objcet-oriented and Objcet-based pro)rammin) lan)ua)e.
0n this pae, "e "ill learn a#out #asics o& EEPs. E#'ect Eriented Prora!!in is a paradi! that provides !any concepts such as inheritance, data !inding, polymorphism etc. Simula is considered as the &irst o#'ect-oriented prora!!in lanuae. The prora!!in paradi! "here everythin is represented as an o#'ect, is )no"n as truly o#'ect-oriented prora!!in lanuae. Smalltal' is considered as the &irst truly o#'ect-oriented prora!!in lanuae. OOPs Object Oriented Pro)rammin) Sstem5
*!ect !eans a real "ord entity such as pen, chair, ta#le etc. *!ect+*riented Programming is a !ethodoloy or paradi! to
desin a prora! usin classes and o#'ects. 0t si!pli&ies the so&t"are develop!ent and !aintenance #y providin so!e concepts* •
Object
•
lass
•
In$eritance
•
Polmorp$ism
•
#bstraction
•
Object
Any entity that has state and #ehavior is )no"n as an o#'ect. or ea!ple* chair, pen, ta#le, )ey#oard, #i)e etc. 0t can #e physical and loical. lass
7ollection of o!ects is called class. 0t is a loical entity. In$eritance
When one o!ect ac.uires all the properties and !ehaviours of parent o!ect i.e. )no"n as inheritance. 0t provides code reusa#ility. 0t is used to achieve runti!e poly!orphis!.
Polmorp$ism
When one tas' is performed !y different 5ays i.e. )no"n as poly!orphis!. or ea!ple* to convense the custo!er di&&erently, to dra" so!ethin e.. shape or rectanle etc. 0n 'ava, "e use !ethod overloadin and !ethod overridin to achieve poly!orphis!.
Another ea!ple can #e to spea) so!ethin e.. cat spea)s !ea", do #ar)s "oo& etc. #bstraction
%iding internal details and sho5ing functionality is )no"n as a#straction. or ea!ple* phone call, "e don%t )no" the internal processin.
0n 'ava, "e use a#stract class and inter&ace to achieve a#straction.
-inding 3or 5rapping) code and data together into a single unit is 'no5n as encapsulation. or ea!ple* capsule, it is "rapped "ith di&&erent !edicines.
A 'ava class is the ea!ple o& encapsulation. Java #ean is the &ully encapsulated class #ecause all the data !e!#ers are private here. d&antage of OOPs o&er Procedure-oriented programming language 15OOPs maAes development and maintenance easier 8$ere as in Procedureoriented pro)rammin) lan)ua)e it is not eas to mana)e if code )ro8s as project si9e )ro8s. 25OOPs provides data $idin) 8$ereas in Procedure-oriented pr)rammin) lan)ua)e a )lobal data can be accessed from an8$ere. 35OOPs provides abilit to simulate real-8orld event muc$ more e:ectivel. ?e can provide t$e solution of real 8ord problem if 8e are usin) t$e Object-Oriented Pro)rammin) lan)ua)e.
5!at is di:erence bet7een object-oriented programming language and object-based programming language4 Object based pro)rammin) lan)ua)e follo8s all t$e features of OOPs ecept In$eritance. JavaScript and K;Script are eamples of object based pro)rammin) lan)ua)es. et$od Overloadin) in Java 1. +i:erent 8as to overload t$e met$od 2. ; c$an)in) t$e no. of ar)uments 3. ; c$an)in) t$e datatpe 4. ?$ met$od overloadin) is not possible b c$an)in) t$e return tpe . an 8e overload t$e main met$od ". met$od overloadin) 8it$ =pe Promotion
0& a class have !ultiple !ethods #y sa!e na!e #ut di&&erent para!eters, it is )no"n as $ethod *verloading. 0& "e have to per&or! only one operation, havin sa!e na!e o& the !ethods increases the reada#ility o& the prora!. +uppose you have to per&or! addition o& the iven nu!#ers #ut there can #e any nu!#er o& aru!ents, i& you "rite the !ethod such as aint,int/ &or t"o para!eters, and #int,int,int/ &or three para!eters then it !ay #e di&&icult &or you as "ell as other prora!!ers to understand the #ehaviour o& the !ethod #ecause its na!e di&&ers. +o, "e per&or! !ethod overloadin to &iure out the prora! (uic)ly.
#dvanta)e of met$od overloadin)
1. ; c$an)in) number of ar)uments
2. ; c$an)in) t$e data tpe
Can 7e o&erload main/0 met!od4 Oes, #y !ethod overloadin. Oou can have any nu!#er o& !ain !ethods in a class #y !ethod overloadin. $et%s see the si!ple ea!ple* 1. class Overloadin)1 2.
public static void mainint a5
3.
Sstem.out.printlna5
4.
. ".
public static void mainStrin) ar)sGH5
&.
Sstem.out.printlnCmain5 met$od invoAedC5
'.
main1,5
*.
1,. =est it %o8 Output:main() method invoked 10
onstructor in Java 1. =pes of constructors 1. +efault onstructor 2. Parameteri9ed onstructor 2. onstructor Overloadin) 3. +oes constructor return an value 4. opin) t$e values of one object into anot$er . +oes constructor perform ot$er tasA instead initiali9ation
7onstructor in ava is a special type of method that is used to initialiFe the o#'ect.
Java constructor is invoked at the time of object creation. 0t constructs the values i.e. provides data &or the o#'ect that is "hy it is )no"n as constructor.
Rules for creating ja&a constructor There are #asically t"o rules de&ined &or the constructor. 1. onstructor name must be same as its class name 2. onstructor must $ave no eplicit return tpe
)ypes of ja&a constructors There are t"o types o& constructors* 1. +efault constructor no-ar) constructor5 2. Parameteri9ed constructor
Java static 'ey5ord 1. +tatic varia#le 2. Prora! o& counter "ithout static varia#le 3. Prora! o& counter "ith static varia#le 4. +tatic !ethod 9. estrictions &or static !ethod =. Why !ain !ethod is static ? >. +tatic #loc) . Can "e eecute a prora! "ithout !ain !ethod ? The static 'ey5ord in 'ava is used &or !e!ory !anae!ent !ainly. We can apply 'ava static )ey"ord "ith varia#les, !ethods, #loc)s and nested class. The static )ey"ord #elons to the class than instance o& the class. The static can #e* 1. varia#le also )no"n as class varia#le/ 2. !ethod also )no"n as class !ethod/ 3. #loc) 4. nested class
this 'ey5ord in ava
1. this )ey"ord 2. Ksae o& this )ey"ord 1. to re&er the current class instance varia#le 2. to invo)e the current class constructor 3. to invo)e the current class !ethod 4. to pass as an aru!ent in the !ethod call 9. to pass as an aru!ent in the constructor call =. to return the current class instance 3. Provin this )ey"ord There can #e a lot o& usae o& ava this 'ey5ord. 0n 'ava, this is a reference varia!le that re&ers to the current o#'ect.
8sage of ava this 'ey5ord 6ere is iven the = usae o& 'ava this )ey"ord. 1. this )ey"ord can #e used to re&er current class instance varia#le. 2. this/ can #e used to invo)e current class constructor. 3. this )ey"ord can #e used to invo)e current class !ethod i!plicitly/ 4. this can #e passed as an aru!ent in the !ethod call. 9. this can #e passed as aru!ent in the constructor call. =. this )ey"ord can also #e used to return the current class instance. In$eritance in Java 1. In$eritance 2. =pes of In$eritance 3. ?$ multiple in$eritance is not possible in java in case of class
9nheritance in ava is a !echanis! in "hich one o#'ect ac(uires all the properties and #ehaviors o& parent o#'ect.
The idea #ehind inheritance in 'ava is that you can create ne" classes that are #uilt upon eistin classes. When you inherit &ro! an eistin class, you can reuse !ethods and &ields o& parent class, and you can add ne" !ethods and &ields also. 0nheritance represents the 9S+A relationship, also )no"n as parent-child relationship.
Aggregation in Java 0& a class have an entity re&erence, it is )no"n as Areation. Areation represents 6A+A relationship. Consider a situation, !ployee o#'ect contains !any in&or!ations such as id, na!e, e!ail0d etc. 0t contains one !ore o#'ect na!ed address, "hich contains its o"n in&or!ations such as city, state, country, Fipcode etc. as iven #elo".
super 'ey5ord in ava The super )ey"ord in 'ava is a re&erence varia#le that is used to re&er i!!ediate parent class o#'ect. Whenever you create the instance o& su#class, an instance o& parent class is created i!plicitly i.e. re&erred #y super re&erence varia#le.
Polymorphism in Java Polymorphism in ava is a concept #y "hich "e can per&or! a single action by different ways. Poly!orphis! is derived &ro! 2 ree) "ords* poly and !orphs. The "ord 5poly5 !eans !any and 5!orphs5 !eans &or!s. +o poly!orphis! !eans !any &or!s.
There are t"o types o& poly!orphis! in 'ava* co!pile ti!e poly!orphis! and runti!e poly!orphis!. We can per&or! poly!orphis! in 'ava #y !ethod overloadin and !ethod overridin. 0& you overload static !ethod in 'ava, it is the ea!ple o& co!pile ti!e poly!orphis!. 6ere, "e "ill &ocus on runti!e poly!orphis! in 'ava.
:untime Polymorphism in Java :untime polymorphism or ;ynamic $ethod ;ispatch is a process in "hich a call to an overridden !ethod is resolved at runti!e rather than co!pile-ti!e.
0n this process, an overridden !ethod is called throuh the re&erence varia#le o& a superclass. The deter!ination o& the !ethod to #e called is #ased on the o#'ect #ein re&erred to #y the re&erence varia#le. $et%s &irst understand the upcastin #e&ore unti!e Poly!orphis!.
0n this ea!ple, "e are creatin t"o classes i)e and +plendar. +plendar class etends i)e class and overrides its run/ !ethod. We are callin the run !ethod #y the re&erence varia#le o& Parent class. +ince it re&ers to the su#class o#'ect and su#class !ethod overrides the Parent class !ethod, su#class !ethod is invo)ed at runti!e. +ince !ethod invocation is deter!ined #y the JB< not co!piler, it is )no"n as runti!e poly!orphis!. 1. class i)e 2.
void run/+yste!.out.println5runnin5/78
3. 8 4. class +plender etends i)e 9.
void run/+yste!.out.println5runnin sa&ely "ith =)!5/78
=. >.
pu#lic static void !ain+trin ars/
.
i)e # L ne" +plender/7HHupcastin
D.
#.run/7
1. 8 11. 8 Java instanceof 1. java instanceof 2. <ample of instanceof operator 3. #pplin) t$e instanceof operator 8it$ a variable t$e $ave null value 4. +o8ncastin) 8it$ instanceof operator . +o8ncastin) 8it$out instanceof operator
The ava instanceof operator is used to test "hether the o#'ect is an instance o& the speci&ied type class or su#class or inter&ace/. The instanceo& in 'ava is also )no"n as type comparison operator #ecause it co!pares the instance "ith type. 0t returns either true or &alse. 0& "e apply the instanceo& operator "ith any varia#le that has null value, it returns &alse.
Simple e(ample of ja&a instanceof $et%s see the si!ple ea!ple o& instance operator "here it tests the current class. 1. class Simple1 2.
public static void mainStrin) ar)sGH5
3. Simple1 sMne8 Simple15 4.
Sstem.out.printlns instanceof Simple1566true
.
". #bstract class in Java
A class that is declared "ith a#stract )ey"ord, is )no"n as a#stract class in 'ava. 0t can have a#stract and non-a#stract !ethods !ethod "ith #ody/. e&ore learnin 'ava a#stract class, let%s understand the a#straction in 'ava &irst.
bstraction in %a&a A!straction is a process o& hidin the i!ple!entation details and sho"in only &unctionality to the user.
Another "ay, it sho"s only i!portant thins to the user and hides the internal details &or ea!ple sendin s!s, you 'ust type the tet and send the !essae. Oou don%t )no" the internal processin a#out the !essae delivery. A#straction lets you &ocus on "hat the o#'ect does instead o& ho" it does it. Interface in Java 1. Interface 2. <ample of Interface 3. ultiple in$eritance b Interface 4. ?$ multiple in$eritance is supported in Interface 8$ile it is not supported in case of class. . arAer Interface ". %ested Interface
An interface in ava is a #lueprint o& a class. 0t has static constants and a#stract !ethods only. The inter&ace in 'ava is a mechanism to achieve fully a!straction. There can #e only a#stract !ethods in the 'ava inter&ace not !ethod #ody. 0t is used to achieve &ully a#straction and !ultiple inheritance in Java. Java 0nter&ace also represents 9S+A relationship . 0t cannot #e instantiated 'ust li)e a#stract class. ;0 pri&ate access modier =$e private access modiBer is accessible onl 8it$in class. 60 default access modier If ou don>t use an modiBer/ it is treated as default bdefault. =$e default modiBer is accessible onl 8it$in pacAa)e. <0 protected access modier The protected access modifier is accessi#le "ithin pac)ae and outside the pac)ae #ut throuh inheritance only.
The protected access !odi&ier can #e applied on the data !e!#er, !ethod and constructor. 0t can%t #e applied on the class. =0 public access modier =$e public access modier is accessible ever8$ere. It $as t$e 8idest scope amon) all ot$er modiBers.
*!ect class in Java The *!ect class is the parent class o& all the classes in 'ava #yde&ault. 0n other "ords, it is the top!ost class o& 'ava. The E#'ect class is #ene&icial i& you "ant to re&er any o#'ect "hose type you don%t )no". :otice that parent class re&erence varia#le can re&er the child class o#'ect, )no" as upcastin. $et%s ta)e an ea!ple, there is etE#'ect/ !ethod that returns an o#'ect #ut it can #e o& any type li)e !ployee,+tudent etc, "e can use E#'ect class re&erence to re&er that o#'ect. or ea!ple*
Java Array
:or!ally, array is a collection o& si!ilar type o& ele!ents that have contiuous !e!ory location. Java array is an o#'ect the contains ele!ents o& si!ilar data type. 0t is a data structure "here "e store si!ilar ele!ents. We can store only &ied set o& ele!ents in a 'ava array.
Array in 'ava is inde #ased, &irst ele!ent o& the array is stored at inde 1. class Testarray 2. pu#lic static void !ain+trin ars/ 3. 4. int aLne" int97HHdeclaration and instantiation 9. aL17HHinitialiFation =. a1L27 >. a2L>7 . a3L47 D. a4L97 1. 11. HHprintin array 12. &orint iL7iMa.lenth7iNN/HHlenth is the property o& array 13. +yste!.out.printlnai/7 14. 19. 88
Wrapper class in ava provides the !echanis! to convert primitive into object and object into primitive.
+ince J2+ 9., auto!oxing and un!oxing &eature converts pri!itive into o#'ect and o#'ect into pri!itive auto!atically. The auto!atic conversion o& pri!itive into o#'ect is )no"n and auto#oin and vice-versa un#oin. onvert usin) Inte)er.toStrin)int5 convert strin) to int
Inte)er.parseIntStrin)5 . covert strin) to int
Java Strin) 1. Java Strin) (andlin) 2. (o8 to create strin) object 1. Strin) literal 2. ne8 Ae8ord
Java String provides a lot o& concepts that can #e per&or!ed on a strin such as co!pare, concat, e(uals, split, lenth, replace, co!pareTo, intern, su#strin etc.
0n 'ava, strin is #asically an o#'ect that represents se(uence o& char values. An array o& characters "or)s sa!e as 'ava strin. or ea!ple* 1. c$arGH c$M>j>/>a>/>v>/>a>/>t>/>p>/>o>/>i>/>n>/>t> 2. Strin) sMne8 Strin)c$5
0n 'ava, string o!ects are immuta!le . 0!!uta#le si!ply !eans un!odi&ia#le or unchanea#le. Ence strin o#'ect is created its data or state can%t #e chaned #ut a ne" strin o#'ect is created. $et%s try to understand the i!!uta#ility concept #y the ea!ple iven #elo"* Java Strin) class met$ods
The 'ava.lan.+trin class provides a lot o& !ethods to "or) on strin. y the help o& these !ethods, "e can per&or! operations on strin such as tri!!in, concatenatin, convertin, co!parin, replacin strins etc. Java +trin is a po"er&ul concept #ecause everythin is treated as a strin i& you su#!it any &or! in "indo" #ased, "e# #ased or !o#ile application. $et%s see the i!portant !ethods o& +trin class.
%a&a String to+pperCase/0 and to>o7erCase/0 met!od The 'ava strin toKpperCase/ !ethod converts this strin into uppercase letter and strin to$o"erCase/ !ethod into lo"ercase letter. 1. Strin) sMCSac$inC 2. Sstem.out.printlns.topperase5566S#(I% 3. Sstem.out.printlns.to@o8erase5566sac$in 4. Sstem.out.printlns566Sac$inno c$an)e in ori)inal5 =est it %o8 S!H"# $a%hin Sa%hin
%a&a String trim/0 met!od The strin tri!/ !ethod eli!inates "hite spaces #e&ore and a&ter strin. 1. Strin) sMC Sac$in C 2. Sstem.out.printlns566 Sac$in 3. Sstem.out.printlns.trim5566Sac$in =est it %o8 Sa%hin Sa%hin
%a&a String starts5it!/0 and ends5it!/0 met!od 1. Strin) sMCSac$inC 2.
Sstem.out.printlns.starts?it$CSaC5566true
3.
Sstem.out.printlns.ends?it$CnC5566true
=est it %o8 t&ue t&ue
%a&a String c!art/0 met!od The strin charAt/ !ethod returns a character at speci&ied inde. 1. Strin) sMCSac$inC 2. Sstem.out.printlns.c$ar#t,5566S 3. Sstem.out.printlns.c$ar#t35566$ =est it %o8
S h
%a&a String lengt!/0 met!od The strin lenth/ !ethod returns lenth o& the strin. 1. Strin) sMCSac$inC 2. Sstem.out.printlns.len)t$5566" =est it %o8 6
%a&a String intern/0 met!od A pool o& strins, initially e!pty, is !aintained privately #y the class +trin.
When the intern !ethod is invo)ed, i& the pool already contains a strin e(ual to this +trin o#'ect as deter!ined #y the e(ualsE#'ect/ !ethod, then the strin &ro! the pool is returned. Ether"ise, this +trin o#'ect is added to the pool and a re&erence to this +trin o#'ect is returned. 1. Strin) sMne8 Strin)CSac$inC5 2. Strin) s2Ms.intern5 3. Sstem.out.printlns2566Sac$in =est it %o8 Sa%hin
%a&a String &alueOf/0 met!od The strin valueE&/ !ethod coverts iven type such as int, lon, &loat, dou#le, #oolean, char and char array into strin. 1. int aM1, 2. Strin) sMStrin).valueOfa5 3. Sstem.out.printlns1,5
Eutput* 1010
%a&a String replace/0 met!od The strin replace/ !ethod replaces all occurrence o& &irst se(uence o& character "ith second se(uence o& character. 1. Strin) s1MCJava is a pro)rammin) lan)ua)e. Java is a platform. Java is an I sland.C