You are on page 1of 29

8/26/2015

Tutorials

Contact us

IntroductiontoJavaprogrammingTutorial
Services

Products

Books

Company
Search

Donate

IntroductiontoJavaprogrammingTutorial
LarsVogel
Version2.6
Copyright2008,2009,2010,2011,2012,2013,2014,2015vogellaGmbH
02.04.2015
IntroductiontoJavaprogramming
ThistutorialexplainstheinstallationandusageoftheJavaprogramminglanguage.Italsocontains
examplesforstandardprogrammingtasks.

TableofContents
1.IntroductiontoJava
1.1.History
1.2.Javaandopensourcesoftware
1.3.Javavirtualmachine
1.4.JavaRuntimeEnvironmentvs.JavaDevelopmentKit
1.5.CharacteristicsofJava
1.6.DevelopmentProcesswithJava
1.7.Garbagecollector
1.8.Classpath
2.InstallationofJava
2.1.Checkinstallation
2.2.InstallJavaonUbuntu
2.3.InstallJavaonMSWindows
2.4.Installationproblemsandotheroperatingsystems
2.5.Validateinstallation
2.6.Howcanyoutellyouareusinga32bitor64bitversionofJava?
3.Exercise:Write,compileandrunaJavaprogram
3.1.Writesourcecode
3.2.CompileandrunyourJavaprogram
3.3.Usingtheclasspath
4.Javalanguagestructure
4.1.Basics:Package,ClassandObject
4.2.Package
4.3.Class
4.4.Object
4.5.Inheritance
4.6.Objectassuperclass
5.Javainterfaces
5.1.WhatisaninterfaceinJava?
5.2.Abstract,defaultandstaticmethodsinInterfaces
5.3.ImplementingInterfaces
5.4.Evolvinginterfaces
5.5.Multipleinheritanceofmethods
5.6.Functionalinterfaces
6.Javabasicterms
6.1.Overridemethodsandthe@Overrideannotation
7.ThetypesystemofJava
7.1.Primitivesandreferences
7.2.Primitives
7.3.Referencetypes
7.4.Autoboxingandwrappertypes
8.Variablesandmethods
8.1.Variable

http://www.vogella.com/tutorials/JavaIntroduction/article.html

1/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
8.2.Instancevariable
8.3.Localvariable
8.4.Methods
8.5.Mainmethod
8.6.Constructor
9.Modifiers
9.1.Accessmodifiers
9.2.Othermodifiers
10.Importstatements
10.1.Usageofimportstatements
10.2.Staticimports
11.MoreJavalanguageconstructs
11.1.Classmethodsandclassvariables
11.2.Abstractclassandmethods
12.CheatSheets
12.1.Workingwithclasses
12.2.Workingwithlocalvariable
13.IntegratedDevelopmentEnvironment
14.ExercisesCreatingJavaobjectsandmethods
14.1.CreateaPersonclassandinstantiateit
14.2.Useconstructor
14.3.Definegetterandsettermethods
14.4.CreateanAddressobject
15.SolutionCreatingJavaobjectsandmethods
15.1.CreateaPersonclassandinstantiateit
15.2.Useconstructor
15.3.Definegetterandsettermethods
15.4.SolutionCreateanAddressobject
16.Javastatements
16.1.ifthenandifthenelse
16.2.Switch
16.3.BooleanOperations
17.LoopsinJava
17.1.Theforloop
17.2.Thewhileloop
17.3.Thedowhileloop
18.Arrays
18.1.ArraysinJava
18.2.EnhancedforloopforArraysandCollections
19.Strings
19.1.StringsinJava
19.2.StringpoolinJava
19.3.CompareStringsinJava
19.4.WorkingwithStrings
20.Lambdas
20.1.Whatarelambdas?
20.2.Differencebetweenalambdaexpressionandaclosure
20.3.Purposeoflambdaexpressions
20.4.Usingmethodreferences
21.Streams
21.1.WhatareStreamsinJava8?
21.2.IntStream
21.3.Reductionoperationswithstreamsandlambdas
22.TypeConversion
22.1.ConversiontoString
22.2.ConversionfromStringtoNumber
22.3.Doubletoint
22.4.SQLDateconversions
23.Scheduletasks
24.Aboutthiswebsite
25.LinksandLiterature

http://www.vogella.com/tutorials/JavaIntroduction/article.html

2/29

8/26/2015

IntroductiontoJavaprogrammingTutorial

Days Inn Hotel New York City-Broadway


$109.65 Covered By Expedia's Best Price Guarantee
Expedia.com

1.IntroductiontoJava
1.1.History
JavaisaprogramminglanguagecreatedbyJamesGoslingfromSunMicrosystems(Sun)in1991.
ThefirstpubliclyavailableversionofJava(Java1.0)wasreleasedin1995.
SunMicrosystemswasacquiredbytheOracleCorporationin2010.Oraclehasnowthe
steermanshipforJava.
OvertimenewenhancedversionsofJavahavebeenreleased.ThecurrentversionofJavais
Java1.7whichisalsoknownasJava7.
FromtheJavaprogramminglanguagetheJavaplatformevolved.TheJavaplatformallows
softwaredeveloperstowriteprogramcodeinotherlanguagesthantheJavaprogramming
languagewhichstillrunsontheJavavirtualmachine.TheJavaplatformisusuallyassociatedwith
theJavavirtualmachineandtheJavacorelibraries.

1.2.Javaandopensourcesoftware
In2006SunstartedtomakeJavaavailableundertheGNUGeneralPublicLicense(GPL).Oracle
continuesthisprojectcalledOpenJDK.

1.3.Javavirtualmachine
TheJavavirtualmachine(JVM)isasoftwareimplementationofacomputerthatexecutes
programslikearealmachine.
TheJavavirtualmachineiswrittenspecificallyforaspecificoperatingsystem,e.g.,forLinuxa
specialimplementationisrequiredaswellasforWindows.

JavaprogramsarecompiledbytheJavacompilerintobytecode.TheJavavirtualmachine
interpretsthisbytecodeandexecutestheJavaprogram.

1.4.JavaRuntimeEnvironmentvs.JavaDevelopmentKit
AJavadistributiontypicallycomesintwoflavors,theJavaRuntimeEnvironment(JRE)andthe
JavaDevelopmentKit(JDK).
TheJavaruntimeenvironment(JRE)consistsoftheJVMandtheJavaclasslibraries.Those
containthenecessaryfunctionalitytostartJavaprograms.
TheJDKadditionallycontainsthedevelopmenttoolsnecessarytocreateJavaprograms.TheJDK
thereforeconsistsofaJavacompiler,theJavavirtualmachineandtheJavaclasslibraries.

1.5.CharacteristicsofJava
ThetargetofJavaistowriteaprogramonceandthenrunthisprogramonmultipleoperating
systems.
Javahasthefollowingproperties:

http://www.vogella.com/tutorials/JavaIntroduction/article.html

3/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
Platformindependent:JavaprogramsusetheJavavirtualmachineasabstractionanddo
notaccesstheoperatingsystemdirectly.ThismakesJavaprogramshighlyportable.AJava
program(whichisstandardcompliantandfollowscertainrules)canrununmodifiedonall
supportedplatforms,e.g.,WindowsorLinux.
Objectorientatedprogramminglanguage:Excepttheprimitivedatatypes,allelementsin
Javaareobjects.
Stronglytypedprogramminglanguage:Javaisstronglytyped,e.g.,thetypesoftheused
variablesmustbepredefinedandconversiontootherobjectsisrelativelystrict,e.g.,must
bedoneinmostcasesbytheprogrammer.
Interpretedandcompiledlanguage:Javasourcecodeistransferredintothebytecode
formatwhichdoesnotdependonthetargetplatform.Thesebytecodeinstructionswillbe
interpretedbytheJavaVirtualmachine(JVM).TheJVMcontainsasocalledHotspot
Compilerwhichtranslatesperformancecriticalbytecodeinstructionsintonativecode
instructions.
Automaticmemorymanagement:Javamanagesthememoryallocationanddeallocation
forcreatingnewobjects.Theprogramdoesnothavedirectaccesstothememory.Theso
calledgarbagecollectorautomaticallydeletesobjectstowhichnoactivepointerexists.
TheJavasyntaxissimilartoC++.Javaiscasesensitive,e.g.,variablescalled myValue and
myvalue aretreatedasdifferentvariables.

