+ All Categories
Home > Documents > Introduction to Java Programming - Tutorial

Introduction to Java Programming - Tutorial

Date post: 05-Mar-2016
Category:
Upload: raghavendra-sh
View: 16 times
Download: 0 times
Share this document with a friend
Description:
java

of 29

Transcript
  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    IntroductiontoJavaprogrammingTutorial

    LarsVogel

    Version2.6

    Copyright2008,2009,2010,2011,2012,2013,2014,2015vogellaGmbH

    02.04.2015

    IntroductiontoJavaprogramming

    ThistutorialexplainstheinstallationandusageoftheJavaprogramminglanguage.Italsocontainsexamplesforstandardprogrammingtasks.

    TableofContents

    1.IntroductiontoJava

    1.1.History1.2.Javaandopensourcesoftware1.3.Javavirtualmachine1.4.JavaRuntimeEnvironmentvs.JavaDevelopmentKit1.5.CharacteristicsofJava1.6.DevelopmentProcesswithJava1.7.Garbagecollector1.8.Classpath

    2.InstallationofJava

    2.1.Checkinstallation2.2.InstallJavaonUbuntu2.3.InstallJavaonMSWindows2.4.Installationproblemsandotheroperatingsystems2.5.Validateinstallation2.6.Howcanyoutellyouareusinga32bitor64bitversionofJava?

    3.Exercise:Write,compileandrunaJavaprogram

    3.1.Writesourcecode3.2.CompileandrunyourJavaprogram3.3.Usingtheclasspath

    4.Javalanguagestructure

    4.1.Basics:Package,ClassandObject4.2.Package4.3.Class4.4.Object4.5.Inheritance4.6.Objectassuperclass

    5.Javainterfaces

    5.1.WhatisaninterfaceinJava?5.2.Abstract,defaultandstaticmethodsinInterfaces5.3.ImplementingInterfaces5.4.Evolvinginterfaces5.5.Multipleinheritanceofmethods5.6.Functionalinterfaces

    6.Javabasicterms

    6.1.Overridemethodsandthe@Overrideannotation

    7.ThetypesystemofJava

    7.1.Primitivesandreferences7.2.Primitives7.3.Referencetypes7.4.Autoboxingandwrappertypes

    8.Variablesandmethods

    8.1.Variable

    Tutorials Services Products Books Company Donate

    Contact us

    Search

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    8.2.Instancevariable8.3.Localvariable8.4.Methods8.5.Mainmethod8.6.Constructor

    9.Modifiers

    9.1.Accessmodifiers9.2.Othermodifiers

    10.Importstatements

    10.1.Usageofimportstatements10.2.Staticimports

    11.MoreJavalanguageconstructs

    11.1.Classmethodsandclassvariables11.2.Abstractclassandmethods

    12.CheatSheets

    12.1.Workingwithclasses12.2.Workingwithlocalvariable

    13.IntegratedDevelopmentEnvironment14.ExercisesCreatingJavaobjectsandmethods

    14.1.CreateaPersonclassandinstantiateit14.2.Useconstructor14.3.Definegetterandsettermethods14.4.CreateanAddressobject

    15.SolutionCreatingJavaobjectsandmethods

    15.1.CreateaPersonclassandinstantiateit15.2.Useconstructor15.3.Definegetterandsettermethods15.4.SolutionCreateanAddressobject

    16.Javastatements

    16.1.ifthenandifthenelse16.2.Switch16.3.BooleanOperations

    17.LoopsinJava

    17.1.Theforloop17.2.Thewhileloop17.3.Thedowhileloop

    18.Arrays

    18.1.ArraysinJava18.2.EnhancedforloopforArraysandCollections

    19.Strings

    19.1.StringsinJava19.2.StringpoolinJava19.3.CompareStringsinJava19.4.WorkingwithStrings

    20.Lambdas

    20.1.Whatarelambdas?20.2.Differencebetweenalambdaexpressionandaclosure20.3.Purposeoflambdaexpressions20.4.Usingmethodreferences

    21.Streams

    21.1.WhatareStreamsinJava8?21.2.IntStream21.3.Reductionoperationswithstreamsandlambdas

    22.TypeConversion

    22.1.ConversiontoString22.2.ConversionfromStringtoNumber22.3.Doubletoint22.4.SQLDateconversions

    23.Scheduletasks24.Aboutthiswebsite25.LinksandLiterature

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    1.IntroductiontoJava

    1.1.History

    JavaisaprogramminglanguagecreatedbyJamesGoslingfromSunMicrosystems(Sun)in1991.ThefirstpubliclyavailableversionofJava(Java1.0)wasreleasedin1995.

    SunMicrosystemswasacquiredbytheOracleCorporationin2010.OraclehasnowthesteermanshipforJava.

    OvertimenewenhancedversionsofJavahavebeenreleased.ThecurrentversionofJavaisJava1.7whichisalsoknownasJava7.

    FromtheJavaprogramminglanguagetheJavaplatformevolved.TheJavaplatformallowssoftwaredeveloperstowriteprogramcodeinotherlanguagesthantheJavaprogramminglanguagewhichstillrunsontheJavavirtualmachine.TheJavaplatformisusuallyassociatedwiththeJavavirtualmachineandtheJavacorelibraries.

    1.2.Javaandopensourcesoftware

    In2006SunstartedtomakeJavaavailableundertheGNUGeneralPublicLicense(GPL).OraclecontinuesthisprojectcalledOpenJDK.

    1.3.Javavirtualmachine

    TheJavavirtualmachine(JVM)isasoftwareimplementationofacomputerthatexecutesprogramslikearealmachine.

    TheJavavirtualmachineiswrittenspecificallyforaspecificoperatingsystem,e.g.,forLinuxaspecialimplementationisrequiredaswellasforWindows.

    JavaprogramsarecompiledbytheJavacompilerintobytecode.TheJavavirtualmachineinterpretsthisbytecodeandexecutestheJavaprogram.

    1.4.JavaRuntimeEnvironmentvs.JavaDevelopmentKit

    AJavadistributiontypicallycomesintwoflavors,theJavaRuntimeEnvironment(JRE)andtheJavaDevelopmentKit(JDK).

    TheJavaruntimeenvironment(JRE)consistsoftheJVMandtheJavaclasslibraries.ThosecontainthenecessaryfunctionalitytostartJavaprograms.

    TheJDKadditionallycontainsthedevelopmenttoolsnecessarytocreateJavaprograms.TheJDKthereforeconsistsofaJavacompiler,theJavavirtualmachineandtheJavaclasslibraries.

    1.5.CharacteristicsofJava

    ThetargetofJavaistowriteaprogramonceandthenrunthisprogramonmultipleoperatingsystems.

    Javahasthefollowingproperties:

    Days Inn Hotel New York City-Broadway$109.65 Covered By Expedia's Best Price GuaranteeExpedia.com

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    Platformindependent:JavaprogramsusetheJavavirtualmachineasabstractionanddonotaccesstheoperatingsystemdirectly.ThismakesJavaprogramshighlyportable.AJavaprogram(whichisstandardcompliantandfollowscertainrules)canrununmodifiedonallsupportedplatforms,e.g.,WindowsorLinux.

    Objectorientatedprogramminglanguage:Excepttheprimitivedatatypes,allelementsinJavaareobjects.

    Stronglytypedprogramminglanguage:Javaisstronglytyped,e.g.,thetypesoftheusedvariablesmustbepredefinedandconversiontootherobjectsisrelativelystrict,e.g.,mustbedoneinmostcasesbytheprogrammer.

    Interpretedandcompiledlanguage:Javasourcecodeistransferredintothebytecodeformatwhichdoesnotdependonthetargetplatform.ThesebytecodeinstructionswillbeinterpretedbytheJavaVirtualmachine(JVM).TheJVMcontainsasocalledHotspotCompilerwhichtranslatesperformancecriticalbytecodeinstructionsintonativecodeinstructions.

    Automaticmemorymanagement:Javamanagesthememoryallocationanddeallocationforcreatingnewobjects.Theprogramdoesnothavedirectaccesstothememory.Thesocalledgarbagecollectorautomaticallydeletesobjectstowhichnoactivepointerexists.

    TheJavasyntaxissimilartoC++.Javaiscasesensitive,e.g.,variablescalled myValue andmyvalue aretreatedasdifferentvariables.

    1.6.DevelopmentProcesswithJava

    Javasourcefilesarewrittenasplaintextdocuments.TheprogrammertypicallywritesJavasourcecodeinanIntegratedDevelopmentEnvironment(IDE)forprogramming.AnIDEsupportstheprogrammerinthetaskofwritingcode,e.g.,itprovidesautoformatingofthesourcecode,highlightingoftheimportantkeywords,etc.

    Atsomepointtheprogrammer(ortheIDE)callstheJavacompiler(javac).TheJavacompilercreatesthebytecodeinstructions.Theseinstructionsarestoredin.classfilesandcanbeexecutedbytheJavaVirtualMachine.

    1.7.Garbagecollector

    TheJVMautomaticallyrecollectsthememorywhichisnotreferredtobyotherobjects.TheJavagarbagecollectorchecksallobjectreferencesandfindstheobjectswhichcanbeautomaticallyreleased.

    Whilethegarbagecollectorrelievestheprogrammerfromtheneedtoexplicitlymanagememory,theprogrammerstillneedtoensurethathedoesnotkeepunneededobjectreferences,otherwisethegarbagecollectorcannotreleasetheassociatedmemory.Keepingunneededobjectreferencesaretypicallycalledmemoryleaks.

    1.8.Classpath

    TheclasspathdefineswheretheJavacompilerandJavaruntimelookfor.classfilestoload.TheseinstructionscanbeusedintheJavaprogram.

    Forexample,ifyouwanttouseanexternalJavalibraryyouhavetoaddthislibrarytoyourclasspathtouseitinyourprogram.

    2.InstallationofJava

    2.1.Checkinstallation

    TorunJavaprogramsonyourcomputeryoumustatleasthavetheJavaruntimeenvironment(JRE)installed.Thismightalreadybethecaseonyourmachine.YoucantestistheJREisinstalledandinyourcurrentpathbyopeningaconsole(ifyouareusingWindows:Win+R,entercmdandpressEnter)andbytypinginthefollowingcommand:

    javaversion

    IftheJREisinstalledandwithinyourpath,thiscommandsprintinformationaboutyourJavainstallation.InthiscaseyoucanskiptheJavainstallationdescription.Youmaywanttonotedownifyouhavea32bitor64bitversionofJava,seeSection2.6,Howcanyoutellyouareusinga32bitor64bitversionofJava?.

    Ifthecommandlinereturnstheinformationthattheprogramcouldnotbefound,youhavetoinstallJava.

    2.2.InstallJavaonUbuntu

    OnUbuntuyoucaninstallJava7viathefollowingcommandonthecommandline.

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    sudoaptgetinstallopenjdk7jdk

    2.3.InstallJavaonMSWindows

    ForMicrosoftsWindows,OracleprovidesanativeinstallerwhichcanbefoundontheOraclewebsite.ThecentralwebsiteforinstallingJavaislocatedunderthefollowingURLandalsocontainsinstructionshowtoinstallJavaforotherplatforms.

    java.com

    2.4.Installationproblemsandotheroperatingsystems

    IfyouhaveproblemsinstallingJavaonyoursystem,searchviaGoogleforHowtoinstallJDKonYOUR_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 andtheoutputcontainsthe"64Bit"stringyouareusingthe64bitversionofJavaotherwiseyourareusingthe32bitversion.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.Inthisdescriptionthepath\home\vogella\javastarterisused.OnMicrosoftWindowsyoumightwanttousec:\temp\javastarter.Thispathiscalledjavadirinthefollowingdescription.

    Openatexteditorwhichsupportsplaintext,e.g.,geditunderLinuxorNotepadunderWindowsandwritethefollowingsourcecode.

    //asmallJavaprogrampublicclassHelloWorld{publicstaticvoidmain(String[]args){System.out.println("HelloWorld");}}

    Warning: DonotusearicheditorlikeMicrosoftWordorLibreOfficeforwritingJavacode.Ifindoubt,googlefor"Plaintexteditorfor[your_OS]".

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    SavethesourcecodeinyourjavadirdirectorywiththeHelloWorld.javafilename.ThenameofaJavasourcefilemustalwaysequaltheclassname(withinthesourcecode)andendwiththe.javaextension.InthisexamplethefilenamemustbeHelloWorld.java,becausetheclassiscalled HelloWorld .

    3.2.CompileandrunyourJavaprogram

    Openashellforcommandlineaccess.

    Tip: Ifyoudon'tknowhowtodothis,googlefor"Howtoopenashellunder[your_OS]".

    Switchtothejavadirdirectorywiththecommand cdjavadir ,forexample,intheaboveexampleviathe cd\home\vogella\javastarter command.Usethe ls command( dir underMicrosoftWindows)toverifythatthesourcefileisinthedirectory.

    CompileyourJavasourcefileintoaclassfilewiththefollowingcommand.

    javacHelloWorld.java

    Afterwardslistagainthecontentofthedirectorywiththe ls or dir command.ThedirectorycontainsnowafileHelloWorld.class.Ifyouseethisfile,youhavesuccessfullycompiledyourfirstJavasourcecodeintobytecode.

    Tip: Bydefault,thecompilerputseachclassfileinthesamedirectoryasitssourcefile.Youcanspecifyaseparatedestinationdirectorywiththedcompilerflag.

    YoucannowstartyourcompiledJavaprogram.EnsurethatyouarestillinthejardirdirectoryandenterthefollowingcommandtostartyourJavaprogram.

    javaHelloWorld

    Thesystemshouldwrite"HelloWorld"onthecommandline.

    3.3.Usingtheclasspath

    Youcanusetheclasspathtoruntheprogramfromanotherplaceinyourdirectory.

    Switchtothecommandline,e.g.,underWindowsStartRun cmd .Switchtoanydirectoryyouwant.Type:

    javaHelloWorld

    Ifyouarenotinthedirectoryinwhichthecompiledclassisstored,thenthesystemwillshowan

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    errormessage:Exceptioninthread"main"java.lang.NoClassDefFoundError:test/TestClass

    Tousetheclass,typethefollowingcommand.Replace"mydirectory"withthedirectorywhichcontainsthetestdirectory.Youshouldagainseethe"HelloWorld"output.

    javaclasspath"mydirectory"HelloWorld

    4.Javalanguagestructure

    4.1.Basics:Package,ClassandObject

    ItisimportanttounderstandthebaseterminologyofJavaintermsofpackages,classesandobjects.Thissectiongivesanoverviewoftheseterms.

    4.2.Package

    Javagroupsclassesintofunctionalpackages.

    Packagesaretypicallyusedtogroupclassesintologicalunits.Forexample,allgraphicalviewsofanapplicationmightbeplacedinthesamepackagecalled com.vogella.webapplication.views .

    Itiscommonpracticetousethereversedomainnameofthecompanyastoplevelpackage.Forexample,thecompanymightownthedomain,vogella.comandinthisexampletheJavapackagesofthiscompanystartswith com.vogella .

    Othermainreasonfortheusageofpackagesistoavoidnamecollisionsofclasses.Anamecollisionoccursiftwoprogrammersgivethesamefullyqualifiednametoaclass.ThefullyqualifiednameofaclassinJavaconsistsofthepackagenamefollowedbyadot(.)andtheclassname.

    Withoutpackages,aprogrammermaycreateaJavaclasscalled Test .Anotherprogrammermaycreateaclasswiththesamename.Withtheusageofpackagesyoucantellthesystemwhichclasstocall.Forexample,ifthefirstprogrammerputsthe Test classintopackage report andthesecondprogrammerputshisclassintopackage xmlreader youcandistinguishbetweentheseclassesbyusingthefullyqualifiedname,e.g, xmlreader.Test or report.Test .

    4.3.Class

    Def.:Templatethatdescribesthedataandbehaviorassociatedwithaninstanceofthatclass.

    Note: Theclasscanbeseenastheblueprintofanobject.Itdescribeshowanobjectiscreated.

    InJavasourcecodeaclassisdefinedbytheclasskeywordandmuststartwithacapitalletter.Thebodyofaclassissurroundedby{}.

    packagetest;

    classMyClass{}

    Thedataassociatedwithaclassisstoredinvariablesthebehaviorassociatedtoaclassorobjectisimplementedwithmethods.

    AclassiscontainedinaJavasourcefilewiththesamenameastheclassplusthe.javaextension.

    4.4.Object

    Def.:Anobjectisaninstanceofaclass.

    Theobjectistherealelementwhichhasdataandcanperformactions.Eachobjectiscreatedbasedontheclassdefinition.

    4.5.Inheritance

    Aclasscanbederivedfromanotherclass.Inthiscasethisclassiscalledasubclass.Anothercommonphraseisthataclassextendsanotherclass.

    Theclassfromwhichthesubclassisderivediscalledasuperclass.

    Inheritanceallowsaclasstoinheritthebehavioranddatadefinitionsofanotherclass.

    Thefollowingcodesdemonstrateshowaclasscanextendanotherclass.InJavaaclasscanonlyextendamaximumofoneclass.

    packagecom.vogella.javaintro.base;

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    classMyBaseClass{@Overridepublicvoidhello(){System.out.println("HellofromMyBaseClass");}}

    packagecom.vogella.javaintro.base;

    classMyExtensionClassextendsMyBaseClass{}

    4.6.Objectassuperclass

    EveryobjectinJavaimplicitlyextendsthe Object class.TheclassdefinesthefollowingmethodsforeveryJavaobject:

    equals(o1) allowscheckingifthecurrentobjectisequaltoo1

    getClass() returnstheclassoftheobject

    hashCode() returnsanidentifierofthecurrentobject

    toString() givesastringrepresentationofthecurrentobject

    5.Javainterfaces

    5.1.WhatisaninterfaceinJava?

    Aninterfacesisatypesimilartoaclassandisdefinedviathe interface keyword.Likeaclassaninterfacedefinesmethods.Classescanimplementtheinterfacesandbythistheymustobeythecontractdefinedintheinterface,e.g.,theclastprovideimplementationforallabstractmethodsdefinedintheinterface.

    5.2.Abstract,defaultandstaticmethodsinInterfaces

    Aninterfacecanhaveabstractmethodsanddefaultmethods.Adefaultmethodisdefinedviathedefault keywordatthebeginningofthemethodsignature.Allothermethodsdefinedinaninterfacesarepublicandabstractexplicitdeclarationofthesemodifiersisoptional.

    Interfacescanhaveconstantswhicharealwaysimplicitlypublic,staticandfinal.

    Thefollowingcodeshowsanexampleimplementationofaninterface.

    packagetesting;

    publicinterfaceMyInterface{

    //constantdefinitionStringURL="http://www.vogella.com";

    //publicabstractmethodsvoidtest();voidwrite(Strings);//defaultmethoddefaultStringreserveString(Strings){returnnewStringBuilder(s).reverse().toString();}}

    Thefollowingclassimplementsthisinterface,itsmustimplementtheabstractmethodandcanusethedefaultmethods.

    5.3.ImplementingInterfaces

    Aclasscanimplementaninterface.Inthiscaseitmustprovideconcreteimplementationsoftheabstractinterfacemethods.Ifyouimplementamethoddefinedbyaninterface,youcanuse@Override annotationtoindicatetotheJavacompilerthatyouactuallywanttoimplementamethoddefinedbythisinterface.Thiswaythecompilercangiveyouanerrorinyoumistypedthenameofthemethodorinthenumberofarguments.

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    packagecom.vogella.javaintro.base;

    publicclassMyClassImplimplementsMyInterface{

    @Overridepublicvoidtest(){}

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

    }

    5.4.Evolvinginterfaces

    BeforeJava8evolvinginterfaces,e.g.,addingnewmethodstoaninterface,wasnotpossiblebecausesuchachangewouldbreakexistingimplementations.Java8introduceddefaultmethods,nowyoucanextendaninterfacewithoutbreakingclientsbysimplysupplingadefaultimplementationwithit.Addingsuchadefaultmethodisasourceanbinarycompatiblechange.

    Aclasscanalwaysoverrideadefaultmethodsosupplyabetterbehavior.

    5.5.Multipleinheritanceofmethods

    Ifaclassimplementstwointerfacesandiftheseinterfacesprovidethesamedefaultmethod,Javaresolvesthecorrectmethodfortheclassbythefollowingrules:

    1. SuperclasswinsalwaysagainstthesuperinterfaceIfaclasscaninheritamethodfromasuperclassandasuperinterface,theclassinhertsthesuperclassmethod.Thisistrueforconcreteandabstractsuperclassmethods.Thisruleimpliesthatdefaultmethodsarenotusedifthismethodisalsodeclaredinthesuperclasschain.

    2. SubtypeswinoverSupertypesIfaclasscaninheritamethodfromtwointerfaces,andoneisasubtypeoftheother,theclassinhertsthemethodfromthesubtype

    3. Inallothercasestheclassneedstoimplementthedefaultmethod

    Thefollowinglistingdemonstrateslistingnumber3.

    publicinterfaceA{defaultvoidm(){}}

    publicinterfaceB{defaultvoidm(){}}

    publicclassCimplementsA,B{@Overridepublicvoidm(){}}

    Inyourimplementationyoucanalsocallthesupermethodyouprefer.

    publicclassCimplementsA,B{@Overridepublicvoidm(){A.super.m();}}

    5.6.Functionalinterfaces

    Allinterfacesthathaveonlyonemethodarecalledfunctionalinterfaces.Functionalinterfaceshavetheadvantagethattheycanbeusedtogetherwithlambdaexpressions.SeeSection20.1,Whatarelambdas?tolearnmoreaboutlambdas,e.g.,thetypeoflambdasisafunctionalinterface.

    TheJavacompilerautomaticallyidentifiesfunctionalinterfaces.Theonlyrequirementisthattheyhaveonlyoneabstractmethod.However,ispossibletocapturethedesignintentwitha@FunctionalInterface annotation.

    SeveraldefaultJavainterfacesarefunctionalinterfaces:

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    java.lang.Runnable

    java.util.concurrent.Callable

    java.io.FileFilter

    java.util.Comparator

    java.beans.PropertyChangeListener

    Javaalsocontainsthe java.util.function packagewhichcontainsfunctionalinterfaceswhicharefrequentlyusedsuchas:

    Predicateabooleanvaluedpropertyofanobject

    Consumeranactiontobeperformedonanobject

    FunctionafunctiontransformingaTtoaR

    SupplierprovidesaninstanceofT(suchasafactory)

    UnaryOperatorafunctionfromTtoT

    BinaryOperatorafunctionfrom(T,T)toT

    6.Javabasicterms

    6.1.Overridemethodsandthe@Overrideannotation

    Ifaclassextendsanotherclass,itinheritsthemethodsfromitssuperclass.Ifitwantstochangethesemethods,itcanoverridethesemethods.Tooverrideamethod,youusethesamemethodsignatureinthesourcecodeofthesubclass.

    ToindicatetothereaderofthesourcecodeandtheJavacompilerthatyouhavetheintentiontooverrideamethod,youcanusethe @Override annotation.

    Thefollowingcodedemonstrateshowyoucanoverrideamethodfromasuperclass.

    packagecom.vogella.javaintro.base;

    classMyBaseClass{@Overridepublicvoidhello(){System.out.println("HellofromMyBaseClass");}}

    packagecom.vogella.javaintro.base;

    classMyExtensionClass2extendsMyBaseClass{publicvoidhello(){System.out.println("HellofromMyExtensionClass2");}}

    Tip: Itisgoodpracticetoalwaysusethe @Override annotation.ThiswaytheJavacompilervalidatesifyoudidoverrideallmethodsasintendedandpreventserrors.

    7.ThetypesystemofJava

    7.1.Primitivesandreferences

    Javadistinguishesbetweenprimitivetypes(suchasboolean,short,int,double,float,charandbyte)andreferencetypes(suchasObjectandString).

    7.2.Primitives

    Primitivetypesvariablesrepresentsthenumber,true/falseorcharacter.Youcannotcallmethodsonvariableswhichhaveaprimitivetypes.

    Operatorssuchas*,,+or/areonlysupportedforprimitivetypes.Only+canalsousedforthereferencetypeStringtoconcatenatestrings.

    7.3.Referencetypes

    Referencetypesvariablesrepresentsareferencetoanobject,e.g.,avariableisapointertothe

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    realobject.Ifyouchangethevalueofareferencetypevariable,thevariablepointstoadifferentobjectorto null whichrepresentsthenonexistingobjectreference.Changingthevalueofareferencetypevariabledoesnotchangetheattributesoftheobjectiswaspointingto.Alsochangingthecontentsofanobjectdoesnotaffectthevalueofavariablereferringtothatobject.

    7.4.Autoboxingandwrappertypes

    EveryprimitivetypehasinJavaafittingreferencetype.Thisreferencetypeallowstostorethevalueoftheprimitivetypeinanobject.Forexampleyouhave java.lang.Integer forint.

    Convertingaprimitivevalueintoaninstanceofawrappertypeandviceversaiscalledboxing/unboxing.Javaperformstheseoperationsautomaticallyofnecessary.Thisallowsyoutouseaprimitiveasparameterinamethodwhichexpectsanobjectofthewrappertype.Thisautomaticboxingandunboxingisknownasautoboxing.

    8.Variablesandmethods

    8.1.Variable

    VariablesallowtheJavaprogramtostorevaluesduringtheruntimeoftheprogram.

    Avariablecaneitherbeaprimitivevariableorareferencevariable.Aprimitivevariablecontainsthevaluewhilethereferencevariablecontainsareference(pointer)totheobject.Hence,ifyoucomparetworeferencevariables,youcompareifbothpointtothesameobject.Tocompareobjects,usethe object1.equals(object2) methodcall.

    8.2.Instancevariable

    Instancevariableisassociatedwithaninstanceoftheclass(alsocalledobject).Accessworksovertheseobjects.

    Instancevariablescanhaveanyaccesscontrolandcanbemarked final or transient .Instancevariablesmarkedasfinalcannotbechangedafteravaluehasbeenassignedtothem.

    8.3.Localvariable

    Local(stack)variabledeclarationscannothaveaccessmodifiers.

    finalistheonlymodifieravailabletolocalvariables.Thismodifierdefinesthatthevariablecannotbechangedafterthefirstassignment.

    Localvariablesdonotgetdefaultvalues,sotheymustbeinitializedbeforeuse.

    8.4.Methods

    Amethodisablockofcodewithparametersandareturnvalue.Itcanbecalledontheobject.

    packagecom.vogella.javaintro.base;

    publicclassMyMethodExample{voidtester(Strings){System.out.println("HelloWorld");}}

    Methodscanbedeclaredwithvarargs.Inthiscasethemethoddeclaresaparameterwhichacceptseverythingfromzerotomanyarguments(syntax:type...name)Amethodcanonlyhaveonevarargsparameterandthismustbethelastparameterinthemethod.

    Overwriteofasuperclassmethod:Amethodmustbeoftheexactsamereturnparameterandthesamearguments.Alsothereturnparametermustbethesame.Overloadmethods:Anoverloadedmethodisamethodwiththesamename,butdifferentarguments.Thereturntypecannotbeusedtooverloadamethod.

    8.5.Mainmethod

    ApublicstaticmethodwiththefollowingsignaturecanbeusedtostartaJavaapplication.Suchamethodistypicallycalled main method.

    publicstaticvoidmain(String[]args){

    }

    8.6.Constructor

    Aclasscontainsconstructorsthatareinvokedtocreateobjectsbasedontheclassdefinition.

    Constructordeclarationslooklikemethoddeclarationsexceptthattheyusethenameoftheclassandhavenoreturntype.

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    Aclasscanhaveseveralconstructorswithdifferentparameters.Eachclassmustdefineatleastoneconstructor.

    Inthefollowingexampletheconstructoroftheclassexpectsaparameter.

    packagecom.vogella.javaintro.base;

    publicclassMyConstructorExample2{

    Strings;

    publicMyConstructorExample2(Strings){this.s=s;}}

    Ifnoexplicitconstructorisdefined,thecompilerimplicitlyaddsaconstructor.Iftheclassissubclassed,thentheconstructorofthesuperclassisalwayscalledimplicitlyinthiscase.

    Inthefollowingexamplethedefinitionoftheconstructorwithoutparameters(alsoknownastheemptyconstructor)isunnecessary.Ifnotspecified,thecompilerwouldcreateone.

    packagecom.vogella.javaintro.base;

    publicclassMyConstructorExample{

    //unnecessary:wouldbecreatedbythecompilerifleftoutpublicMyConstructorExample(){}}

    Thenamingconventionforcreatingaconstructoristhefollowing:classname(Parameterp1,...){} .

    Everyobjectiscreatedbasedonaconstructor.Thisconstructormethodisthefirststatementcalledbeforeanythingelsecanbedonewiththeobject.

    9.Modifiers

    9.1.Accessmodifiers

    TherearethreeaccessmodifierskeywordsavailableinJava:public,protectedandprivate.

    Therearefouraccesslevels:public,protected,defaultandprivate.Theydefinehowthecorrespondingelementisvisibletoothercomponents.

    Ifsomethingisdeclaredpublic,e.g.,classesormethodscanbefreelycreatedorcalledbyotherJavaobjects.Ifsomethingisdeclaredprivate,e.g.,amethod,itcanonlybeaccessedwithintheclassinwhichitisdeclared.

    Theaccesslevelsprotectedanddefaultaresimilar.Aprotectedclasscanbeaccessedfromthepackageandsubclassesoutsidethepackage,whileadefaultclasscangetaccessedonlyviathesamepackage.

    Thefollowingtabledescribesthevisibility:

    Table1.AccessLevel

    Modifier Class Package Subclass World

    public Y Y Y Y

    protected Y Y Y N

    no modifier Y Y N N

    private Y N N N

    9.2.Othermodifiers

    finalmethods:cannotbeoverwritteninasubclass

    abstractmethod:nomethodbody

    synchronizedmethod:threadsafe,canbefinalandhaveanyaccesscontrol

    nativemethods:platformdependentcode,applyonlytomethods

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    strictfp:classormethod

    10.Importstatements

    10.1.Usageofimportstatements

    InJavayouhavetoaccessaclassalwaysviaitsfullqualifiedname,i.e.,thepackagenameandtheclassname.

    Youcanadd import statementsforclassesorpackagesintoyourclassfile,whichallowyoutousetherelatedclassesinyourcodewithoutthepackagequalifier.

    10.2.Staticimports

    Staticimportisafeaturethatallowsmembers(fieldsandmethods)whicharedefinedinaclasswiththe publicstatic accessmodifiertobeusedinJavacodewithoutspecifyingtheclassinwhichthememberisdefined.

    Thefeatureprovidesatypesafemechanismtoincludeconstantsintocodewithouthavingtoreferencetheclassthatoriginallydefinedthefield.

    11.MoreJavalanguageconstructs

    11.1.Classmethodsandclassvariables

    Classmethodsandclassvariablesareassociatedwiththeclassandnotaninstanceoftheclass,i.e.,objects.Torefertotheseelements,youcanusetheclassnameandadot(".")followedbytheclassmethodorclassvariablename.

    Classmethodsandclassvariablesaredeclaredwiththe static keyword.Classmethodsarealsocalledstaticmethodsandclassvariablesarealsocalledstaticvariablesorstaticfields.

    Anexamplefortheusageofastaticfieldis println ofthefollowingstatement:System.out.println("HelloWorld") .Hereby out isastaticfield,anobjectoftypePrintStream andyoucallthe println() methodonthisobject.

    Ifyoudefineastaticvariable,theJavaruntimeenvironmentassociatesoneclassvariableforaclassnomatterhowmanyinstances(objects)exist.Thestaticvariablecanthereforebeseenasaglobalvariable.

    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 finalkeyword.

    Thestaticmethodrunswithoutanyinstanceoftheclass,itcannotdirectlyaccessnonstaticvariablesormethods.

    11.2.Abstractclassandmethods

    Aclassandmethodcanbedeclaredas abstract .An abstract classcannotbedirectly

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    instantiated.

    Ifaclasshasatleastonemethod,whichonlycontainsthedeclarationofthemethod,butnottheimplementation,thenthisclassis abstract andcannotbeinstantiated.Subclassesneedthentodefinethemethodsexceptiftheyarealsodeclaredasabstract.

    Ifaclasscontainsanabstractmethod,italsoneedstogetdefinedwiththekeyword abstract .

    Thefollowingexampleshowsanabstractclass.

    packagecom.vogella.javaintro.base;

    publicabstractclassMyAbstractClass{abstractdoublereturnDouble();}

    12.CheatSheets

    Thefollowingcanbeusedasareferenceforcertaintaskwhichyouhavetodo.

    12.1.Workingwithclasses

    WhileprogrammingJavayouhavetocreateseveralclasses,methods,instancevariables.Thefollowingusesthepackagetest.

    Table2.

    What to do How to do it

    Create a newclass calledMyNewClass.

    packagetest;

    publicclassMyNewClass{

    }

    Create a newattribute(instancevariable) calledvar1 of typeString in theMyNewClass

    class

    packagetest;

    publicclassMyNewClass{privateStringvar1;}

    Create aConstructorfor yourMyNewClass

    class whichhas a Stringparameter andassigns thevalue of it tothe var1instancevariable.

    packagetest;

    publicclassMyNewClass{privateStringvar1;

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

    Create a newmethod calleddoSomeThingin your classwhich doesnot return avalue and hasnoparameters.

    packagetest;

    publicclassMyNewClass{privateStringvar1;

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

    publicvoiddoSomeThing(){

    }

    }

    Create a newmethod calleddoSomeThing2in your classwhich doesnot return a

    packagetest;

    publicclassMyNewClass{privateStringvar1;

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    value and hastwoparameters,an int and aPerson

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

    publicvoiddoSomeThing(){

    }

    publicvoiddoSomeThing2(inta,Personperson){

    }

    }

    Create a newmethod calleddoSomeThing2in your classwhich returnsan int valueand has threeparameters,two Stringsand aPerson .

    packagetest;

    publicclassMyNewClass{privateStringvar1;

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

    publicvoiddoSomeThing(){

    }

    publicvoiddoSomeThing2(inta,Personperson){

    }

    publicintdoSomeThing3(Stringa,Stringb,Personperson){return5;//anyvaluewilldoforthisexample}

    }

    Create a classcalledMyOtherClasswith twoinstancevariables. Onewill store aString , the

    other will storea Dog . Creategetter andsetter forthesevariables.

    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();

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    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 forthis variable which can hold 5 persons.

    Personarray[]=newPerson[5];

    Assign 5 to the int variable var1 (which was alreadydeclared);

    var1=5;

    Assign the existing variable pers2 to the exiting variablepers1 ;

    pers1=pers2;

    Declare an ArrayList variable which can hold objects oftype Person

    ArrayList persons;

    Create a new ArrayList with objects of type Person andassign it to the existing variable persons .

    persons = new ArrayList();

    Declare an ArrayList variable which can hold objects oftype Person and create a new Object for it.

    ArrayList persons = newArrayList();

    13.IntegratedDevelopmentEnvironment

    ThepreviouschapterexplainedhowtocreateandcompileaJavaprogramonthecommandline.AJavaIntegratedDevelopmentEnvironment(IDE)provideslotsofeaseofusefunctionalityforcreatingJavaprograms.ThereareotherverypowerfulIDEsavailable,forexample,theEclipseIDE.

    ForanintroductiononhowtousetheEclipseIDEpleaseseeEclipseIDETutorial.

    Theremainingdescriptionusesthephrase:"CreateaJavaprojectcalled...".ThisreferstocreatingaJavaprojectinEclipse.IfyouareusingadifferentIDE,pleasefollowtherequiredstepsinthatIDE.

    14.ExercisesCreatingJavaobjectsandmethods

    14.1.CreateaPersonclassandinstantiateit

    CreateanewJavaprojectcalled com.vogella.javastarter.exercises1 andapackagewiththesamename.

    CreateaclasscalledPerson.

    Addthreeinstancevariablestoit,oneforstoringthefirstnameoftheperson,oneforstoringthelastnameandoneforstoringtheageofthePerson.

    Usetheconstructorofthe Person objecttosetthevaluestosomedefaultvalue.

    Adda toString methodasdescribedbythefollowingcodeingandsolvetheTODO.ThismethodisusedtoconverttheobjecttoaStringrepresentation.

    @OverridepublicStringtoString(){//TODOreplace""withthefollowing://firstName+""+lastNamereturn"";}

    CreateanewclasscalledMainwitha publicstaticvoidmain(String[]args) .Inthismethodcreateaninstanceofthe Person class.

    14.2.Useconstructor

    Addaconstructortoyour Person classwhichtakesfirstname,lastnameandageasparameter.Assignthevaluestoyourinstancevariables.

    Inyourmainmethodcreateatleastoneobjectoftype Person anduse System.out.println()withtheobjectasparameter.

    14.3.Definegetterandsettermethods

    Definemethodswhichallowyoutoreadthevaluesoftheinstancevariablesandtosetthem.Thesemethodsarecalledsetterandgetter.

    Gettersshouldstartwith get followedbythevariablenamewherebythefirstletterofthevariableiscapitalized.

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    Settershouldstartwith set followedbythevariablenamewherebythefirstletterofthevariableiscapitalized.

    Forexample,thevariablecalledfirstNamewouldhavethe getFirstName() gettermethodandthe setFirstName(Strings) settermethod.

    Changeyour main methodsothatyoucreateone Person objectandusethesettermethodtochangethelastname.

    14.4.CreateanAddressobject

    CreateanewobjectcalledAddress.The Address shouldallowyoutostoretheaddressofaperson.

    Addanewinstancevariableofthistypeinthe Person object.Also,createagetterandsetterforthe Address objectinthe Person object.

    15.SolutionCreatingJavaobjectsandmethods

    15.1.CreateaPersonclassandinstantiateit

    ThefollowingistheexpectedresultafterSection14.1,CreateaPersonclassandinstantiateit.

    packageexercises.exercise04;

    classPerson{Stringfirstname="Jim";Stringlastname="Knopf";intage=12;

    @OverridepublicStringtoString(){returnfirstName+""+lastName;}

    }

    packageexercises.exercise04;

    publicclassMain{publicstaticvoidmain(String[]args){Personperson=newPerson();//thiscallsthetoStringmethodonthepersobjectSystem.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;}@OverridepublicStringtoString(){returnfirstName+""+lastName;}

    }

    packagecom.vogella.javastarter.exercises1;

    publicclassMain{

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    publicstaticvoidmain(String[]args){Personp1=newPerson("Jim","Knopf",12);System.out.println(p1);

    //reusethesamevariableandassignanewobjecttoitPersonp2=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;}@OverridepublicStringtoString(){returnfirstName+""+lastName;}

    }

    packagecom.vogella.javastarter.exercises1;

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

    15.4.SolutionCreateanAddressobject

    ThefollowingistheexpectedresultafterSection14.4,CreateanAddressobject.

    packagecom.vogella.javastarter.exercises1;

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    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;}

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    publicvoidsetLastName(StringlastName){this.lastName=lastName;}

    publicintgetAge(){returnage;}

    publicvoidsetAge(intage){this.age=age;}

    publicAddressgetAddress(){returnaddress;}

    publicvoidsetAddress(Addressaddress){this.address=address;}

    @OverridepublicStringtoString(){returnfirstName+""+lastName;}

    }

    packagecom.vogella.javastarter.exercises1;

    publicclassMain{publicstaticvoidmain(String[]args){//IcreateapersonPersonpers=newPerson("Jim","Knopf",31);//settheageofthepersonto32pers.setAge(32);

    //justfortestingIwritethistotheconsoleSystem.out.println(pers);/**actuallySystem.out.printlnalwayscallstoString,ifyoudonot*specifyitsoyoucouldalsohavewrittenSystem.out.println(pers);*///createanaddressAddressaddress=newAddress();//setthevaluesfortheaddressaddress.setCity("Heidelberg");address.setCountry("Germany");address.setNumber("104");address.setPostalCode("69214");address.setStreet("Musterstr.");

    //assigntheaddresstothepersonpers.setAddress(address);

    //disposereferencetoaddressobjectaddress=null;

    //personismovingtothenexthouseinthesamestreetpers.getAddress().setNumber("105");

    }

    }

    16.Javastatements

    TheJavalanguagedefinescertainstatementswithapredefinedmeaning.Thefollowingdescriptionlistssomeofthem.

    16.1.ifthenandifthenelse

    The ifthen statementisacontrolflowstatement.Ablockofcodeisonlyexecutedwhenthetestspecifiedbythe if partevaluatesto true .Theoptional else blockisexecutedwhenthe ifpartevaluatesto false .

    Thefollowingexamplecodeshowsaclasswithtwomethods.Thefirstmethoddemonstratestheusageof ifthen andthesecondmethoddemonstratestheusageof ifthenelse .

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    16.2.Switch

    Theswitchstatementcanbeusedtohandleseveralalternativesiftheyarebasedonthesameconstantvalue.

    switch(expression){caseconstant1:command;break;//willpreventthattheothercasesoralsoexecutedcaseconstant2: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.Usetheequals() methodtoseeiftwodifferentobjectsareequal.

    &&and||arebothShortCircuitMethodswhichmeansthattheyterminateoncetheresultofanevaluationisalreadyclear. 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 referencevariable point to the same object. It will not compare thecontent 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

    Aforloopisarepetitioncontrolstructurethatallowsyoutowriteablockofcodewhichisexecutedaspecificnumberoftimes.Thesyntaxisthefollowing.

    for(initialization;expression;update_statement){//blockofcodetorun}

    Thefollowingshowsanexampleforaforloop.

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    publicclassForTest{

    publicstaticvoidmain(Stringargs[]){

    for(inti=1;i

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    int[]array;

    //allocatesmemoryfor10integersarray=newint[10];

    //initializevaluesarray[0]=10;//initializesecondelementarray[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){//declaresanarrayofintegersint[]array;

    //allocatesmemoryfor10integersarray=newint[10];

    //initializevaluesarray[0]=10;//initializesecondelementarray[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",areimplementedasinstancesofthisclass.Aninstanceofthisclassisanobject.Stringsareimmutable,e.g.,anassignmentofanewvaluetoa String objectcreatesanewobject.

    19.2.StringpoolinJava

    FormemoryefficiencyJavausesa String pool.Thestringpoolallowsstringliteralstobereused.ThisispossiblebecausestringsinJavaareimmutable.

    IfthesamestringliteralisusedinseveralplacesintheJavacode,onlyonecopyofthatstringiscreated.

    Whenevera String objectiscreatedandgetsastringliteralassigned,e.g.,asin

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    Strings="constant" ,thestringpoolisused.However,the new operatorforcesanewString 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.Thefollowingexamplewouldworkwith == .

    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() methodwhenyoucomparestrings.

    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, itwould 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 fifthcharacter.

    str.indexOf("Test") Look for the String "Test" in String str .Returns the index of the first occurrence of thespecified string.

    str.lastIndexOf("ing") Returns the index of the last occurrence of thespecified String "ing" in the String str.StringBuffer does not support this method.

    Hence first convert the StringBuffer toString via method toString .

    str.endsWith("ing") Returns true if str ends with String"ing"

    str.startsWith("Test") Returns true if String str starts withString "Test" .

    str.trim() Removes leading and trailing spaces.

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    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 intoan array of strings. Attention: the split stringis a regular expression, so if you usingspecial characters which have a meaning inregular expressions, you need to quotethem. In the second example the . is usedand must be quoted by two backslashes.

    20.Lambdas

    20.1.Whatarelambdas?

    TheJavaprogramminglanguagesupportslambdasasofJava8.Alambdaexpressionisablockofcodewithparameters.Lambdasallowstospecifyablockofcodewhichshouldbeexecutedlater.Ifamethodexpectsafunctionalinterfaceasparameteritispossibletopassinthelambdaexpressioninstead.

    ThetypeofalambdaexpressioninJavaisafunctionalinterface.

    20.2.Differencebetweenalambdaexpressionandaclosure

    Alambdaisananonymousfunction,e.g.,itcanbedefinedasparameter.Aclosureisanyfunctionwhichclosesovertheenvironmentinwhichitwasdefined.Thismeansthatitcanaccessvariablesnotinitsparameterlistandassignedtoavariable.

    Javasupportslambdasbutnotclosures.

    20.3.Purposeoflambdaexpressions

    UsinglambdasallowstouseacondensedsyntaxcomparedtootherJavaprogrammingconstructs.Forexamplethe Collections inJava8havea forEach methodwhichacceptsalambdaexpression.

    Listlist=newArrayList();list.add("vogella.com");list.add("google.com");list.add("heise.de");list.forEach(System.out::println);

    20.4.Usingmethodreferences

    Youcanusemethodreferencesinalambdaexpression.Methodreferencedefinethemethodtobecalledvia CalledFrom::method .CalledFromcanbe

    instance::instanceMethod

    SomeClass::staticMethod

    SomeClass::instanceMethod

    Listlist=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 packageisasequenceofelementsfromasourcethatsupportsaggregateoperations.

    21.2.IntStream

    Allowtocreateastreamofsequenceofprimitiveintvaluedelementssupportingsequentialand

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    parallelaggregateoperations.

    packagecom.vogella.java.streams;

    importjava.util.ArrayList;importjava.util.List;importjava.util.stream.IntStream;

    publicclassIntStreamExample{

    publicstaticvoidmain(String[]args){//printoutthenumbersfrom1to100IntStream.range(1,101).forEach(s>System.out.println(s));//createalistofintegersfor1to100Listlist=newArrayList();IntStream.range(1,101).forEach(it>list.add(it));System.out.println("Size"+list.size());}

    }

    21.3.Reductionoperationswithstreamsandlambdas

    Allowtocreateastreamofsequenceofprimitiveintvaluedelementssupportingsequentialandparallelaggregateoperations.

    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();//GeneratealistofrandomtaskListvalues=newArrayList();IntStream.range(1,20).forEach(i>values.add(newTask("Task"+random.nextInt(10),random.nextInt(10))));

    //getalistofthedistincttasksummaryfieldListresultList=values.stream().filter(t>t.getDuration()>5).map(t>t.getSummary()).distinct().collect(Collectors.toList());System.out.println(resultList);//getaconcatenatedstringofTaskwithadurationlongerthan5hoursStringcollect=values.stream().filter(t>t.getDuration()>5).map(t>t.getSummary()).distinct().collect(Collectors.joining(""));

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    System.out.println(collect);}

    }

    22.TypeConversion

    IfyouusevariablesofdifferenttypesJavarequiresforcertaintypesanexplicitconversion.Thefollowinggivesexamplesforthisconversion.

    22.1.ConversiontoString

    UsethefollowingtoconvertfromothertypestoStrings

    //ConvertfrominttoStringStrings1=String.valueOf(10);//"10"//ConvertfromdoubletoStringStrings2=String.valueOf(Math.PI);//"3.141592653589793"//ConvertfrombooleantoStringStrings3=String.valueOf(1

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    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.Theobjectwhichimplements TimeTask willthenbeperformedbythe Timer basedonthegiveninterval.

    packageschedule;

    importjava.util.TimerTask;

    publicclassMyTaskextendsTimerTask{privatefinalStringstring;privateintcount=0;

    publicMyTask(Stringstring){this.string=string;}

    @Overridepublicvoidrun(){count++;System.out.println(string+"called"+count);}

    }

    packageschedule;

    importjava.util.Timer;

    publicclassScheduleTest{

    publicstaticvoidmain(String[]args){Timertimer=newTimer();

    //wait2seconds(2000millisecs)andthenstarttimer.schedule(newMyTask("Task1"),2000);

    for(inti=0;i

  • 8/26/2015 IntroductiontoJavaprogrammingTutorial

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

    24.Aboutthiswebsite

    Support free content Questions anddiscussion

    Tutorial & code license Get source code

    25.LinksandLiterature

    CodeConventionsfortheJavaProgrammingLanguagebyGoogle


Recommended