1.6.DevelopmentProcesswithJava
Javasourcefilesarewrittenasplaintextdocuments.TheprogrammertypicallywritesJavasource
codeinanIntegratedDevelopmentEnvironment(IDE)forprogramming.AnIDEsupportsthe
programmerinthetaskofwritingcode,e.g.,itprovidesautoformatingofthesourcecode,
highlightingoftheimportantkeywords,etc.
Atsomepointtheprogrammer(ortheIDE)callstheJavacompiler(javac).TheJavacompiler
createsthebytecodeinstructions.Theseinstructionsarestoredin.classfilesandcanbe
executedbytheJavaVirtualMachine.

1.7.Garbagecollector
TheJVMautomaticallyrecollectsthememorywhichisnotreferredtobyotherobjects.TheJava
garbagecollectorchecksallobjectreferencesandfindstheobjectswhichcanbeautomatically
released.
Whilethegarbagecollectorrelievestheprogrammerfromtheneedtoexplicitlymanagememory,
theprogrammerstillneedtoensurethathedoesnotkeepunneededobjectreferences,otherwise
thegarbagecollectorcannotreleasetheassociatedmemory.Keepingunneededobject
referencesaretypicallycalledmemoryleaks.

1.8.Classpath
TheclasspathdefineswheretheJavacompilerandJavaruntimelookfor.classfilestoload.
TheseinstructionscanbeusedintheJavaprogram.
Forexample,ifyouwanttouseanexternalJavalibraryyouhavetoaddthislibrarytoyour
classpathtouseitinyourprogram.

2.InstallationofJava
2.1.Checkinstallation
TorunJavaprogramsonyourcomputeryoumustatleasthavetheJavaruntimeenvironment
(JRE)installed.Thismightalreadybethecaseonyourmachine.YoucantestistheJREis
installedandinyourcurrentpathbyopeningaconsole(ifyouareusingWindows:Win+R,enter
cmdandpressEnter)andbytypinginthefollowingcommand:
javaversion

IftheJREisinstalledandwithinyourpath,thiscommandsprintinformationaboutyourJava
installation.InthiscaseyoucanskiptheJavainstallationdescription.Youmaywanttonotedown
ifyouhavea32bitor64bitversionofJava,seeSection2.6,Howcanyoutellyouareusing
a32bitor64bitversionofJava?.
Ifthecommandlinereturnstheinformationthattheprogramcouldnotbefound,youhaveto
installJava.

2.2.InstallJavaonUbuntu
OnUbuntuyoucaninstallJava7viathefollowingcommandonthecommandline.

http://www.vogella.com/tutorials/JavaIntroduction/article.html

4/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
sudoaptgetinstallopenjdk7jdk

2.3.InstallJavaonMSWindows
ForMicrosoftsWindows,OracleprovidesanativeinstallerwhichcanbefoundontheOracle
website.ThecentralwebsiteforinstallingJavaislocatedunderthefollowingURLandalso
containsinstructionshowtoinstallJavaforotherplatforms.
java.com

2.4.Installationproblemsandotheroperatingsystems
IfyouhaveproblemsinstallingJavaonyoursystem,searchviaGoogleforHowtoinstallJDKon
YOUR_OS.Thisshouldresultinhelpfullinks.ReplaceYOUR_OSwithyouroperatingsystem,e.g.,
Windows,Ubuntu,MacOSX,etc.

2.5.Validateinstallation
Switchagaintothecommandlineandrunthefollowingcommand.
javaversion

Theoutputshouldbesimilartothefollowingoutput.
javaversion"1.7.0_25"
OpenJDKRuntimeEnvironment(IcedTea2.3.10)(7u252.3.101ubuntu0.13.04.2)
OpenJDK64BitServerVM(build23.7b01,mixedmode)

2.6.Howcanyoutellyouareusinga32bitor64bitversionofJava?
Youcanruna32bitora64bitversionofJavaona64bitsystem.Ifyouuse javaversion and
theoutputcontainsthe"64Bit"stringyouareusingthe64bitversionofJavaotherwiseyourare
usingthe32bitversion.Thefollowingistheoutputofa64bitversion.
javaversion"1.7.0_25"
OpenJDKRuntimeEnvironment(IcedTea2.3.10)(7u252.3.101ubuntu0.13.04.2)
OpenJDK64BitServerVM(build23.7b01,mixedmode)

3.Exercise:Write,compileandrunaJavaprogram
3.1.Writesourcecode
ThefollowingJavaprogramisdevelopedunderLinuxusingatexteditorandthecommandline.
Theprocessonotheroperatingsystemshouldbesimilar,butisnotcoveredinthisdescription.
SelectorcreateanewdirectorywhichwillbeusedforyourJavadevelopment.Inthisdescription
thepath\home\vogella\javastarterisused.OnMicrosoftWindowsyoumightwanttouse
c:\temp\javastarter.Thispathiscalledjavadirinthefollowingdescription.
Openatexteditorwhichsupportsplaintext,e.g.,geditunderLinuxorNotepadunderWindows
andwritethefollowingsourcecode.
//asmallJavaprogram
publicclassHelloWorld{
publicstaticvoidmain(String[]args){
System.out.println("HelloWorld");
}
}

Warning: DonotusearicheditorlikeMicrosoftWordorLibreOfficeforwriting
Javacode.Ifindoubt,googlefor"Plaintexteditorfor[your_OS]".

http://www.vogella.com/tutorials/JavaIntroduction/article.html

5/29

8/26/2015

IntroductiontoJavaprogrammingTutorial

SavethesourcecodeinyourjavadirdirectorywiththeHelloWorld.javafilename.Thenameofa
Javasourcefilemustalwaysequaltheclassname(withinthesourcecode)andendwiththe
.javaextension.InthisexamplethefilenamemustbeHelloWorld.java,becausetheclassis
called HelloWorld .

3.2.CompileandrunyourJavaprogram
Openashellforcommandlineaccess.

Tip: Ifyoudon'tknowhowtodothis,googlefor"Howtoopenashellunder
[your_OS]".
Switchtothejavadirdirectorywiththecommand cdjavadir ,forexample,intheaboveexample
viathe cd\home\vogella\javastarter command.Usethe ls command( dir underMicrosoft
Windows)toverifythatthesourcefileisinthedirectory.
CompileyourJavasourcefileintoaclassfilewiththefollowingcommand.
javacHelloWorld.java

Afterwardslistagainthecontentofthedirectorywiththe ls or dir command.Thedirectory


containsnowafileHelloWorld.class.Ifyouseethisfile,youhavesuccessfullycompiledyour
firstJavasourcecodeintobytecode.

Tip: Bydefault,thecompilerputseachclassfileinthesamedirectoryasits
sourcefile.Youcanspecifyaseparatedestinationdirectorywiththedcompiler
flag.
YoucannowstartyourcompiledJavaprogram.Ensurethatyouarestillinthejardirdirectoryand
enterthefollowingcommandtostartyourJavaprogram.
javaHelloWorld

Thesystemshouldwrite"HelloWorld"onthecommandline.

3.3.Usingtheclasspath
Youcanusetheclasspathtoruntheprogramfromanotherplaceinyourdirectory.
Switchtothecommandline,e.g.,underWindowsStartRun cmd .Switchtoanydirectoryyou
want.Type:
javaHelloWorld

Ifyouarenotinthedirectoryinwhichthecompiledclassisstored,thenthesystemwillshowan

http://www.vogella.com/tutorials/JavaIntroduction/article.html

6/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
errormessage:Exceptioninthread"main"java.lang.NoClassDefFoundError:test/TestClass
Tousetheclass,typethefollowingcommand.Replace"mydirectory"withthedirectorywhich
containsthetestdirectory.Youshouldagainseethe"HelloWorld"output.
javaclasspath"mydirectory"HelloWorld

4.Javalanguagestructure
4.1.Basics:Package,ClassandObject
ItisimportanttounderstandthebaseterminologyofJavaintermsofpackages,classesand
objects.Thissectiongivesanoverviewoftheseterms.

4.2.Package
Javagroupsclassesintofunctionalpackages.
Packagesaretypicallyusedtogroupclassesintologicalunits.Forexample,allgraphicalviewsof
anapplicationmightbeplacedinthesamepackagecalled com.vogella.webapplication.views .
Itiscommonpracticetousethereversedomainnameofthecompanyastoplevelpackage.For
example,thecompanymightownthedomain,vogella.comandinthisexampletheJavapackages
ofthiscompanystartswith com.vogella .
Othermainreasonfortheusageofpackagesistoavoidnamecollisionsofclasses.Aname
collisionoccursiftwoprogrammersgivethesamefullyqualifiednametoaclass.Thefullyqualified
nameofaclassinJavaconsistsofthepackagenamefollowedbyadot(.)andtheclassname.
Withoutpackages,aprogrammermaycreateaJavaclasscalled Test .Anotherprogrammermay
createaclasswiththesamename.Withtheusageofpackagesyoucantellthesystemwhich
classtocall.Forexample,ifthefirstprogrammerputsthe Test classintopackage report and
thesecondprogrammerputshisclassintopackage xmlreader youcandistinguishbetween
theseclassesbyusingthefullyqualifiedname,e.g, xmlreader.Test or report.Test .

4.3.Class
Def.:Templatethatdescribesthedataandbehaviorassociatedwithaninstanceofthat
class.

Note: Theclasscanbeseenastheblueprintofanobject.Itdescribeshowan
objectiscreated.
InJavasourcecodeaclassisdefinedbytheclasskeywordandmuststartwithacapitalletter.
Thebodyofaclassissurroundedby{}.
packagetest;
classMyClass{

Thedataassociatedwithaclassisstoredinvariablesthebehaviorassociatedtoaclassorobject
isimplementedwithmethods.
AclassiscontainedinaJavasourcefilewiththesamenameastheclassplusthe.java
extension.

4.4.Object
Def.:Anobjectisaninstanceofaclass.
Theobjectistherealelementwhichhasdataandcanperformactions.Eachobjectiscreated
basedontheclassdefinition.

4.5.Inheritance
Aclasscanbederivedfromanotherclass.Inthiscasethisclassiscalledasubclass.Another
commonphraseisthataclassextendsanotherclass.
Theclassfromwhichthesubclassisderivediscalledasuperclass.
Inheritanceallowsaclasstoinheritthebehavioranddatadefinitionsofanotherclass.
Thefollowingcodesdemonstrateshowaclasscanextendanotherclass.InJavaaclasscanonly
extendamaximumofoneclass.
packagecom.vogella.javaintro.base;

http://www.vogella.com/tutorials/JavaIntroduction/article.html

7/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
classMyBaseClass{
@Override
publicvoidhello(){
System.out.println("HellofromMyBaseClass");
}
}

packagecom.vogella.javaintro.base;
classMyExtensionClassextendsMyBaseClass{
}

4.6.Objectassuperclass
EveryobjectinJavaimplicitlyextendsthe Object class.Theclassdefinesthefollowingmethods
foreveryJavaobject:
equals(o1) allowscheckingifthecurrentobjectisequaltoo1
getClass() returnstheclassoftheobject
hashCode() returnsanidentifierofthecurrentobject
toString() givesastringrepresentationofthecurrentobject

5.Javainterfaces
5.1.WhatisaninterfaceinJava?
Aninterfacesisatypesimilartoaclassandisdefinedviathe interface keyword.Likeaclass
aninterfacedefinesmethods.Classescanimplementtheinterfacesandbythistheymustobey
thecontractdefinedintheinterface,e.g.,theclastprovideimplementationforallabstractmethods
definedintheinterface.

5.2.Abstract,defaultandstaticmethodsinInterfaces
Aninterfacecanhaveabstractmethodsanddefaultmethods.Adefaultmethodisdefinedviathe
default keywordatthebeginningofthemethodsignature.Allothermethodsdefinedinan
interfacesarepublicandabstractexplicitdeclarationofthesemodifiersisoptional.
Interfacescanhaveconstantswhicharealwaysimplicitlypublic,staticandfinal.
Thefollowingcodeshowsanexampleimplementationofaninterface.
packagetesting;
publicinterfaceMyInterface{
//constantdefinition
StringURL="http://www.vogella.com";
//publicabstractmethods
voidtest();
voidwrite(Strings);

//defaultmethod
defaultStringreserveString(Strings){
returnnewStringBuilder(s).reverse().toString();
}
}

Thefollowingclassimplementsthisinterface,itsmustimplementtheabstractmethodandcanuse
thedefaultmethods.

5.3.ImplementingInterfaces
Aclasscanimplementaninterface.Inthiscaseitmustprovideconcreteimplementationsofthe
abstractinterfacemethods.Ifyouimplementamethoddefinedbyaninterface,youcanuse
@Override annotationtoindicatetotheJavacompilerthatyouactuallywanttoimplementa
methoddefinedbythisinterface.Thiswaythecompilercangiveyouanerrorinyoumistypedthe
nameofthemethodorinthenumberofarguments.

http://www.vogella.com/tutorials/JavaIntroduction/article.html

8/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
packagecom.vogella.javaintro.base;
publicclassMyClassImplimplementsMyInterface{
@Override
publicvoidtest(){
}
@Override
publicvoidwrite(Strings){
}

publicstaticvoidmain(String[]args){
MyClassImplimpl=newMyClassImpl();
System.out.println(impl.reserveString("LarsVogel"));
}
}

5.4.Evolvinginterfaces
BeforeJava8evolvinginterfaces,e.g.,addingnewmethodstoaninterface,wasnotpossible
becausesuchachangewouldbreakexistingimplementations.Java8introduceddefaultmethods,
nowyoucanextendaninterfacewithoutbreakingclientsbysimplysupplingadefault
implementationwithit.Addingsuchadefaultmethodisasourceanbinarycompatiblechange.
Aclasscanalwaysoverrideadefaultmethodsosupplyabetterbehavior.

5.5.Multipleinheritanceofmethods
Ifaclassimplementstwointerfacesandiftheseinterfacesprovidethesamedefaultmethod,Java
resolvesthecorrectmethodfortheclassbythefollowingrules:

1.

SuperclasswinsalwaysagainstthesuperinterfaceIfaclasscaninheritamethodfroma
superclassandasuperinterface,theclassinhertsthesuperclassmethod.Thisistruefor
concreteandabstractsuperclassmethods.Thisruleimpliesthatdefaultmethodsarenot
usedifthismethodisalsodeclaredinthesuperclasschain.

2.

SubtypeswinoverSupertypesIfaclasscaninheritamethodfromtwointerfaces,andone
isasubtypeoftheother,theclassinhertsthemethodfromthesubtype

3.

Inallothercasestheclassneedstoimplementthedefaultmethod

Thefollowinglistingdemonstrateslistingnumber3.
publicinterfaceA{
defaultvoidm(){}
}
publicinterfaceB{
defaultvoidm(){}
}
publicclassCimplementsA,B{
@Override
publicvoidm(){}
}

Inyourimplementationyoucanalsocallthesupermethodyouprefer.
publicclassCimplementsA,B{
@Override
publicvoidm(){A.super.m();}
}

5.6.Functionalinterfaces
Allinterfacesthathaveonlyonemethodarecalledfunctionalinterfaces.Functionalinterfaces
havetheadvantagethattheycanbeusedtogetherwithlambdaexpressions.SeeSection20.1,
Whatarelambdas?tolearnmoreaboutlambdas,e.g.,thetypeoflambdasisafunctional
interface.
TheJavacompilerautomaticallyidentifiesfunctionalinterfaces.Theonlyrequirementisthatthey
haveonlyoneabstractmethod.However,ispossibletocapturethedesignintentwitha
@FunctionalInterface annotation.
SeveraldefaultJavainterfacesarefunctionalinterfaces:

http://www.vogella.com/tutorials/JavaIntroduction/article.html

9/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
java.lang.Runnable
java.util.concurrent.Callable
java.io.FileFilter
java.util.Comparator
java.beans.PropertyChangeListener

Javaalsocontainsthe java.util.function packagewhichcontainsfunctionalinterfaceswhich


arefrequentlyusedsuchas:
Predicate<T>abooleanvaluedpropertyofanobject
Consumer<T>anactiontobeperformedonanobject
Function<T,R>afunctiontransformingaTtoaR
Supplier<T>providesaninstanceofT(suchasafactory)
UnaryOperator<T>afunctionfromTtoT
BinaryOperator<T>afunctionfrom(T,T)toT

6.Javabasicterms
6.1.Overridemethodsandthe@Overrideannotation
Ifaclassextendsanotherclass,itinheritsthemethodsfromitssuperclass.Ifitwantstochange
thesemethods,itcanoverridethesemethods.Tooverrideamethod,youusethesamemethod
signatureinthesourcecodeofthesubclass.
ToindicatetothereaderofthesourcecodeandtheJavacompilerthatyouhavetheintentionto
overrideamethod,youcanusethe @Override annotation.
Thefollowingcodedemonstrateshowyoucanoverrideamethodfromasuperclass.
packagecom.vogella.javaintro.base;
classMyBaseClass{
@Override
publicvoidhello(){
System.out.println("HellofromMyBaseClass");
}
}

packagecom.vogella.javaintro.base;
classMyExtensionClass2extendsMyBaseClass{
publicvoidhello(){
System.out.println("HellofromMyExtensionClass2");
}
}

Tip: Itisgoodpracticetoalwaysusethe @Override annotation.Thiswaythe


Javacompilervalidatesifyoudidoverrideallmethodsasintendedandprevents
errors.

7.ThetypesystemofJava
7.1.Primitivesandreferences
Javadistinguishesbetweenprimitivetypes(suchasboolean,short,int,double,float,charand
byte)andreferencetypes(suchasObjectandString).

7.2.Primitives
Primitivetypesvariablesrepresentsthenumber,true/falseorcharacter.Youcannotcallmethods
onvariableswhichhaveaprimitivetypes.
Operatorssuchas*,,+or/areonlysupportedforprimitivetypes.Only+canalsousedforthe
referencetypeStringtoconcatenatestrings.

7.3.Referencetypes
Referencetypesvariablesrepresentsareferencetoanobject,e.g.,avariableisapointertothe

http://www.vogella.com/tutorials/JavaIntroduction/article.html

10/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
realobject.Ifyouchangethevalueofareferencetypevariable,thevariablepointstoadifferent
objectorto null whichrepresentsthenonexistingobjectreference.Changingthevalueofa
referencetypevariabledoesnotchangetheattributesoftheobjectiswaspointingto.Also
changingthecontentsofanobjectdoesnotaffectthevalueofavariablereferringtothatobject.

7.4.Autoboxingandwrappertypes
EveryprimitivetypehasinJavaafittingreferencetype.Thisreferencetypeallowstostorethe
valueoftheprimitivetypeinanobject.Forexampleyouhave java.lang.Integer forint.
Convertingaprimitivevalueintoaninstanceofawrappertypeandviceversaiscalledboxing/
unboxing.Javaperformstheseoperationsautomaticallyofnecessary.Thisallowsyoutousea
primitiveasparameterinamethodwhichexpectsanobjectofthewrappertype.Thisautomatic
boxingandunboxingisknownasautoboxing.

8.Variablesandmethods
8.1.Variable
VariablesallowtheJavaprogramtostorevaluesduringtheruntimeoftheprogram.
Avariablecaneitherbeaprimitivevariableorareferencevariable.Aprimitivevariablecontains
thevaluewhilethereferencevariablecontainsareference(pointer)totheobject.Hence,ifyou
comparetworeferencevariables,youcompareifbothpointtothesameobject.Tocompare
objects,usethe object1.equals(object2) methodcall.

8.2.Instancevariable
Instancevariableisassociatedwithaninstanceoftheclass(alsocalledobject).Accessworksover
theseobjects.
Instancevariablescanhaveanyaccesscontrolandcanbemarked final or transient .
Instancevariablesmarkedasfinalcannotbechangedafteravaluehasbeenassignedtothem.

8.3.Localvariable
Local(stack)variabledeclarationscannothaveaccessmodifiers.
finalistheonlymodifieravailabletolocalvariables.Thismodifierdefinesthatthevariablecannot
bechangedafterthefirstassignment.
Localvariablesdonotgetdefaultvalues,sotheymustbeinitializedbeforeuse.

8.4.Methods
Amethodisablockofcodewithparametersandareturnvalue.Itcanbecalledontheobject.
packagecom.vogella.javaintro.base;
publicclassMyMethodExample{
voidtester(Strings){
System.out.println("HelloWorld");
}
}

Methodscanbedeclaredwithvarargs.Inthiscasethemethoddeclaresaparameterwhich
acceptseverythingfromzerotomanyarguments(syntax:type...name)Amethodcanonlyhave
onevarargsparameterandthismustbethelastparameterinthemethod.
Overwriteofasuperclassmethod:Amethodmustbeoftheexactsamereturnparameterandthe
samearguments.Alsothereturnparametermustbethesame.Overloadmethods:Anoverloaded
methodisamethodwiththesamename,butdifferentarguments.Thereturntypecannotbe
usedtooverloadamethod.

8.5.Mainmethod
ApublicstaticmethodwiththefollowingsignaturecanbeusedtostartaJavaapplication.Sucha
methodistypicallycalled main method.
publicstaticvoidmain(String[]args){
}

8.6.Constructor
Aclasscontainsconstructorsthatareinvokedtocreateobjectsbasedontheclassdefinition.
Constructordeclarationslooklikemethoddeclarationsexceptthattheyusethenameoftheclass
andhavenoreturntype.

http://www.vogella.com/tutorials/JavaIntroduction/article.html

11/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
Aclasscanhaveseveralconstructorswithdifferentparameters.Eachclassmustdefineatleast
oneconstructor.
Inthefollowingexampletheconstructoroftheclassexpectsaparameter.
packagecom.vogella.javaintro.base;
publicclassMyConstructorExample2{
Strings;
publicMyConstructorExample2(Strings){
this.s=s;
}
}

Ifnoexplicitconstructorisdefined,thecompilerimplicitlyaddsaconstructor.Iftheclassissub
classed,thentheconstructorofthesuperclassisalwayscalledimplicitlyinthiscase.
Inthefollowingexamplethedefinitionoftheconstructorwithoutparameters(alsoknownasthe
emptyconstructor)isunnecessary.Ifnotspecified,thecompilerwouldcreateone.
packagecom.vogella.javaintro.base;
publicclassMyConstructorExample{
//unnecessary:wouldbecreatedbythecompilerifleftout
publicMyConstructorExample(){
}
}

Thenamingconventionforcreatingaconstructoristhefollowing:
classname(Parameterp1,...){} .
Everyobjectiscreatedbasedonaconstructor.Thisconstructormethodisthefirststatement
calledbeforeanythingelsecanbedonewiththeobject.

9.Modifiers
9.1.Accessmodifiers
TherearethreeaccessmodifierskeywordsavailableinJava:public,protectedandprivate.
Therearefouraccesslevels:public,protected,defaultandprivate.Theydefinehowthe
correspondingelementisvisibletoothercomponents.
Ifsomethingisdeclaredpublic,e.g.,classesormethodscanbefreelycreatedorcalledbyother
Javaobjects.Ifsomethingisdeclaredprivate,e.g.,amethod,itcanonlybeaccessedwithinthe
classinwhichitisdeclared.
Theaccesslevelsprotectedanddefaultaresimilar.Aprotectedclasscanbeaccessedfromthe
packageandsubclassesoutsidethepackage,whileadefaultclasscangetaccessedonlyviathe
samepackage.
Thefollowingtabledescribesthevisibility:
Table1.AccessLevel
Modifier

Class

Package

Subclass

World

public

protected

no modifier

private

9.2.Othermodifiers
finalmethods:cannotbeoverwritteninasubclass
abstractmethod:nomethodbody
synchronizedmethod:threadsafe,canbefinalandhaveanyaccesscontrol
nativemethods:platformdependentcode,applyonlytomethods

http://www.vogella.com/tutorials/JavaIntroduction/article.html

12/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
strictfp:classormethod

10.Importstatements
10.1.Usageofimportstatements
InJavayouhavetoaccessaclassalwaysviaitsfullqualifiedname,i.e.,thepackagenameand
theclassname.
Youcanadd import statementsforclassesorpackagesintoyourclassfile,whichallowyouto
usetherelatedclassesinyourcodewithoutthepackagequalifier.

10.2.Staticimports
Staticimportisafeaturethatallowsmembers(fieldsandmethods)whicharedefinedinaclass
withthe publicstatic accessmodifiertobeusedinJavacodewithoutspecifyingtheclassin
whichthememberisdefined.
Thefeatureprovidesatypesafemechanismtoincludeconstantsintocodewithouthavingto
referencetheclassthatoriginallydefinedthefield.

11.MoreJavalanguageconstructs
11.1.Classmethodsandclassvariables
Classmethodsandclassvariablesareassociatedwiththeclassandnotaninstanceoftheclass,
i.e.,objects.Torefertotheseelements,youcanusetheclassnameandadot(".")followedbythe
classmethodorclassvariablename.
Classmethodsandclassvariablesaredeclaredwiththe static keyword.Classmethodsare
alsocalledstaticmethodsandclassvariablesarealsocalledstaticvariablesorstaticfields.
Anexamplefortheusageofastaticfieldis println ofthefollowingstatement:
System.out.println("HelloWorld") .Hereby out isastaticfield,anobjectoftype
PrintStream andyoucallthe println() methodonthisobject.

Ifyoudefineastaticvariable,theJavaruntimeenvironmentassociatesoneclassvariablefora
classnomatterhowmanyinstances(objects)exist.Thestaticvariablecanthereforebeseenasa
globalvariable.
Thefollowingcodedemonstratestheusageof static fields.
packagecom.vogella.javaintro.base;
publicclassMyStaticExample{
staticStringPLACEHOLDER="TEST";
staticvoidtest(){
System.out.println("Hello");
}
}

packagecom.vogella.javaintro.base;
publicclassTester{
publicstaticvoidmain(String[]args){
System.out.println(MyStaticExample.PLACEHOLDER);
MyStaticExample.test();
}
}

Ifavariableshouldbedefinedasconstant,youdeclareitwiththe static andthe final


keyword.
Thestaticmethodrunswithoutanyinstanceoftheclass,itcannotdirectlyaccessnonstatic
variablesormethods.

11.2.Abstractclassandmethods
Aclassandmethodcanbedeclaredas abstract .An abstract classcannotbedirectly

http://www.vogella.com/tutorials/JavaIntroduction/article.html

13/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
instantiated.
Ifaclasshasatleastonemethod,whichonlycontainsthedeclarationofthemethod,butnotthe
implementation,thenthisclassis abstract andcannotbeinstantiated.Subclassesneedthen
todefinethemethodsexceptiftheyarealsodeclaredasabstract.
Ifaclasscontainsanabstractmethod,italsoneedstogetdefinedwiththekeyword abstract .
Thefollowingexampleshowsanabstractclass.
packagecom.vogella.javaintro.base;
publicabstractclassMyAbstractClass{
abstractdoublereturnDouble();
}

12.CheatSheets
Thefollowingcanbeusedasareferenceforcertaintaskwhichyouhavetodo.

12.1.Workingwithclasses
WhileprogrammingJavayouhavetocreateseveralclasses,methods,instancevariables.The
followingusesthepackagetest.
Table2.
What to do
Create a new
class called
MyNewClass.

How to do it

packagetest;
publicclassMyNewClass{
}

Create a new
attribute
(instance
variable) called
var1 of type
String in the

packagetest;
publicclassMyNewClass{
privateStringvar1;
}

MyNewClass

class
Create a
Constructor
for your
MyNewClass

class which
has a String
parameter and
assigns the
value of it to
the var1
instance
variable.
Create a new
method called
doSomeThing
in your class
which does
not return a
value and has
no
parameters.

packagetest;
publicclassMyNewClass{
privateStringvar1;
publicMyNewClass(Stringpara1){
var1=para1;
//orthis.var1=para1;
}
}

packagetest;
publicclassMyNewClass{
privateStringvar1;
publicMyNewClass(Stringpara1){
var1=para1;
//orthis.var1=para1;
}
publicvoiddoSomeThing(){
}
}

Create a new
method called
doSomeThing2
in your class
which does
not return a

packagetest;
publicclassMyNewClass{
privateStringvar1;

http://www.vogella.com/tutorials/JavaIntroduction/article.html

14/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
value and has
two
parameters,
an int and a

publicMyNewClass(Stringpara1){
var1=para1;
//orthis.var1=para1;
}

Person

publicvoiddoSomeThing(){
}
publicvoiddoSomeThing2(inta,Personperson){
}
}

Create a new
method called
doSomeThing2
in your class
which returns
an int value
and has three
parameters,
two Strings
and a
Person .

packagetest;
publicclassMyNewClass{
privateStringvar1;
publicMyNewClass(Stringpara1){
var1=para1;
//orthis.var1=para1;
}
publicvoiddoSomeThing(){
}
publicvoiddoSomeThing2(inta,Personperson){
}
publicintdoSomeThing3(Stringa,Stringb,Personperson){
return5;//anyvaluewilldoforthisexample
}
}

Create a class
called
MyOtherClass
with two
instance
variables. One
will store a
String , the
other will store
a Dog . Create
getter and
setter for
these
variables.

packagetest;
publicclassMyOtherClass{
Stringmyvalue;
Dogdog;
publicStringgetMyvalue(){
returnmyvalue;
}
publicvoidsetMyvalue(Stringmyvalue){
this.myvalue=myvalue;
}
publicDoggetDog(){
returndog;
}
publicvoidsetDog(Dogdog){
this.dog=dog;
}
}

12.2.Workingwithlocalvariable
Alocalvariablemustalwaysbedeclaredinamethod.
Table3.
What to do

How to do it

Declare a (local) variable of type String .

Stringvariable1;

Declare a (local) variable of type String and assign


"Test" to it.

Stringvariable2="Test";

Declare a (local) variable of type Person

Personperson;

Declare a (local) variable of type Person , create a new

Personperson=newPerson();

http://www.vogella.com/tutorials/JavaIntroduction/article.html

15/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
Object and assign the variable to this object.
Declare an array of type String

Stringarray[];

Declare an array of type Person and create an array for


this variable which can hold 5 persons.

Personarray[]=newPerson[5];

Assign 5 to the int variable var1 (which was already


declared);

var1=5;

Assign the existing variable pers2 to the exiting variable


pers1 ;

pers1=pers2;

Declare an ArrayList variable which can hold objects of


type Person

ArrayList<Person> persons;

Create a new ArrayList with objects of type Person and


assign it to the existing variable persons .

persons = new ArrayList<Person>();

Declare an ArrayList variable which can hold objects of


type Person and create a new Object for it.

ArrayList<Person> persons = new


ArrayList<Person>();

13.IntegratedDevelopmentEnvironment
ThepreviouschapterexplainedhowtocreateandcompileaJavaprogramonthecommandline.
AJavaIntegratedDevelopmentEnvironment(IDE)provideslotsofeaseofusefunctionalityfor
creatingJavaprograms.ThereareotherverypowerfulIDEsavailable,forexample,theEclipse
IDE.
ForanintroductiononhowtousetheEclipseIDEpleaseseeEclipseIDETutorial.
Theremainingdescriptionusesthephrase:"CreateaJavaprojectcalled...".Thisreferstocreating
aJavaprojectinEclipse.IfyouareusingadifferentIDE,pleasefollowtherequiredstepsinthat
IDE.

14.ExercisesCreatingJavaobjectsandmethods
14.1.CreateaPersonclassandinstantiateit
CreateanewJavaprojectcalled com.vogella.javastarter.exercises1 andapackagewiththe
samename.
CreateaclasscalledPerson.
Addthreeinstancevariablestoit,oneforstoringthefirstnameoftheperson,oneforstoringthe
lastnameandoneforstoringtheageofthePerson.
Usetheconstructorofthe Person objecttosetthevaluestosomedefaultvalue.
Adda toString methodasdescribedbythefollowingcodeingandsolvetheTODO.Thismethod
isusedtoconverttheobjecttoaStringrepresentation.
@Override
publicStringtoString(){
//TODOreplace""withthefollowing:
//firstName+""+lastName
return"";
}

CreateanewclasscalledMainwitha publicstaticvoidmain(String[]args) .Inthismethod


createaninstanceofthe Person class.

14.2.Useconstructor
Addaconstructortoyour Person classwhichtakesfirstname,lastnameandageasparameter.
Assignthevaluestoyourinstancevariables.
Inyourmainmethodcreateatleastoneobjectoftype Person anduse System.out.println()
withtheobjectasparameter.

14.3.Definegetterandsettermethods
Definemethodswhichallowyoutoreadthevaluesoftheinstancevariablesandtosetthem.
Thesemethodsarecalledsetterandgetter.
Gettersshouldstartwith get followedbythevariablenamewherebythefirstletterofthevariable
iscapitalized.

http://www.vogella.com/tutorials/JavaIntroduction/article.html

16/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
Settershouldstartwith set followedbythevariablenamewherebythefirstletterofthevariable
iscapitalized.
Forexample,thevariablecalledfirstNamewouldhavethe getFirstName() gettermethodand
the setFirstName(Strings) settermethod.
Changeyour main methodsothatyoucreateone Person objectandusethesettermethodto
changethelastname.

14.4.CreateanAddressobject
CreateanewobjectcalledAddress.The Address shouldallowyoutostoretheaddressofa
person.
Addanewinstancevariableofthistypeinthe Person object.Also,createagetterandsetterfor
the Address objectinthe Person object.

15.SolutionCreatingJavaobjectsandmethods
15.1.CreateaPersonclassandinstantiateit
ThefollowingistheexpectedresultafterSection14.1,CreateaPersonclassandinstantiate
it.
packageexercises.exercise04;
classPerson{
Stringfirstname="Jim";
Stringlastname="Knopf";
intage=12;
@Override
publicStringtoString(){
returnfirstName+""+lastName;
}
}

packageexercises.exercise04;
publicclassMain{
publicstaticvoidmain(String[]args){
Personperson=newPerson();

//thiscallsthetoStringmethodonthepersobject
System.out.println(pers);
}
}

15.2.Useconstructor
ThefollowingistheexpectedresultafterSection14.2,Useconstructor.
packagecom.vogella.javastarter.exercises1;

classPerson{
StringfirstName;
StringlastName;
intage;
publicPerson(Stringa,Stringb,intvalue){
firstName=a;
lastName=b;
age=value;
}

@Override
publicStringtoString(){
returnfirstName+""+lastName;
}
}

packagecom.vogella.javastarter.exercises1;
publicclassMain{

http://www.vogella.com/tutorials/JavaIntroduction/article.html

17/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
publicstaticvoidmain(String[]args){
Personp1=newPerson("Jim","Knopf",12);
System.out.println(p1);
//reusethesamevariableandassignanewobjecttoit
Personp2=newPerson("Henry","Ford",104);
System.out.println(p2);
}
}

15.3.Definegetterandsettermethods
ThefollowingistheexpectedresultafterSection14.3,Definegetterandsettermethods.
packagecom.vogella.javastarter.exercises1;
classPerson{
StringfirstName;
StringlastName;
intage;
publicPerson(Stringa,Stringb,intvalue){
firstName=a;
lastName=b;
age=value;
}
publicStringgetFirstName(){
returnfirstName;
}
publicvoidsetFirstName(StringfirstName){
this.firstName=firstName;
}
publicStringgetLastName(){
returnlastName;
}
publicvoidsetLastName(StringlastName){
this.lastName=lastName;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}

@Override
publicStringtoString(){
returnfirstName+""+lastName;
}

packagecom.vogella.javastarter.exercises1;
publicclassMain{
publicstaticvoidmain(String[]args){
Personperson=newPerson("Jim","Knopf",21);
Personp2=newPerson("Jill","Sanders",20);
//JillgetsmarriedtoJim
//andtakeshisname
p2.setLastName("Knopf");
System.out.println(p2);
}
}

15.4.SolutionCreateanAddressobject
ThefollowingistheexpectedresultafterSection14.4,CreateanAddressobject.
packagecom.vogella.javastarter.exercises1;

http://www.vogella.com/tutorials/JavaIntroduction/article.html

18/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
publicclassAddress{
privateStringstreet;
privateStringnumber;
privateStringpostalCode;
privateStringcity;
privateStringcountry;
publicStringgetStreet(){
returnstreet;
}
publicvoidsetStreet(Stringstreet){
this.street=street;
}
publicStringgetNumber(){
returnnumber;
}
publicvoidsetNumber(Stringnumber){
this.number=number;
}
publicStringgetPostalCode(){
returnpostalCode;
}
publicvoidsetPostalCode(StringpostalCode){
this.postalCode=postalCode;
}
publicStringgetCity(){
returncity;
}
publicvoidsetCity(Stringcity){
this.city=city;
}
publicStringgetCountry(){
returncountry;
}
publicvoidsetCountry(Stringcountry){
this.country=country;
}
publicStringtoString(){
returnstreet+""+number+""+postalCode+""+city+""
+country;
}
}

packagecom.vogella.javastarter.exercises1;

classPerson{
StringfirstName;
StringlastName;
intage;
privateAddressaddress;
publicPerson(Stringa,Stringb,intvalue){
firstName=a;
lastName=b;
age=value;
}
publicStringgetFirstName(){
returnfirstName;
}
publicvoidsetFirstName(StringfirstName){
this.firstName=firstName;
}
publicStringgetLastName(){
returnlastName;
}

http://www.vogella.com/tutorials/JavaIntroduction/article.html

19/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
publicvoidsetLastName(StringlastName){
this.lastName=lastName;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}

publicAddressgetAddress(){
returnaddress;
}
publicvoidsetAddress(Addressaddress){
this.address=address;
}
@Override
publicStringtoString(){
returnfirstName+""+lastName;
}
}

packagecom.vogella.javastarter.exercises1;
publicclassMain{
publicstaticvoidmain(String[]args){
//Icreateaperson
Personpers=newPerson("Jim","Knopf",31);
//settheageofthepersonto32
pers.setAge(32);
//justfortestingIwritethistotheconsole
System.out.println(pers);
/*
*actuallySystem.out.printlnalwayscallstoString,ifyoudonot
*specifyitsoyoucouldalsohavewrittenSystem.out.println(pers);
*/
//createanaddress
Addressaddress=newAddress();
//setthevaluesfortheaddress
address.setCity("Heidelberg");
address.setCountry("Germany");
address.setNumber("104");
address.setPostalCode("69214");
address.setStreet("Musterstr.");
//assigntheaddresstotheperson
pers.setAddress(address);
//disposereferencetoaddressobject
address=null;
//personismovingtothenexthouseinthesamestreet
pers.getAddress().setNumber("105");
}
}

16.Javastatements
TheJavalanguagedefinescertainstatementswithapredefinedmeaning.Thefollowing
descriptionlistssomeofthem.

16.1.ifthenandifthenelse
The ifthen statementisacontrolflowstatement.Ablockofcodeisonlyexecutedwhenthetest
specifiedbythe if partevaluatesto true .Theoptional else blockisexecutedwhenthe if
partevaluatesto false .
Thefollowingexamplecodeshowsaclasswithtwomethods.Thefirstmethoddemonstratesthe
usageof ifthen andthesecondmethoddemonstratestheusageof ifthenelse .

http://www.vogella.com/tutorials/JavaIntroduction/article.html

20/29

8/26/2015

IntroductiontoJavaprogrammingTutorial

16.2.Switch
Theswitchstatementcanbeusedtohandleseveralalternativesiftheyarebasedonthesame
constantvalue.
switch(expression){
caseconstant1:
command;
break;//willpreventthattheothercasesoralsoexecuted
caseconstant2:
command;
break;
...
default:
}
//Example:
switch(cat.getLevel()){
case0:
returntrue;
case1:
if(cat.getLevel()==1){
if(cat.getName().equalsIgnoreCase(req.getCategory())){
returntrue;
}
}
case2:
if(cat.getName().equalsIgnoreCase(req.getSubCategory())){
returntrue;
}
}

16.3.BooleanOperations
Use == tocomparetwoprimitivesortoseeiftworeferencesrefertothesameobject.Usethe
equals() methodtoseeiftwodifferentobjectsareequal.
&&and||arebothShortCircuitMethodswhichmeansthattheyterminateoncetheresultofan
evaluationisalreadyclear. Example(true||...) isalways true while (false&&...)
alwaysisalwaysinterpretedas false .Usage:
( var!=null&&var.method1()... )ensuresthat var isnot null beforedoingtherealcheck.
Table4.Boolean
Operations

Description

==

Is equal, in case of objects the system checks if the reference


variable point to the same object. It will not compare the
content of the objects!

&&

And

!=

is not equal, similar to == .

a.equals(b)

Checks if string a equals b.

a.equalsIgnoreCase(b)

Checks if string a equals b while ignoring lower cases.

If(value?false:true){}

Negotiation: return true if value is not true.

17.LoopsinJava
17.1.Theforloop
Aforloopisarepetitioncontrolstructurethatallowsyoutowriteablockofcodewhichisexecuted
aspecificnumberoftimes.Thesyntaxisthefollowing.
for(initialization;expression;update_statement)
{
//blockofcodetorun
}

Thefollowingshowsanexampleforaforloop.

http://www.vogella.com/tutorials/JavaIntroduction/article.html

21/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
publicclassForTest{
publicstaticvoidmain(Stringargs[]){
for(inti=1;i<10;i=i+1){
System.out.println("valueofi:"+i);
}
}
}

Tip: Forarraysandcollectionsthereisalsoanenhancedforloopavailable.This
loopiscoveredintheArraydescription.

17.2.Thewhileloop
Awhileloopisarepetitioncontrolstructurethatallowsyoutowriteablockofcodewhichis
executeduntilaspecificconditionevaluatestofalse.Thesyntaxisthefollowing.
while(expression)
{
//blockofcodetorun
}

Thefollowingshowsanexampleforawhileloop.
publicclassWhileTest{
publicstaticvoidmain(Stringargs[]){
intx=1;
while(x<10){
System.out.println("valueofx:"+x);
x++;
}
}
}

17.3.Thedowhileloop
Thedowhileloopissimilartothewhileloop,withtheexceptionthattheconditionischeckedafter
theexecution.Thesyntaxisthefollowing.
do
{
//blockofcodetorun
}while(expression);

Thefollowingshowsanexampleforadowhileloop.
publicclassDoTest{
publicstaticvoidmain(Stringargs[]){
intx=1;
do{
System.out.println("valueofx:"+x);
x++;
}while(x<10);
}
}

18.Arrays
18.1.ArraysinJava
Anarrayisacontainerobjectthatholdsafixednumberofvaluesofasingletype.Aniteminan
arrayiscalledanelement.Everyelementcanbeaccessedviaanindex.Thefirstelementinan
arrayisaddressedviathe0index,thesecondvia1,etc.
packagecom.vogella.javaintro.array;
publicclassTestMain{
publicstaticvoidmain(String[]args){
//declaresanarrayofintegers

http://www.vogella.com/tutorials/JavaIntroduction/article.html

22/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
int[]array;
//allocatesmemoryfor10integers
array=newint[10];
//initializevalues
array[0]=10;
//initializesecondelement
array[1]=20;
array[2]=30;
array[3]=40;
array[4]=50;
array[5]=60;
array[6]=70;
array[7]=80;
array[8]=90;
array[9]=100;
}
}

18.2.EnhancedforloopforArraysandCollections
Arraysandcollectionscanbeprocessedwithasimplerforloop.
for(declaration:expression)
{
//bodyofcodetobeexecuted
}

Thefollowingcodedemonstratesitsusage.
packagecom.vogella.javaintro.array;
publicclassTestMain{
publicstaticvoidmain(String[]args){
//declaresanarrayofintegers
int[]array;
//allocatesmemoryfor10integers
array=newint[10];
//initializevalues
array[0]=10;
//initializesecondelement
array[1]=20;
array[2]=30;
array[3]=40;
array[4]=50;
array[5]=60;
array[6]=70;
array[7]=80;
array[8]=90;
array[9]=100;
for(inti:array){
System.out.println("Elementatindex"+i+":"+array[i]);
}
}
}

19.Strings
19.1.StringsinJava
The String classrepresentscharacterstrings.Allstringliterals,forexample,"hello",are
implementedasinstancesofthisclass.Aninstanceofthisclassisanobject.Stringsare
immutable,e.g.,anassignmentofanewvaluetoa String objectcreatesanewobject.

19.2.StringpoolinJava
FormemoryefficiencyJavausesa String pool.Thestringpoolallowsstringliteralstobe
reused.ThisispossiblebecausestringsinJavaareimmutable.
IfthesamestringliteralisusedinseveralplacesintheJavacode,onlyonecopyofthatstringis
created.
Whenevera String objectiscreatedandgetsastringliteralassigned,e.g.,asin

http://www.vogella.com/tutorials/JavaIntroduction/article.html

23/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
Strings="constant" ,thestringpoolisused.However,the new operatorforcesanew
String copytobeallocated,forexample,in Strings=newString("constant"); .

19.3.CompareStringsinJava
Tocomparethe String objects s1 and s2 ,usethe s1.equals(s2) method.
A String comparisonwith == isincorrect,as == checksforobjectreferenceequality. ==
sometimesgivesthecorrectresult,asJavausesa String pool.Thefollowingexamplewould
workwith == .
Thiswouldworkasexpected.
Stringa="Hello";
Stringb="Hello";
if(a==b){
//ifstatementistrue
//becauseStringpoolisusedand
//aandbpointtothesameconstant
}

Thiscomparisonwouldfail.
Stringa="Hello";
Stringb=newString("Hello");
if(a==b){

}else{
//ifstatementisfalse
//becauseStringpoolisusedand
//aandbpointtothesameconstant
}

Warning: Therefore,youshouldalwaysusethe equals() methodwhenyou


comparestrings.

19.4.WorkingwithStrings
Thefollowingliststhemostcommonstringoperations.
Table5.
Command

Description

"Testing".equals(text1);

Return true if text1 is equal to "Testing" .


The check is case-sensitive.

"Testing".equalsIgnoreCase(text1);

Return true if text1 is equal to "Testing" .


The check is not case-sensitive. For example, it
would also be true for "testing" .

StringBufferstr1=newStringBuffer();

Define a new String with a variable length.

str.charat(1);

Return the character at position 1. (Note:


strings are arrays of chars starting with 0)

str.substring(1);

Removes the first characters.

str.substring(1,5);

Gets the substring from the second to the fifth


character.

str.indexOf("Test")

Look for the String "Test" in String str .


Returns the index of the first occurrence of the
specified string.

str.lastIndexOf("ing")

Returns the index of the last occurrence of the


specified String "ing" in the String str.
StringBuffer does not support this method.
Hence first convert the StringBuffer to
String via method toString .

str.endsWith("ing")

Returns true if str ends with String


"ing"

str.startsWith("Test")

Returns true if String str starts with


String "Test" .

str.trim()

Removes leading and trailing spaces.

http://www.vogella.com/tutorials/JavaIntroduction/article.html

24/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
str.replace(str1,str2)

Replaces all occurrences of str1 by str2

str2.concat(str1);

Concatenates str1 at the end of str2 .

str.toLowerCase() / str.toUpperCase()

Converts the string to lower- or uppercase

str1+str2

Concatenate str1 and str2

String[]array=myString.split("");
String[]array2=myString.split("\\.");

Splits the character separated myString into


an array of strings. Attention: the split string
is a regular expression, so if you using
special characters which have a meaning in
regular expressions, you need to quote
them. In the second example the . is used
and must be quoted by two backslashes.

20.Lambdas
20.1.Whatarelambdas?
TheJavaprogramminglanguagesupportslambdasasofJava8.Alambdaexpressionisablock
ofcodewithparameters.Lambdasallowstospecifyablockofcodewhichshouldbeexecuted
later.Ifamethodexpectsafunctionalinterfaceasparameteritispossibletopassinthelambda
expressioninstead.
ThetypeofalambdaexpressioninJavaisafunctionalinterface.

20.2.Differencebetweenalambdaexpressionandaclosure
Alambdaisananonymousfunction,e.g.,itcanbedefinedasparameter.Aclosureisanyfunction
whichclosesovertheenvironmentinwhichitwasdefined.Thismeansthatitcanaccessvariables
notinitsparameterlistandassignedtoavariable.
Javasupportslambdasbutnotclosures.

20.3.Purposeoflambdaexpressions
UsinglambdasallowstouseacondensedsyntaxcomparedtootherJavaprogramming
constructs.Forexamplethe Collections inJava8havea forEach methodwhichacceptsa
lambdaexpression.
List<String>list=newArrayList<>();
list.add("vogella.com");
list.add("google.com");
list.add("heise.de");
list.forEach(System.out::println);

20.4.Usingmethodreferences
Youcanusemethodreferencesinalambdaexpression.Methodreferencedefinethemethodto
becalledvia CalledFrom::method .CalledFromcanbe
instance::instanceMethod
SomeClass::staticMethod
SomeClass::instanceMethod

List<String>list=newArrayList<>();
list.add("vogella.com");
list.add("google.com");
list.add("heise.de");
list.forEach(s>System.out.println(s));

21.Streams
21.1.WhatareStreamsinJava8?
Astreamfromthe java.util.stream packageisasequenceofelementsfromasourcethat
supportsaggregateoperations.

21.2.IntStream
Allowtocreateastreamofsequenceofprimitiveintvaluedelementssupportingsequentialand

http://www.vogella.com/tutorials/JavaIntroduction/article.html

25/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
parallelaggregateoperations.
packagecom.vogella.java.streams;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.stream.IntStream;
publicclassIntStreamExample{
publicstaticvoidmain(String[]args){
//printoutthenumbersfrom1to100
IntStream.range(1,101).forEach(s>System.out.println(s));

//createalistofintegersfor1to100
List<Integer>list=newArrayList<>();
IntStream.range(1,101).forEach(it>list.add(it));
System.out.println("Size"+list.size());
}
}

21.3.Reductionoperationswithstreamsandlambdas
Allowtocreateastreamofsequenceofprimitiveintvaluedelementssupportingsequentialand
parallelaggregateoperations.
packagecom.vogella.java.streams;
publicclassTask{
privateStringsummary;
privateintduration;

publicTask(Stringsummary,intduration){
this.summary=summary;
this.duration=duration;
}
publicStringgetSummary(){
returnsummary;
}
publicvoidsetSummary(Stringsummary){
this.summary=summary;
}
publicintgetDuration(){
returnduration;
}
publicvoidsetDuration(intduration){
this.duration=duration;
}

packagecom.vogella.java.streams;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Random;
importjava.util.stream.Collectors;
importjava.util.stream.IntStream;
publicclassStreamTester{
publicstaticvoidmain(String[]args){
Randomrandom=newRandom();
//Generatealistofrandomtask
List<Task>values=newArrayList<>();
IntStream.range(1,20).forEach(i>values.add(newTask("Task"+random.nextInt
(10),random.nextInt(10))));

//getalistofthedistincttasksummaryfield
List<String>resultList=values.stream().filter(t>t.getDuration()>5).map(
t>t.getSummary()).distinct().collect(Collectors.toList());
System.out.println(resultList);

//getaconcatenatedstringofTaskwithadurationlongerthan5hours
Stringcollect=values.stream().filter(t>t.getDuration()>5).map(t>t.ge
tSummary()).distinct().collect(Collectors.joining(""));

http://www.vogella.com/tutorials/JavaIntroduction/article.html

26/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
System.out.println(collect);
}
}

22.TypeConversion
IfyouusevariablesofdifferenttypesJavarequiresforcertaintypesanexplicitconversion.The
followinggivesexamplesforthisconversion.

22.1.ConversiontoString
UsethefollowingtoconvertfromothertypestoStrings
//ConvertfrominttoString
Strings1=String.valueOf(10);//"10"
//ConvertfromdoubletoString
Strings2=String.valueOf(Math.PI);//"3.141592653589793"
//ConvertfrombooleantoString
Strings3=String.valueOf(1<2);//"true"
//ConvertfromdatetoString
Strings4=String.valueOf(newDate());//"TueJun0314:40:38CEST2003"

22.2.ConversionfromStringtoNumber
//ConversionfromStringtoint
inti=Integer.parseInt(String);
//Conversionfromfloattoint
floatf=Float.parseFloat(String);
//Conversionfromdoubletoint
doubled=Double.parseDouble(String);

Theconversionfromstringtonumberisindependentfromthelocalesettings,e.g.,itisalways
usingtheEnglishnotificationfornumber.Inthisnotificationacorrectnumberformatis"8.20".
ThedGermannumber"8,20"wouldresultinanerror.
ToconvertfromaGermannumber,youhavetousethe NumberFormat class.Thechallengeis
thatwhenthevalueis,forexample,98.00thenthe NumberFormat classwouldcreatea Long
whichcannotbecastedtoDouble.Hencethefollowingcomplexconversionclass.
privateDoubleconvertStringToDouble(Strings){
Localel=newLocale("de","DE");
Locale.setDefault(l);
NumberFormatnf=NumberFormat.getInstance();
Doubleresult=0.0;
try{
if(Class.forName("java.lang.Long").isInstance(nf.parse(s))){
result=Double.parseDouble(String.valueOf(nf.parse(s)));
}else{
result=(Double)nf.parse(newString(s));
}
}catch(ClassNotFoundExceptione1){
e1.printStackTrace();
}catch(ParseExceptione1){
e1.printStackTrace();
}
returnresult;
}

22.3.Doubletoint
inti=(int)double

22.4.SQLDateconversions
UsethefollowingtoconvertaDatetoaSQLdate
packagetest;
importjava.text.DateFormat;
importjava.text.ParseException;
importjava.text.SimpleDateFormat;
publicclassConvertDateToSQLDate{

http://www.vogella.com/tutorials/JavaIntroduction/article.html

27/29

8/26/2015

IntroductiontoJavaprogrammingTutorial
privatevoidconvertDateToSQL(){
SimpleDateFormattemplate=
newSimpleDateFormat("yyyyMMdd");
java.util.Dateenddate=
newjava.util.Date("10/31/99");
java.sql.DatesqlDate=
java.sql.Date.valueOf(template.format(enddate));

}
publicstaticvoidmain(String[]args){
ConvertDateToSQLDatedate=newConvertDateToSQLDate();
date.convertDateToSQL();
}
}

23.Scheduletasks
Javaallowsyoutoscheduletasks.Ascheduledtaskscanperformonceorseveraltimes.
java.util.Timer and java.util.TimerTask canbeusedtoscheduletasks.Theobjectwhich

implements TimeTask willthenbeperformedbythe Timer basedonthegiveninterval.


packageschedule;
importjava.util.TimerTask;
publicclassMyTaskextendsTimerTask{
privatefinalStringstring;
privateintcount=0;
publicMyTask(Stringstring){
this.string=string;
}
@Override
publicvoidrun(){
count++;
System.out.println(string+"called"+count);
}
}

packageschedule;
importjava.util.Timer;
publicclassScheduleTest{
publicstaticvoidmain(String[]args){
Timertimer=newTimer();
//wait2seconds(2000millisecs)andthenstart
timer.schedule(newMyTask("Task1"),2000);
for(inti=0;i<100;i++){
//wait1secondsandthenagainevery5seconds
timer.schedule(newMyTask("Task"+i),1000,5000);
}
}
}

Tip: Improved job scheduling is available via the open source


framework quartz. See http://www.onjava.com/lpt/a/4637 or
http://www.quartz-scheduler.org/ for an explanation.

http://www.vogella.com/tutorials/JavaIntroduction/article.html

28/29

8/26/2015

IntroductiontoJavaprogrammingTutorial

24.Aboutthiswebsite
Support free content

Questions and
discussion

Tutorial & code license

Get source code

25.LinksandLiterature
CodeConventionsfortheJavaProgrammingLanguagebyGoogle

http://www.vogella.com/tutorials/JavaIntroduction/article.html

29/29

You might also like