Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming -...

42

Transcript of Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming -...

Page 1: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language
Page 2: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

JAVAProgrammingAnIntroduction,History,andtheFundamentalsforCreatingYour

FirstProgram

©Copyright2016byScottBernard-Allrightsreserved.

The transmission, duplication or reproduction of any of the following work includingspecific information will be considered an illegal act irrespective of if it is doneelectronicallyorinprint.Thisextendstocreatingasecondaryortertiarycopyoftheworkora recorded copy and is only allowedwith express written consent from the Publisher. Alladditionalrightreserved.

The information in the followingpages isbroadlyconsidered tobea truthful andaccurateaccountoffactsandassuchanyinattention,useormisuseoftheinformationinquestionbythereaderwillrenderanyresultingactionssolelyundertheirpurview.Therearenoscenariosinwhichthepublisherortheoriginalauthorofthisworkcanbeinanyfashiondeemedliablefor anyhardshipor damages thatmaybefall themafter undertaking informationdescribedherein.

Additionally, the information in the following pages is intended only for informationalpurposes and should thus be thought of as universal.As befitting its nature, it is presentedwithoutassuranceregardingitsprolongedvalidityorinterimquality.

Page 3: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

TABLEOFCONTENTS

INTRODUCTION

CHAPTER1 AnIntroductiontoJAVA

CHAPTER2 HowJAVAisBeingUsedToday

CHAPTER3 IntroductiontoJAVAProgrammingBasics

CHAPTER4 FamiliarizingYourselfwithJAVACommands

CHAPTER5 HowtoStartWritingProgramswithJAVAStepbyStep

CONCLUSION

Page 4: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language
Page 5: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

INTRODUCTION

CongratulationsondownloadingJAVAProgramming:An Introduction,History,and theFundamentalsforCreatingYourFirstProgram,andthankyoufordoingso!

ThefollowingchapterswilldiscussthefundamentalsofJAVAprogramming,itsuses,andhowtostartwritingJAVAcodeforyourself.

Thereareplentyofbooksonthissubjectavailableonthemarket,sothankyouagainforchoosingJAVAProgramming!Everyeffortwasmadetoensure thisbookisfullofasmuchusefulinformationaspossible.Pleaseenjoy!

Page 6: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language
Page 7: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

CHAPTER1

AnIntroductiontoJAVA

JAVAisatypeofprogramminglanguagethatwasdesignedspecificallytobeusedontheinternet. It is easier to use than its counterpart, C++ language, while utilizing a model ofprogramming that is object-oriented. JAVA may be utilized in order to create entireapplicationsthatmaybedistributedamongclientsandserversinanetworkorrunonasinglecomputer. JAVAcanalsobeusedbuilda smallapplet,ora smallapplicationmodule, tobeusedaspartofaWebpage.AppletsenableWebuserstointeractwiththatparticularWebpage.JAVAprogramscanbefoundinmobiledevices,desktops,Blu-rayDiscs,servers,andsmartcards.

JAVAwasoriginallyknownasOakwhenitwasfirstcreated.OakwascreatedbyJamesGosling in theyear1991. JamesGoslingworked for a companyat the timeknownasSunMicrosystemsandtheoriginalpurposeforGosling’sprogramminglanguagewastobeusedinsmallelectronics suchas televisions, toasters,VCRs,andso forth.Thepurposeof JAVAsinceitsbeginningwastobefast,efficient,small,andportable.SunMicrosystemsrenamedthe programming language and introduced JAVA in 1995. After this introduction, theinteractivecapabilitiesoftheWorldWideWebgrewexponentially.AJAVAvirtualmachineisincluded in all major Web browsers. Likewise, almost every major operating systemdeveloper has added JAVA compilers as a part ofwhat they offer in their products,majoroperating system developers being companies such as Microsoft and IBM. JAVA is nowownedandmaintainedbyacompanycalledOracle.

SohowdidthenameJAVAcometobe?ThenameJAVAcameintoexistencewhenJamesGosling,alongwithhisteammembers,weredevelopingtheJAVAlanguageandhappenedtobedrinkingcopiouslyhighamountsofcoffee.TheJAVAteamfeltthat,becauseofthelargequantityandhighqualityof thecoffee theyhappened tobedrinking, theywere thenable tobetterdevelopahigherqualityofaprogramminglanguage.Thecoffee thatJamesGoslingand his teamwere drinking had its own very special role in the development of the JAVAprogramminglanguageandhappenedtobedistributedtotheentireglobefromaplacewiththemoniker “Java Island”. Essentially,Gosling and his cutting edge teamwere inspired tochristen the brand new programming language with the name of the place where theircaffeinatednectaroriginated.Hence,thesymbolfortheJAVAprogramminglanguageistheunmistakablecupandsaucer.

Thetop10factsyouneedtoknowaboutJavaasyougetstartedreadingthisbook

1. ThetermJavarefersgenerallytoatrifectacombinationofthesethings:

TheprogramminglanguageknownasJAVA

TheJVM,orJAVAVirtualMachine,whichistheJAVAplatform.TheJVMiswhat

Page 8: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

runs Java bytecodes that have been compiled, usually calling on a set ofstandardizedlibrariesspecifictoJAVA.Theselibrariesincludethoseprovidedbythe Enterprise Edition, referred to as EE or Java Standard Edition, which isreferred to as SE. Though the platform for JAVA and the JVM are designed toworkhandinhand,thelanguageitselfdoesnotnecessarilyimplytheuseofJAVAVirtualMachine,andviceversaaswell.The JavaVirtualMachine (JVM) refers to a virtualmachineoperating at a veryhigh performance level, and executes bytecodes on a very specific computingplatform.The JAVAVirtualMachine is abbreviated and is simply referred to byprogrammerstypicallyasJVM.

2. ThemajorityofthehigherlayersofthewidelyusedmobileAndroidoperatingsystem,

orOS, is built using JAVA, so it is imperative that you learn JAVA if your goal is toeventually build applications for the android operating system. With JAVAprogramming,youare able tobuildgames, embedded systems,websites, anddesktopapplications,whichmayhavesimilarversionsofthoseprogramsonmobiledevicesandotherdevicesaswell.

3. Thereare4differentJAVAplatformsavailable:The JAVA Micro Edition. The JAVA Micro Edition contains the libraries andframeworksneededinordertobuildtheapplicationsthatrunonsmallerdevices,knownasmicrodevices,suchastabletsandsmartphones.

The JAVA Enterprise Edition. The JAVA Enterprise Edition is comprised of thelibrariesandframeworksthatarerequiredtobuildapplicationswhichareutilizedmostlybyenterprises.

TheJAVAFXEdition.TheJAVAFXEditioniscomprisedofgraphiclibrariesthatare used to operate consistently across a wide variety of platforms and also tobuildstrongclientapplications.

TheJAVAStandardEdition.TheJAVAStandardEditioniscomprisedofallofthecoreJAVAfunctionalitiesandallofthecoreJAVAlibraries.ThisistheeditionthatyouwillbeusingtolearnJAVAprogrammingfrominthisbook,andalsoutilizingwhenorifyoucontinuetopursueyourprogrammingeducation.

4. The JAVA programming language is an object oriented programming language,

referredtobyprogrammersasOOP,andoperatesonahighlevel.

5. TheJAVAprogramsarerunonaspecialdedicatedsoftwareknownastheJAVAVirtualMachine,referredtoasJVMintheprogrammingworld.

6. TheJAVAvirtualmachine,orJVM,issupportedbyahighnumberofoperatingsystems.BecauseofthefactthatJAVAcanberunonsomanyoperatingsystems,thismakesJAVAa cross-platform language. This is where the popular phrase “write once, run

Page 9: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

anywhere”,orWORA,originates from.This term isalsosometimesknownas“writeonce,runeverywhere”,orWORE.

7. YouwillneedtodownloadandtheninstalltheJAVAruntimeenvironment,alsoknownas theJRE, inorder to install theJAVAvirtualmachineandrunJAVAprograms.Notethat the JREcannot beused to develop JAVAprograms.The JREcanonlybeused toreadJAVAprograms.

8. InordertoaccessthetoolsnecessarytothedevelopmentofJAVAapplications,however,youfirstneedtodownloadandinstalltheJAVAdevelopmentkit.TheJAVAdevelopmentkit isalso referred tobyprogrammersas theJDK.The latestavailableversionof theJDKisversion8.However,youwillnotneedtodownloadtheJREifyoudownloadtheJDK8version,becauseyouareabletofreelyredistributetheJREinthatversionwithyourapplication,inaccordancetotheJRElicensingterms.

9. The acronym IDE refers to a software suite that is known as IntegratedDevelopmentEnvironment and which provides the people who program computers the necessarycomprehensive tools needed in order to make software writing, testing and overalldevelopmentpossible.Normally,amodernIDEwillbemadeupofadebugger,asourcecode editor, and an interpreter or compiler. The software developer utilizes a singlegraphicaluserinterface,referredtobydevelopersassimplyaGUI,inordertoaccessthosethreetools.TherearetwoverypopularJAVAIDEsthatarealsocompletelyfree–an IDE known as Netbeans, and an IDE known as Eclipse. In this book, you will beshownhowtoprogramutilizingtheEclipseIDE.

10. AgreatresourceoflearningallaboutbeginningyourJAVAprogrammingexperienceisrightinfrontofyou-thisbook!

JAVAFeatures

ThemajorfeaturesofJAVAare:

JAVA’s code is robust. This means that the JAVA objects may contain zeroreferences to other known objects, or data that is external to themselves. Incontrast, programswritten in C++ and other languages do not have this ability.This processmakes sure that the instruction does not contain the address of thestoreddataintheoperatingsystemitself,orthatofanotherapplication.Eitherofthoseoccurrenceswouldeffectivelycausetheoperatingsystemortheprogramtocrash,orterminate.Inordertoensureintegrity,theJAVAvirtualmachine,orJVM,hasanumberofchecksinplace.

JAVA applets have other features that are in place in order to make it work asefficientlyaspossible,inadditiontobeingexecutednotattheserver,butinstead,attheclient.

Page 10: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

JAVA is much easier to learn than C++, although the language is certainly notlearnedovernight.

Programs created in JAVA are portable in a network. This means that theseprograms can be used in other operating systems than the one that created itwithout needing to perform a complicated, time consuming,major rework. ThesourceprogramiscompiledintowhatJAVAreferstoasbytecode.ThisbytecodeisabletoberuninanynetworkonaclientorserverthathasaJVM.ThatJVMthentranslatesthebytecodetoacodewhichwillthenhavetheabilitytoberunontheactualcomputerhardwareitself,whichmeansthatdistinctdifferencesinplatforms,suchasthelengthofinstructionsforexample,areabletoberecognizedanddealtwith locally -assoonas theprogramisbeingexecuted.Basically,JAVAensuresthat it is no longer necessary to produce platform- specific versions of yoursoftwareprogram.

JAVAprogrammingiswhatisknownasobjectoriented.Thismeansthatasingleobjectisablebeapartofagroupofotherobjectsaswellasinheritcodewhichiscommontothatclass,amongothernumerousfeatures.Ratherthanthetraditionalprocedural“verbs”,objectsarereferredtointermsof“nouns”whichsomeoneismore likely to relate to. A method may be looked upon as one of the object’sbehaviorsorcapabilities.

Moreaboutobjectorientedprogramming(OOP)

Object oriented programming, referred to by programmers as OOP, is a model oflanguagethat isbuiltarounddatainsteadof logic,andalsoobjects insteadofactions.Afterthe input data is processed it then gives output data. OOP takes the view of the object ofinterest tobeworkedwithover the logic that isneededinorder tomakethemwork.Theseobjects,forexample,canvaryfromcomputerwidgetstoabuildinganditsfloorstohumanbeings.

InOOP,thefirststepistolocatealloftheobjectstheprogrammerwishestomanipulate,andthentoidentifyhowthesespecificobjectsareabletorelatetoeachother.Thisprocessisusually referred to as data modeling. Once a programmer has selected an object to beidentified, theprogrammerwould thengeneralize it.For example, thisoneparticularbookwould then stand for allbooks.Thisgeneralizationdefines the typeof information that theobjectholds aswell as the logic sequenceswhichare able toworkwith it. Every separatesequenceisreferredtoasamethod.ObjectswithinOOPcommunicatewithmessages,whichare interfaces that are clearlydefined.The rules, parameters, and concepts utilized inOOPofferthesebenefitsthatallprogrammersneedtobeawareofandgrasp:

Thedataclassconceptmakesitpossibletodefineobjectsubclasseswhichhaveallorat leastsomeof thekeygroupcharacteristics.ThisparticularqualityofOOP,called inheritance, reduces development time, inheritance ensures more acutelyaccuratecoding,andinheritancealsorequiresamorethoroughdataanalysis.

Page 11: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

Aclassdefinesonlyspecificdata.Whenthatobjectorgroupisrunning,thecodewill not mistakenly access data from the program that is not intended. Thisparticular conceptual characteristic known as data hiding avoids unintended datacorruptionandprovidesgreatersystemsecurity.

Sincethedefinitionofacertainclassisnotonlyabletobereusedbyaprogramthatitisespeciallybuiltforbutalsobyotherprogramsthatareobjectoriented,itis thenmoreefficientlydistributedfornetworkuse.(Refer tothewriteonce,useanywhereconcept)

Thedataclassconceptenablesaprogrammer tobuildanykindofnewdata thathasnotalreadybeendefinedwithintheparametersofthelanguageitself.

Gettingtounderstandtheuseofapplets

JAVA produces browser run programs which are called applets. Although applets arebecoming more and more obsolete as time goes on, they are used to facilitate objectintercommunication byWeb users and graphical user interface, orGUI.Before therewereJAVA applets available, Web pages and sites were normally not interactive and otherwisestatic. Suchcompetingproducts suchasMicrosoftSilverlight andAdobeFlashhavemadeJAVAmuch less popular, since it once dominated the market. JAVA runs its applets on aninternetbrowserusingtheJVM.TheJVMthentranslatesthespecificcodeintowhatisknownas native processor instructions, also known as native code. This translation allows forindirect platform program or indirect Operating System (OS) execution. JAVA VirtualMachinesuppliesmostof thecomponents thatarenecessary inorder to runbytecode.Thisbytecode is normally significantly smaller than other programming languages in whichexecutableprogramsarenormallywrittenthrough.Basically,whenusedonline,JAVAallowsfor applets to be used and also downloaded through a browser. This process allows thebrowser to access a feature or perform a function that would normally not be availablewithouttheapplet.TheprogramorappletmustbedownloadedorinstalledbytheuserbeforetheuserisabletofullyaccessandusetheJAVAprogram.

HowJAVAdiffersfromJavaScript

WhilebothJAVAandJavaScriptareprogramminglanguagesusedtodevelopfeaturesorapplications on aWeb page, it is highly important that JAVA should not be confused withJavaScript. JavaScript originated at Netscape and is a little easier to learn than JAVA.JavaScript is also interpreted at a higher level than JAVA, meaning that JavaScript uses aprogramminglanguagewithastrongabstraction,ortechniqueformanagingthecomplexityof computer systems, from the details of the computer. JavaScript, however, does lack thespeedofJAVAbytecodeaswellassomeoftheportability.ThismeansthattherunningspeedofJavaScriptisconsiderablymuchslowerthanthatofJAVA.JAVAappletsareabletorunonjustaboutanyoperatingsystemwithoutnecessitatingrecompilationandhavenovariationsorextensionsthatareuniquetoanoperatingsystem.ThisiswhatmakesJAVAgenerallythoughttobethemoststrategiclanguageindevelopingWebapplications.JavaScript,however,may

Page 12: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

beusefulinextremelysmallapplicationsthatrunoneithertheWebserverortheWebclient.Byfarandwide,themosthighlyrecognizabledifferencebetweenJAVAandJavaScriptis

the type of applications in which they are used to create. JAVA programs are utilized forapplicationswhichareeitherinitiatedthroughaWebpageorrunfromacomputer ’sdesktop.Theseprogramsare standaloneprograms thatusuallyopenacompletely separateprogramwindow.Inaddition,acomputerisabsolutelynotabletorunJAVAapplicationswithoutJAVAhavingbeeninstalled.JavaScriptisalwaysincludedinalloftheuptodatebrowsers,however,and will start the JavaScript on a Web page when the Web page is loading, as long asJavaScripthasbeenenabled.

Whenaprogrammer isusing JavaScript code, JavaScript’s “thinking”andcalculationsareconsistentlyalwaysperformedon theclient side.Theclient side refers to thecomputerwhere the page on the Web is initially accessed. On the other hand, JAVA programs donormally perform all of themain “thinking” and the calculations process within a certainJAVA applet that must first be downloaded, or on the server side. Because of the fact thatJavaScriptrunsontheclientside,itusuallyrunsfasterthanJAVA,andisattimesevenalmostinstant,dependingonthespeedoftheconnection.SinceJAVAprogramsarerunontheclientside, it takes just a bitmore time in order to process, but usually only several seconds ormore.

JavaScript uses significantly lessmemory than JAVA, evenvery, very littlememory insomecases in fact, inorder todo itsprocessingandalsoperformcorrectly.Becauseof itslowermemoryrequirementsanditscapabilityofofferingsomanyvariedWebpagefeatures,JavaScriptisaverycommonprogramlanguageutilizedinmanyvariouspagesontheWebatthis present time. JAVAprograms, however,may sometimes require that a lot of computermemorybeusedinordertofunctionproperly.Thisrequirementcanabsolutelycauseanotherprogramtorunatamuchslowerrateandevencausethecomputertoslowdownaltogether.So evenwhile JAVAprograms have the innate ability to be developed to do various, oftenpowerfulthingsbecauseitutilizesahighermemoryusage,itcanalsobeaspeeddisadvantageinsomerespects.

Page 13: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language
Page 14: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

CHAPTER2

HowJAVAisBeingUsedToday

Asof2016,JAVAisnowbeingutilizedbyover9millionsoftwaredevelopersaroundtheglobeand isalsooneof themostutilizedprogramming languagesavailableespecially forclient-serverapplications.Regardlessofacomputer ’sarchitecture,theapplicationsofJAVAareabletobecompiledintocodewhichrunsonallJVMs.JAVAusedtobeidentifiedmainlywith slow performance,with having towait for SunMicrosystems to drop upgrades,withbytecodeinterpretation,andwiththeuseofApplets.Todayhowever,JAVAhasbecomemoreassociated with reliably high performance, with dynamic compilation of hotspots, with amoreandmoreindependentopensourcecommunity,andwithserviceorientedarchitecture,orSOAs,withwebservices,andwithwebapplications.ThischapterwillgointodepthontheusesoftheJVM,theJAVAprogramminglanguage,aswellasJAVAplatforms.

UsingJAVAProgrammingLanguage

The JAVA programming language operates on a high level and was inspired bySmalltalk,andbybothCandC++programming.TheJAVAprogramminglanguagehasalsoborrowed a few ideas from other languages. The syntactic design of JAVA programminglanguage was made to be familiar to those already versed in "curly brace", C-descendedlanguages,buthasstronger(attimesarguably)OOprinciplesthantheprinciplesusedinC++.Also,garbagecollectionisfairlyautomatic,whichdoesawaywiththeneedofthedevelopertohavetofreeupmemoryusedbyobjects thathavebecomeobsoleteandarenolonger inuse.

JAVA is philosophically referred to as a "fail early" language. Since it has syntaxrestrictions,mostprogrammingfailuresarejustnotactuallypossiblewithJavaatall.BecauseofthefactthatJAVAdoesnothaveaccesstopointersdirectly,errorsspecifictoitsarithmeticsimplyjustdonotexist.Utilizingacertainobjectasatypeotherthanwhatitoriginallywasnamed as requires a straightforward cast conversion, which allows the code compiler theobviouschancetodenyprogrammingthatmaybeillogicalandthereforunabletobeused.

AvariednumberofJavaenterpriseframeworksmakeitnecessarytousethedeploymentdescriptors or configuration files,which are usuallywritten inXML in order to identify afunction.This could include the order of the steps that are needed to executewithin a ruleengineorwhichclassmayhandleaparticularrequestinHTTP.Inotherwords,theymustgobeyond the language at hand in order to implement their function properly. JAVA5.0 addsfootnotestothislanguage,andthisallowsforclasses,fields,andmethodstobetaggedwithvaluesthatarethenabletobedevelopedandinspectedatthetimetheyarerun,andmostoftenvia reflection.A lotofsoftwareprogrammersprefer thesefootnotes,usually referred toasannotations,becausetheyareabletosimplifythethingsthatmaybeotherwisecalledoutby

Page 15: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

certaindescriptorsorotherways.TheyarealsoabletomakeitdifficulttointerprettheJavacode, though.Whether or not a footnote or annotation is in place may actually affect theexecutionofthecodeandalsomayaffectitinwaysthatmaynotbecompletelyobviousfromthefootnoteorannotationitself.

Aside from this one singular criticism, JAVA is mainly regarded as the most populargeneral-purpose computer programming language utilized in theworld at the present. Thebenefits of JAVAprogramming language are extremelyvast.Themainbenefits includebutcertainlyarenotlimitedto:

Thebenefitofavastlyimmenseknowledgebase.

Thebenefitofavastlyenormousamountofsoftwaredeveloperswhoarealwaysreadilyavailable.

ThebenefitoffreetoolswhicharewidelyavailableonnumerousplatformssuchasWindows,Solaris,LinuxandMac.AlloftheseplatformsareabletoexecuteandcompileallJavaapplications.

TheJAVAprogramminglanguageitselfhitsauniqueandvaluablepointinthequidproquo between code performance and software developer efficiency. While CPU (centralprocessing unit) cycles continue to steadily reduce in cost factor, software developers,however, usually do not continue to reduce in cost. If anything, the cost of softwaredevelopers continues to rise for many reasons, among them being rising inflation and anincrease of technical education costs. Because of this fact it may inevitably lead to theacceptance of yet an additional piece of abstraction inbetween the CPU opcodes beingexecuted and the software developers themselves – as long as it allows for the softwaredeveloperstobeabletocreateahigherqualitysoftwareandatamuchmoreefficientrate.

ExplanationoftheuseofJAVAplatforms

JAVAisregardedgenerallyintermsofthreedifferentplatforms.Thesethreeplatformswerebrieflyregardedpreviouslyinthisbook.NotethattheJAVAFXEditionisnotincludedhere.

1. TheEnterpriseEdition,alsoknownasJAVAEE2. TheStandardEdition,alsoknownasJAVASE1. And2. TheMicroEdition,alsoknownasJAVAME

Eachofthesedifferentplatformsutilizesacomboofaspecificgroupoflibraries,virtual

machine, and a language version that is used to execute its code. TheEE version containseverything that the SE version does and more, so that means that any EE application canaccess and utilize the entirety of the SE libraries. Also, the EE's use of the programminglanguageisidenticaltothatoftheSE'saswell.ThismeansthattheSEversionisasubsetoftheEEversion.

JAVAMicroEdition,orME,issignificantlydifferentthanitscounterpartsbecauseofthefact that a smalldevice (suchas a smartphone) are just simply thatmuchmore limitedonspaceandcapabilitiesaswell.TheMicroEditionisnotabletobeconsideredasasubsetof

Page 16: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

theStandardEdition(therefore,cannotbeconsideredasubsetoftheEE),becauseofthefactthatanumberof its librariesonlyexist in theMicroEdition. Inaddition, theMicroEditionversion completely eliminates some of the programming language features because of thecomputationlimitationsoftheplatformonwhichitisrun.ExamplesofsomesucheliminatedfeaturesincludeFloatclassandthefloatprimitive.ThismeansthatMicroEditionrequiresaslightly different set of tools than the Enterprise Edition version and the Standard Editionversion.Withsuchdeepseateddifferencesinthedevices,itmakesthecompleteportabilityofcodemuch less realistic in themicro space. In fact, a lotof JavadevelopersviewMEasacompletelydifferentanimalaltogether,almostaseparateentityeven.

WhattoexpectwhenusingtheJAVAVirtualMachine(JVM)

JAVA source code has to translate into executable platform native code at some pointalongtheway.Typically,doingsorequirestheuseofatwo-stepprocess:

1. ThesoftwaredeveloperneedstocompilethesourcecodetoJAVAcode.2. TheJVMthenhastotranslatethatinformation,fortheplatforminuse,intothat

platform’snativecode.Thesecondstepwasoriginallyexecutedbyinterpretation,orbytakingeachsingleJAVA

VirtualMachine(JVM)instructionandconvertingthatinstructioninaninstanttooneormoreinstructionsnativetotheplatform.Thenafterthatisaccomplished,thejustintimecompilers,referredtobysoftwaredevelopersasJITcompilers,converttheprogramfrombytecodeontheJVMintocodenativetothatparticularplatformastheprogramisrun.Thereareseveralways to achieve this conversion at this present time. SunMicrosystem's HotSpot compilerinitializesthisprocessbytranslatingthecodeandthenprofilingitatruntime,optimizingandcompiling theparticularareas thathavebeenconcluded tobe the firstpriority inorder forthat program to continue towork efficiently. IBM’s "mixedmode interpreter" of its JVMsoperatesinaverysimilarfashion.Theseprocedurescircumventthestartupperformancelagentailed by utilizing JIT compilers on the whole program, but then this also means thatperformance is accumulated, arriving consistently over a period of time, when crucialsectionsofcodearedetectedandmadetoworkmoreefficiently.Becauseofthisprocedure,client applications are far less benefitted by this approach than the long-running serverprocesses.

WhattoexpectwhenusingJAVAwithoutusingtheJAVAVirtualMachine

ItisentirelypossibletorunJAVAwithouttheuseofaJAVAVirtualMachine.SinceJAVAsource endsupbecomingbytecode, thenwhich in turnbecomesplatform-native code, as itstands,thiscanactuallybeaccomplishedallatonetime.TheGNU(GNUrecursivelyreferstotheterm“GNU’sNotUnix”)CompilerforJAVA,alsoreferredtoasGCJ,allowsforanupfront, one-time, compendiumof JAVAcode to a command that is able to be executed on asingularplatform.Thoughthereisenoughinformationtocompilecommandlineandserversideapplicationswhenusingthisprocess,itisnotactuallyabletoallowforthesupportofthe

Page 17: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

AbstractWindowingToolkit (AWT),whichwould obviously render it unsuitable forAWTprogrammingandalsoSwingGUIprogrammingaswell.

This obvious downside to using this process is that cross platform code ends upbecomingboundtoonlyoneplatformandonlyinonesinglestep.What ismore, thatstatictype of compilation does not automatically negate the workings of the HotSpot's dynamiccompilation.The author of said compilation didwork on a piece of research inwhich theGCJperformancegainwasconcludedasbeingfewerthanamere5%abovetheperformancegainof theHotSpotversion.Evenstill,GCJdoeshavetheperformancegainadvantageandhastheabilitytosolvecrucialproblems,suchastheabilitytosuccinctlydeployaparticularJava application that is completely able to be ran regardless of which version the JVM isrunningandwhetherornotit’sevenavailable.

WhattoexpectwhenusingtheJAVAVirtualMachinewithoutJAVA

ItisalsoabsolutelypossibletogetstraighttotheJVMlevelimmediatelyandsuccessfullybypass the JAVA language entirely. C-to-JVMbytecode compilers are already in existence;compilers like theAxiomaticMulti-PlatformC,which iscommercialandsuppliesapartialversionofANSIC.Whatismore,theprogressofthemanipulationofJAVAbytecodeallowsforthecreationofclassesatruntimethatarecompletelyexecutableinJavaapplications.Thismeans that what youwill beworkingwithwill no longer be JAVA, but insteadwill be aneffectiveformofprogramminglanguageusedforassemblyintheJAVAVirtualMachine.

ExplanationoftheJAVACommunityProcess

There is a JAVA community that exists beyond virtualmachines, beyond libraries, andbeyond programming language. In spite of the overwhelming amounts of software that isconsideredtobeopensourceandutilizedbyandwrittenintheJAVAprogramminglanguage,there is a continuously obvious and open conflict at large between the open sourcecommunityandtheJAVAcommunity.

TheJAVACommunityProcess,sometimesreferredtobysoftwaredevelopersassimplythe JCP, was established in 1998. The JCP is the formalized mechanism by which anyinterestedpartiesmaybeallowedtoofferinputinthedevelopmentofstandardtechnicalspecsof the JAVA technology. It is open to the public and anyonemay become amember of theJAVA Community Process by simply submitting the appropriate form available at theirwebsite.

A hugely varied number of JAVA aspects exist entirely without the JCP’s standardizedacceptations.A lot of independent projects have gained in size enough to actually competewiththeactualJCPbenchmarksinthelevelofawarenessinthemindsofJCPconsumers.Asawhole though, these independent projects have also been able to be quick in adapting tomodifications completely without the use of JAVA and also simultaneously utilize the bestfeaturesofthosemodifications,asinthefeatureAJAX,whichisafeaturethatsimplifiescode.ThisisaDirectWebRemoting,orDWRprojectortheRails-inspiredTrailsproject.

Page 18: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language
Page 19: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

CHAPTER3

IntroductiontoJAVAProgrammingBasics

WhenitcomestolearningJAVAprogramminglanguage,oranyprogramminglanguagefor that matter, there are five basic concepts you must understand before you get started.Thesefivebasicconceptsinclude:

1. Variables2. DataStructures3. ControlStructures4. Syntax5. Tools

Each of these five conceptswill be thoroughly explained in this book on a beginner ’s

level,toensurethattheyareunderstood.

Variables

Variablesareactually thecornerstoneofanyandallJAVAprogramsyouwill run into,and so they are the cornerstone of the JAVA programming language in and of itself. Bydefinition,avariableincomputerprogrammingissimplythelocationofstorageaswellasthe associated name that symbolizes what an unknown or known piece of information orquantitymay be. In other words, a particular value. Simply put, a variable is amethod ofstoringsomekindofinformationforuseatalatertime,andisretrievablebyreferringtoanameorwordwhichwilldescribethesaidinformation.

Forexample,let’ssayyouchoosetonavigatetoacertainwebsite,andtheveryfirstthingthiswebsitedoesisaskyouwhatyournameis.Thisisnormallydoneinordertoinstatesomeformof human familiarity – upon your next visit, thatwebsitewill call you by name.Thepersonwhobuiltthewebsitewouldcreateasmalltextboxonthescreenthatwouldaskyouforyournameandthatsmall textboxwouldrepresentavariable.Thepersonwhobuilt thepagemaydecidetocallthatsmalltextboxsomethinglike“VisitorName”,andthatwouldbethesymbolicwordornameforthesmalltextboxvariable.

So then after you type your name into the small text box, your name is then stored asinformation in avariable called “VisitorName”. This informationwouldbemade readilyavailable to thepersonwhohadbuilt thepage,or theprogrammer.Thenthispersonwouldhave the ability to revisit the page and ask “What value does the variable “Visitor Name”contain?”, and the programwould answer the programmerwith the value ofwhatever youmayhavetypedintothatsmalltextboxthatyousawwhenyoufirstvisitedthepage.

Page 20: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

ThisconceptisusedconstantlyoverandoveragainthroughoutJAVAprogramminganditisalsosuperpowerfulinitsprogramming.ThisparticularconceptiswhatmakesTwitterand Facebookwork; it iswhat allows you to pay your bills using your online banking orbankingapp,anditisalsowhatmakesitpossibletoplaceabidonsiteslikeeBay.Variablesenabletheprogrammingworldtokeepspinning‘round,asitwere.

Okay,nowitistimetogetalittlebitmorespecific.Therearedifferenttypesofvariableswhen it comes to programming using the JAVA programming language. If a programmerwere to choose to store your name in a variable, your namewould be stored as a type ofvariable called aString. Or, perhaps theprogrammer alsowanted to storeyour age - thatwouldbestoredasatypeofvariableknownasanInteger. Finally,maybetheprogrammerwantedtostoreyouryearlyincome–yourincomewouldthenbestoredasatypeofvariablereferred to as a Double. Just to recap, there are three different types of variables beingcoveredhere:

String

Integer

Double

So,whatexactlyconstitutesaStringvariable,anIntegervariableandaDoublevariable?

WhenusingJAVA, theprogramminglanguageneeds toknowwhatsortof informationyouwill be going to store within a particular variable. The programming language needs toknowthisbecauseJAVAiswhat isknownasastrongly typedlanguage. Basically, inorderforalanguagetobeweaklytyped,thatmeansthatthetypesofallofthevariablesareinferred,orknownatthetimeofcompilation.Astronglytypedlanguage,however,doesnotallowfortheuseofonetypeasanothertype,meaningthatitutilizesdifferenttypesofvariables.Thisiswherestring,integer,anddoublevariablesareputtouse.

StringVariables

Typing in JAVA programming lets the programming language know for sure that theinformationthatisbeingstoredwithinavariablewillbeconcretelydefined.WhenastringisreferredtoinJAVA,wearelookingatthedataasifitweresimplyasentencecomprisedofwords in the English language. A String only specifically represents letters placed in aspecificorder.AsintheEnglishlanguage,stringvariablesconstituteaseriesoflettersplacedinaparticularorderwhichgivesthatseriesoflettersaveryspecificmeaning.

In the way that string variables are made more understandable by comparing it toeverydaylanguage,addingtwostringstogetherworksverymuchthesameway.Ifyouhavetwostingvariablesandtheystored,forexample,thedata“Visitor”and“Name”,iftheywereaddedtogetheryouwouldgettheString:“VisitorName”.

IntegerVariables

InJAVA,anintegervariablemeansthatyouhaveanumberthatdoesnotincludedecimal

Page 21: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

places. Thismeansawholenumbersuchas23or -784. InJava,when it is specified thatavariableisaninteger,itissimplynotallowabletostoreanythingbutawholenumber.

Forexample,ifyouwanttoaddtwonumberstogether,thenumber35andthenumber5.Javaactuallybehavesreallydifferently,itdependsupontheexacttypeofvariablebeingusedtostoringthisdata.Thenadding35and5togetherwillresultintheinteger40.Insteadofjustcompoundingthetwo,asastringwould(when35and5areaddedtogetherinastring,youwouldget355),theintegersareaddedtogetherinsimplemath.

TheDoubleVariable

ThedoublevariableinJAVAwilleitheruseverybignumbersorverylittlenumbers.Theminimumvaluesaswellasthemaximumsarerespectivelyboth17andthen307zeros.

Adoublevariablecanbeusedtoalsocontainpointvaluesthatareknownas‘floating’.Afloatingpointvalueisbasicallyanynumericalvaluewithadecimalpoint.

The bottom line is that having a typewill help you to start to understandwhat sort ofthings you are able to do with the information contained within the variable. Types ofvariables are really powerful andmake sense ofwhat is andwhat is not allowedwithin acertainvariablegroup.

HowdatastructuresareusedintheJAVAprogramminglanguage

A data structure in computer science is a specific method of organizing and storinginformation inacomputer so that itmaybeused in themostefficientmannerpossible.Tobetter explain data structures, let’s use the concept of a list of contacts. Usually, a list ofcontacts contains numerous contacts which could shrink or grow at any time. For thisexample,let’ssayyouneedtokeepfivecontactsinorder.Ifyouweretoattempttorepresentthosecontactsasvariablesinaprogram,youwouldneedtoknowdatastructure.

In this instance,youhavea listofcontacts.WhenusingJAVAprogramming, there isadatastructurecalledalist.Thisiswhatthecodelookslike:

1. Listcontacts=newArrayList();

Donotworryaboutthesymbolsjustyet,thatwillbecoveredlaterinchapter5ofthisbook.Allyouneedtoknowatthemomentisthatthereisawaytostorealistintoadatastructure.InaListdatastructureyoucaneasilybothadditemstoyourlistandalsoremoveitemsfromyourlist.

contacts.add("JohnDoe([email protected])");contacts.add("JaneDoe([email protected])");

Whencreatingadatastructure, it issupremelymoreefficient tocreateonevariable,as

shownabove,insteadofadifferentvariablethatyouwouldneedtowriteoutforeverysingleitemonyour list.Becauseyouonlycreatedonevariable,contacts.add(RandomContact) thatmeans thatyourcode ismoredynamicand flexible. In this instance,dynamic refers to thefact that the outcome of the program is able to change depending on which variables areinputted.Youideallywantyourcodetoberenderedasdynamicaspossible,andyoualsowant

Page 22: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

yourcodetohavetheabilitytohandlealotofdifferentsituationswithoutneedingtohavetokeepwritingmoreandmorecode,overandover,astimegoeson.Basically,datastructureisjustawaytoavoidhavingtocreatemorevariablesthanisabsolutelynecessary.

HowcontrolstructuresareusedintheJAVAprogramminglanguage

Acontrolstructureisablockofprogrammingthatanalyzesvariablesandchoosesaflowbasedongivenparameters. It is thebasic processwheredecisions aremade in computing.Flowcontrolregulateshowacomputerwillrespondwhenit isgivenspecificconditionsaswellasspecificparameters.Thismeansthatwhileaparticularprogramisrunning,thecodeisreadbythecomputerlinebyline.Thisprocessisknownas“codeflow”.Asthecodeisreadfrom top to bottom, itmay reach a point that requires some amount of a decisionmakingprocess. This decision could result in the code jumping to a different part of that specificprogram,anditmayrequirethatacertainpieceofcodeisrerun,oritmayjustskipalotofcodeinresponse.Thisprocesscouldbeequatedtoa‘chooseyourownadventure’book.Youreachpage12of thebook, andyouhavea choicebetween selectionAand selectionB. Acomputerprogramworksmuchthesamewayexcepttheprogramhasastrictsetofrulestoabideby,givenbytheprogrammer.Thedecisionthattheprogrammakeseffectstheflowofcode,andthatisknownasacontrolstructure.

HowSyntaxisUsedwithintheJAVAProgrammingLanguage

Thesyntaxof theprogramming languageofJAVAis really just simply thesetof ruleswhichdefinethecombinationsofsymbolsconsideredtobepreciselystructuredprogramsinthatsetlanguage.Syntaxisbasicallyaparticularlayoutofsymbols.InJAVA,anexampleofthiswould be curly brackets { } or round brackets ( ). For example,when you look at anemailaddressyouareabletoidentifythefactthatitisanemailaddressbecauseofthesyntax.Youmayalso identify this as its structureor simplyby ‘theway it looks’.Youare able torecognizeanemailaddressanddifferentiateitfromawebsiteaddressbecauseofthedifferentsyntaxthatliestherein.SyntaxinJAVAprogramminglanguageissimilar.Therearerulesinplace, and when followed, those rules allow programming language to comprehend thefunctioning software and also allows you to create functioning software. Youwill receiveerrorsifyoudonotabidebytherulesofaprogramminglanguages’particularsyntax.

WhenusingJAVA,therearefourspecificstepstothesyntaxofcreatingavariable.Theyareasfollows:

1. The firstpart to the syntaxofcreatingavariable is theuseof thewordString,

whichisthevariable’stype.AStringinthisparticularcaseallowsthestorageofregularlettersaswellasthestorageofspecialcharacters.

2. Thesecondparttothesyntaxofcreatingavariableisusingthevariablename.A

variable name can be made up of numbers and letters, but the only specialcharacters they are allowed are underscores. The first letter in variable namesarenormallylowercase,whichisnotnecessarilyamust,butiskindofaruleof

Page 23: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

thumbintheJAVAprogrammingworld.3. Thethirdparttothesyntaxofcreatingavariableisimplementingthevaluethat

the particular variable holds. In JAVA strings are clearly defined by placingquotesaroundregularnumbers,letters,andspecialcharacters.

4. Thefourthandfinalparttothesyntaxofcreatingavariableisimplementingthe

mark of completion. In JAVA, a semi-colon is used.Although there are a fewexceptions,nearlyallofthelinesofaJAVAcodewillendinasemi-colon;muchlikeaperiodattheendofasentence.

ExplanationoftheuseoftoolsintheJAVAprogramminglanguage

Atoolthatisusedinprogrammingisalotlikeanyothertoolthatweaspeopleuseinthatithelpsyouaccomplishyourgoalmoreefficiently–exceptthatJAVAtoolsareonlyusefultoJAVAprogrammers,ofcourse.InJAVA,atoolisapieceofsoftwarethatenablesyoutogetyour program completed more quickly. There is a vast array of tools used in JAVAprogramming,butforallintentsandpurposes,thisbookwillfocusontheIDE.

AnIDEisessentiallyapieceofsoftwarewhichwillbasicallymakecodinga loteasierandisthemostessentialtoolofeveryprogrammerontheplanet.IDEscheckthesyntaxofacodetomakesuretherearenoerrors.IDEsalsoorganizeyourfilesandgiveyouaspecificwaytocomprehensivelyviewthem.IDEstendtoincorporatecodecompletion,whichactuallyfillsincodeforyou,insomecommonscenarios.IDEsenableeasynavigationthroughcode.TherearemanymoreadvantagesofusinganIDE,thoughthemostusefularenotedhere,andyouwillbecomemorefamiliarwithusinganIDEonceyousetyoursupfollowingthesimplestepbystepguideoutlinedinchapter5ofthisbook.

Page 24: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language
Page 25: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

CHAPTER4

FamiliarizingYourselfwithJAVACommands

ThevastamountofJAVAcommandsarefartoonumberedtoincludeeverysingleoneinthe list here, but this chapter includes a visual of some of the most common and usefulcommandsavailabletodate.Thediagramsinthischapteraresuppliedasanintroductiontothenameofthemostbasiccommandsandalsoasavisualreferenceasyoumakeyourwaythrough the next chapter, so you will have numerous ways of checking your work andmaking more sense of what you have read thus far. These JAVA commands are in noparticularorderreally,withtheonlyexceptionbeingtheveryfirstcommandexplainedinthislist,helloworld.TheHelloWorldapplicationisbyfarandwidethemostcommonstartingpoint for every single newbie programmer in the world. There are literally millions ofdifferent “Hello World!” application codes out there, written by just as many beginnerprogrammers.

AnintroductiontotheHelloWorldapplicationcodeintheJAVAprogramminglanguage

There are three primary components that make up the application known as “HelloWorld!".ThesecomponentsconsistoftheHelloWorldAppmainmethod,theclassdefinition,and the source code comments.Unless you are already familiarwith how to program andutilize commands in JAVA, the further implications of “Hello World!” will be able to beunderstood only after you have completed reading the rest of the “Hello World!”programmingmaterial in thisbook.Below, thekeyword“class” (beneath the firstarrow inthefirstline)launcheswhatisknownastheclassdefinitionwhichgivesmeaningtotheclass“name”.Italsolaunchesthecodeforeveryindividualclasswhichappearsinbetweeneachsetoftheopeningandclosingcurlybracesinthediagrambelow.Forthoseofyouwhomaynotalreadybefamiliarwithwhatcurlybracesare(“{“and“}”),theyareasymbolusedtoexecutecodeinJAVA.InJAVA,everysingleapplicationwillbeginwithaclassdefinition,asyouwillseeinthefollowingchapter.Also,whenutilizingtheJAVAprogramminglanguage,a“main”methodmustbeused ineveryapplication.Lastly,sourcecodecommentsareonlyuseful toother programmers in order for them tomore fully understand the code.The source codecommentsarecompletelyignoredbytheprogramcompiler.

AnintroductiontoIntegervariablesintheJAVAprogramminglanguage

WhenyouarewritingcodewiththeJAVAprogramminglanguage,everysinglevariablefirsthastobedeclaredpriortoitsabilitytobeusedinthatcode.WhenworkinginJAVA,thisis referred toasbeing statically typed.Whenaprogrammerdeclaresavariable thatmeansthatthevariable’snameandthevariable’stypearebothstatedveryclearlyinthecode.When

Page 26: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

the variable’s name and the variable’s type are both clearly stated, this lets your programknowthat,inthatparticularcode,thereisaninitialvalue.Italsoletsyourprogramknowthatthere is numerical data being held and that there is a particular field named“yournamedobjecthere”thatexistswithintheprogramandcode.Thedatatypeofavariablecompletelydeterminestheparticularoperationsthatareabletobeperformedonitandalsodeterminesthevaluesthevariableisabletocontain.

AnintroductiontousinganObjectintheJAVAprogramminglanguage

Asstatedpreviouslyinthisbook,JAVAisaprogramminglanguagethatisveryheavilyobject oriented.When a programmer isworking in the JAVAprogramming language, thenthatprogrammerutilizesobjectsinordertocompletethecodetaskathand.Theprogrammerwillcreatethoseobjects,modifythoseobjects,movetheobjectsaroundwithintheprogram,change the objects’ variables, call the objects’ methods, and then will also combine thoseobjects with other objects in the code as well. When programming with the JAVAprogramming language, the programmer will develop classes within the code, theprogrammerwillcreateobjectsoutofthoseparticularclasseswithinthatcode,andthentheprogrammerwillusethoseclassesinthecodewithotherclassesandotherobjectswithinthecode.

WhenaprogrammeriswritingcodeinaJAVAprogram,theprogrammerwilldefineaset of specific classeswithin the code.Asyouwill learn further in the next chapter of thisbook,classesaresimplyjust the templates thatareusedbyprogrammers inorder tocreatetheobjectswithintheprogrammer’scode.Theobjectsthattheprogrammerchoosestocreate,which are also known as instances, are self-contained aspects of a particular program thatalsohasrelativedataaswellasfeatures.Aprogrammerwill,forthemostpart,usethatclasssimplytocreateanddefineinstanceswithinacodeandthentheprogrammerwillworkwiththoseparticularinstanceswithinthatonecode.Hence,inchapter5youwilllearnhowtobeabletocreateanynewobjectfromanyclassthatyouhavecreated.

In order to create a brand new object, the programmermust first use a new operatoralongwiththenameoftheparticularclass,andthatclassistobeusedbytheprogrammerandtheIDEasacomprehensive template.Keep inmindasyouproceed thatparenthesesalwaysfollowthenameoftheclass,nomatterwhat.Thiswillbeshowninthenextchapteraswell.Theseparenthesesareveryimportant,somakedoublysureyoudonotleavethemoutorelseyourcodewillnotexecuteproperly,ormaynotexecuteatall.Theparenthesesfollowingthenameoftheclasscanevenbeleftempty.Ifyouleavetheparenthesesfollowingthenameofthe class empty, this means that you will have successfully created the most basic objectpossibleinyourcodeaswellasthesimplestobjectpossibleinyourcode.

When you have successfully created an object in your code, you will probably thendecidetoutilizethatobjectinwritingyourprogram.Whenyouastheprogrammerdecideonhowyouwish touseyourobject,you thenmayhave tocalloneof theobject’smethods inorder to perform a specific action, you may choose to use a certain value of one of theobject’sfieldswithinthelinesofcode,oryoumaychoosetoevenchangeoneoftheobject’sfieldsaltogether.

Page 27: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

AnintroductiontousingaclassintheJAVAprogramminglanguage

A class is really just a simple template or a simple blueprint when a programmer is

creatingseveraldifferentobjects.Thissimpletemplateorsimpleblueprintwillacttodefineaclass’s behaviors as well as a class’s properties. The JAVA programming language classobjectsshowthebehaviorsaswellasthepropertiesasdefinedbytheobject’sparticularclass.A class in the JAVAprogramming language is able to containmethods aswell as fields inorder todescribehow theobject is supposed tobehavewithina lineofcodeandwithinanentireprogramaswell.

AnintroductiontousingStringDataTypeintheJAVAprogramminglanguage

Even though the compiler in the JAVAprogramming languagepossesses aparticularlyspecialsupportfortheStrings,StringbyitselfisnotaprimitivedatatypeatallsinceStringincludesavastarrayofcharacters.Inthatinstance,Stringisquitesimplyareferencedatatypeand a class in the JAVA programming language. For the sake of reference, examples ofsupport for the String s include such things as performing what is known as performingStringconcatenationandalsoincludestheprogrammerchoosingtoconvertstringliterals-whichisnotaprimitivetype-intoStringinstances,whichareaprimitivetype.WhenusingtheJAVAprogramminglanguage,StringactuallyborrowsfromtheCprogrammingsyntax.This means that the JAVA programming language compiler understands String as what isknownaschararray.Thusly,StringisthenonlyanabstractdatatypeinJAVAthatisactuallymade by a primitive data type char array, a data type essentially borrowed from JAVA’sprogrammingcounterpart–theCprogramminglanguage.

TheanatomyofanifstatementinJAVA

In an ‘if’ statement’s simplest andmost basic possible form, it executes a statement orblock of statements if a boolean expression proves to true. A Boolean value is only oneanswerofeither1or0,eitheryesorno,oreithertrueorfalse.Belowisthesyntax:

Theanatomyofanif-elsestatementinJAVA

Whenan‘if’statement includes theelseclause, iteffectivelyexecutesastatement if thebooleanexpressionistrueorissuesablockifthebooleanexpressionisfalse.

TheanatomyofaLoopintheJAVAprogramminglanguage

InJAVAthereare3differenttypesofloops.Thereisthe‘forloop’,the‘whileloop’andthe‘do-whileloop’.The‘for ’loop(aptly)repeatedlyexecutesablockofstatementsuntilthecondition that theprogrammerwrote returnsas false.The ‘while’ loopexecutesablockofstatementswhentheBooleanexpressionturnsouttobetrueandthe‘while’loopisterminatedwhen that sameexpression turnsout tobe false.The ‘dowhile’ loop isvery similar to the

Page 28: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

‘while’ loop,with theexception that itprocesses thebooleanconditiononlyafterexecutingtheblockofthestatement.

booleanandBooleandefined

Firstofalla ‘Boolean’value isavalue thathas theoptionofonlyoneof twochoices.These choices are either yes or no, either 1 or 0, or either true or false. In the JAVAprogramming language,Booleanvalueshaveavariable type.Forexample:booleanuser=true. Insteadof typing ‘string’or ‘double’or ‘int’, theprogrammersimply types ‘boolean’withalowercase‘b’.

Page 29: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

CHAPTER5

HowtoStartWritingProgramswithJAVAStepbyStep

Becauseofitsflexibility,JAVAisoneofthemostwidelyusedprogramminglanguagesinuse by software developers to date. As previously stated in this book, JAVA is the coreprogramminglanguagethatisusedinthedevelopmentoftheappsforAndroid,andJAVAisreallywidelyusedintheback-endsideofwebdevelopmentaswell.Ifyouhappentobebrandnew to the programmingworld and are looking to or thinking aboutmaking a career orhobbyinthisfield,thefollowingstepbystepbeginner ’sguidewillgiveyouagoodideawhatyoumayexpectwhenlearningtoprogramandwriteyourowncode.Sinceit iseasytouseand sowidely used by all sorts of programs and programmers, JAVA programming is anexcellentoptionfortheinterestedfirsttimecodewriter,evenifyoudonotnecessarilyhaveyoursightssetonafulltimecareerinthisfield.Thefollowingstepbystepguidewillsupplyyouwithareallysolidfoundationinthebeginningbasicsofprogramming,ObjectOrientedProgramming concepts, orOOP, a better understanding of computer science, and even getyou on the right path to succeed in software engineering. This information will alsosuccessfullyputyouaheadof thegame in the instance that a career in computer science iswhatyouarereallyinterestedin.

1. HowtoinstallJAVADevelopmentKit,orJDK.

OpenyourbrowserandsearchforJAVAJDK

LookforanoptionfromOracle.comandclick

ClickontheJAVAJDKdownload

ClicktoacceptlicenseChooseyouroperatingsystem

Minimizeeverythingelseonyourcomputer

Onceitisdownloaded,bereadytoruntheexecutablefile

Clicknextandcheckstatus

JAVAJDKwillstartinstalling

ClicknextandwaitforJAVAtofinishinstalling

Onceinstalled,youcangotoyourCfolderandyoushouldseetwofiles,JDKandJRE

2. HowtoinstallandsetupEclipseIntegratedDevelopmentEnvironment,orIDE

Typewww.eclipse.orginyourbrowser

Page 30: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

OpttodownloadeclipseIDEforJAVAdevelopers

Chooseyouroperatingsystem

You will then be directed to choose your PC’s nearest location, so click thelocationthatisnearesttoyou

Youwillthenbepromptedtosavethezipfile,savezipfile

Openthezipfileonceitisfinisheddownloading

Minimizeeverythingelseonyourcomputer

Thezipfilecontainsafoldernamedeclipse,extracttoCfolder

Oncetheextractioniscomplete,youshouldbeabletoseeeclipseinyourCfolder

OpenupEclipse

Thevery first time that youopenupEclipse, aquestionwill appear thatwill askyouwhereyouwantyourprojectstobesaved-choosealocationorleaveitatCfolderdefault

ClickOKandeclipseshouldopenshortlyInorder tostartabrandnewproject,go tofile, thenclickonnew, thenclickonJAVAproject

Nameyourproject

Capitalizethefirstletterofeachofthewordsinyourprojectname

Clicknext

Clickfinish

Your“MyProject”folderiscreated

3. HowtocreateyourfirstJAVAcodeinEclipseIDEStartanewprojectwithinEclipse

Youwillseethateclipsewillalsocreateasubdirectoryfortheprojectyoucreate,thiswillcontainyoursourcefile

Closeallprojectsexceptfortheprojectyouwillbeworkingon

Rightclickonthesourcefolderoftheprojectyouwanttoworkonandyouwillbeable to add packages to your folder (whenever you add a package itwill add afoldertoyoursourcefolder)

Accessthepackageyoujustcreatedandyouwillbeabletocreateanewclass

Whennamingyourclass,makesurethefirstletterofeachwordofthenameyouchooseiscapitalized

Youwillbeaskedwhichmethodstopyouwouldliketocreate,checkpublicstaticvoidmean

Page 31: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

Pressfinish

Youwillwanttoincludeacommentsectioninyourproject;inordertodothisyouwillfirststartwithaforwardslash,followedbyanasterisk,thenpressenter

This comment section is not executed by your program, it is only info you aredocumentingforyourprogram

Anotherway of creating comments is by first startingwith two forward slashesandpostingyourcommentafter;thiswillnotbeexecutedeither

Whateveryouwriteinthemainclasswillbeexecuted

JAVA has built-in classes to help you program; the most important of these iscalledSystem–makesuretheSiscapitalized

WhenyoutypeSystemthenaperiodeclipsewillautomaticallyknowwhattodo;itshouldlooklikethis:System.

Apopupmenuwill thenappear,showingyoutheavailablemethodsofa label inthissystemclass

Selectthemethodcalledout.println

Once that is selected, you will then be able to click on it and start leaving acomment

When you are ready to run your program, you will then right click on yourprojectand run itasa JAVAapplication–or–youcanclick the“runmyclass”option,whichwillopenthesaveandlaunchpopupWheneveryouscrolloverabuilt-inmethodofclassineclipseeditoritwillgiveyouahelppopupwhichshowsyouwhatthatparticularcodecanbeusedfor

4. ProgrammingwithvariablesandTypesinJAVA

WhendeclaringavariableinJAVAyoumustfirstselectthedatatype

Forexample,let’ssayyouwanttostoreanintegerinavariable

Declarethedatatypeas“int”(forinteger)

Nameyourvariable,sayyounameyourvariablex

Assignvaluetoyourvariable,suchas10

Yourlineofcodeshouldnowlooklikethis:intx=10;

YoucanalsodirectlyuseyourvariableintheSystem.out.printlnline

Instead of typing a message in this line, you can put x as the value; your lineshouldthenlooklikethis:

System.out.println(x);

When this program is run, the value assigned to x,which is 10,will be printed

Page 32: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

wherethexisintheline

Basicdatatypesinclude:

1. abyte–whichisanumberand1byte2. ashort–whichisanumberand2bytes3. anint–whichisanumberand4bytes4. along–whichisanumberand8bytes5. afloat–whichisafloatnumberand4bytes6. adouble–whichisafloatnumberand8bytes7. achar–whichisacharacterand2bytes8. aboolean–whichisatrueorfalseand1byte

Byte,short,int,andlongcanallstoreanumber,theonlydifferenceistheirsize–asindicated

Therangeofallofthevariablesincreaseswithbytesize

Shortexample:shortmy_variable=10;

Whenusingthefloatvariable,youneedtoincludethewordfloatintoyourcode:floatmy_decimal=(float)4.5;

Whenusingthedoublevariable,itisnotnecessarytodifferentiateandshouldlooklikethis:doublemy_double=11.52;

Usecharifyouwanttostoreanyonesinglecharacter:charmy_char=’A’;

Booleancanstoretrueorfalse:booleanis_true=false;

When printed out, only the values of all of these variableswould appear, so inordertheywouldshowupas10,4.5,11.52,A,andfalse

5. WhatitmeanstogetuserinputusingJAVA

ThereisaclassinJAVAcalledScannerwhichenablesyoureceiveinputandlookslikethis:Scannerscan=newScanner(System.in);Inordertobeabletogiveoutputinthesameline,itshouldlooklikethis:Scannerscan=newScanner(System.out);

If you want to gather input from a user, your first line of code should be:System.out.println(“Entersomenumber”);

Youthenwanttonameyourvariableandcontinuecoding:

Intuser_input_number=scan.

Whenyoureachthepartinthesecondlineatscan.,eclipsewillthenpromptyoutomakeachoice,hereyouwanttochoosenextint,sothecompletedsecondlinewilllooklikethis:intuser_input_number=scan.nextint();

Now if you want to print this value, that line of code should look like this:System.out.println(“Theenteredvalueis”);

Page 33: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

Ifyouwant toprintyouroutputwithoutbreaking the line, firstomit the ln afterprint in the line code, then copy your variable, which in this case isuser_input_number, thenpaste it in theparenthesesandrun theprogram,and theverylastlinewillappearthisway:System.out.print(user_input_number);

Whenyou’verunthisprogram,youwillnoticethatitaskstheusertoenteravalue.Let’ssayyouenterthevalueof1,000

Onceyouenterthevalue,theprogramwillconfirmtheenteredvalue

Double works the same way, but you have to make sure you are consistent inchangingtheentirelineofcode,forexample:

Scannerscan1=newScanner(willappearas“System.in”);

System.out.println(Enteradecimalvaluehere);

doubleuser_input_double=scan1.nextdouble();

System.out.println(“Theenteredvalueis”);

System.out.print(user_input_double);

Ifyouwanttotaketextinput,youneedtodefinethevariableasstring

Takethepreviouscodeandjustchangeitscan.nextline,becauseyouareexpectingalinefromtheuserTheentireprogramshouldthenlooklikethis:

Firstline:“Scannerscan1=newScanner(System.in);"Secondline:“System.out.println(“Entersomestring”);”Thirdline:“stringuser_input_string=scan1.nextLine();”Fourthline:“System.out.println(“Theenteredstringis”);”Fifthline:“System.out.print(user_input_string);”

When you run this programyouwill be prompted to enter some string, enter aphraseofyourchoosing

6. GettingtoknowthemathandarithmeticoperatorsinJAVA

First,declaretwovariables,xandyinthisinstance

Thenassignananswer

intx,y,answer;

Assignvaluetoxandy,20and30respectively

Assignvaluetotheanswer,50

Ifyouwanttoprintoutyouranswer,theprogramshouldlooklikethis:

intx,y,answer;

Page 34: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

x=20;y=30;answer=x+y;System.out.println(“Answer=“+answer);When an addition or plus symbol is used in a print function, it is known as aconcatenationorconcatenationoperator

Thecorrectanswershouldbeprintedoutineclipsewithoutyouactuallyhavingtodothemath,aslongasthecodeiscorrect

Inordertoperformasubtraction,allyouneedtodoisreplacetheadditionsymbolwiththesubtractionsymbolinthefourthlineofcode,ortheanswerline:answer=x–y;

When performingmultiplication, x cannot be used as themultiplication symbolbecausexisoftenavariable;instead,anasteriskisused

Allyouhavetodotoperformmultiplicationisreplacethesymbolagain:answer=x*y;

Divisionisalittlebittrickier–ifyoudividealowernumberbyahighernumberandhavedeclaredyourvariableasinteger,theanswerwillalwaysbezerobecauseintegerscannotbedecimals

In the same light,when your variable has been declared as integer and you aredividing a higher number that is not divisible by a lower numberwithout usingdecimals,youwillnotgetanexactlymathematicallycorrectanswereither–ifyoutrytodivideseventybythirty,youranswerwillbetwobecausethatishowmanytimesthirtycangointoseventywhilehavingawholenumberasananswer

Inorder toget accurate answers indivision,youmustdeclareyourvariablesasdouble

Aforwardslashsymbolisusedinplaceoftheothersymbolswhenusingdivision

Onemoreoperator in JAVA is called themodulusoperator and it gives you theremainderofadivision

7. Gettingtoknowtheincrementoperatorandtheassignmentoperator

An increment operator is used when you would like to increase the value of avariableandsomewhatresemblesalgebraintx=10;

x=x+1;

System.out.println(x);

Anotherwayofwritingthiscodetoachievethesamegoalwouldbetoreplacethe+1withtwoadditionsymbols,thisiscalledpostincrementoperation

intx=10;

Page 35: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

x++;

System.out.println(x);

Thesameanswerofelevenhasbeenreachedbothtimesinprint

Ifyouusex++intheprintlineitlookslikethis:

intx=10;

System.out.println(x++);

In post increment operation, the value of xwill only be changed after this plusoperation

Nowyouaregoingtoincreasethevalueofxbyonewhichshouldlooklikethis:

intx=10;

System.out.println(x++);

System.out.println(x);Preincrementoperationplacestheplussymbolsinfrontofthexandincreasesitsvaluebeforetheoperationisperformed

Soifweadd++xinplaceofx++inthepreviouscode,thisiswhatyouwouldsee:

intx=10;

System.out.println(++x);

System.out.println(x);

Theanswertothisisactually:

11

11

Thisisbecausethepreincrementoperator,wherexhadavalueof11andthepostincrementoperator,wherexalsohadavalueof11werecompiled

Nowlet’ssayyouwanttoaddfivetothisvalue,youcandoitbywritingout:x=x+5

Anotherwayofwritingthisis:x+=5

Ifyouwouldliketomultiplythevalueof5andthevalueof10intheequation,youwouldonly need to replace the addition symbol in x+=5with an asterisk – thatshortcutworksformultiplicationaswell–anditwouldlooklikethis:x*=5

Theterm‘equalto’inJAVAisreferredtoasassignmentoperator

Thus,x*=5andx=x*5 isanassignmentoperatorand thisoperatorworksforaddition,subtraction,multiplicationanddivision

Page 36: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

8. HowtoincorporatetheifelseorconditionalstatementsandtheirrelationaloperatorsAconditionalstatementisastatementwhichevaluateswhetheraconditionistrueorfalse,andbaseduponthisconditionexecutesacertaincode

Adoubleequalsign==symbolizesrelationaloperator

Anifstatementlookslikethis:

intx=10;if(x==10){

System.out.println(“yesx==10”);

Thisstatementisbasicallysayingifxisequalto10,thenIwanttorunthiscode.Here,theprogramanswersthatyes,xisinfactequalto10,whichistrue.

Thatmeansthestatementisfollowedandtheconditionwillbeexecuted

Now try to see ifx isequal to20byonlychanging the statementbyplacing thenumber20intheifline

Noanswerwillcomeupineclipsebecausethisstatementisfalseandtheconditioncannotbeexecuted

Anifelsestatementcanexecutewhenanifstatementdoesnotandlookslikethis:

intx=10;

if(x==20){

System.out.println(“yesx==10”);

}else{

System.out.println(“nox!=10”);

Take note of the exclamation point that has taken the place of one of the equalsignsaftertheelseline–thisiscalledanon-equalityoperator

Nowwhenyouruntheprogramagaineclipsewillgiveyoutheanswerthatxisinfactnotequalto10

InJAVA,comparisonoperatorsinclude:

1. ==isequalto2. !=isnotequalto

isgreaterthan3. <islessthan4. >=isgreaterthanorequalto5. <=islessthanorequalto

9. HowtoutilizethelogicaloperatorsinJAVA

Ifyouwanttoevaluatemorethanoneconditionusingasimpleifstatementoranif

Page 37: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

elsestatementyouwillneedtousealogicaloperator

There are two basic kinds of logical operators – the and operator, which issymbolizedbydoubleampersands&&andthesecondtypeiscalledanoroperatorwhichissymbolizedbydoublepipesymbols||

Theandoperator and theoroperator canbothbeused todefine twoconditionssimultaneouslyinbothifandifelsestatements

Theandoperatorcheckstoseeifallconditionsaresimultaneouslytruewhiletheoroperatorcheckstoseeifoneormorethingsistrue

Thesymbolplacedbetweensubjects tellswhichyouareusing,as in linefourofthefollowingtwocodes:

intsubject1=40;intsubject2=60;//&&->AND ||->ORif((subject1>=35)&&(subject2>=35)){

System.out.println(“theconditionistrue”);

Thisconditionistruebecauseboth40and60aregreaterthan35.Nowtrytoincorporateanelsestatementwiththeifstatement,nutfirstchangethevalueofsubject1to20

ifelseintsubject1=20;intsubject2=60;//&&->AND ||->ORif((subject1>=35)&&(subject2>=35)){

System.out.println(“theconditionistrue”);}else{System.out.println(“theconditionisfalse”);

Thisconditionisfalse.Now try running the same program but replace the and operator with the oroperator:

intsubject1=40;intsubject2=60;//&&->AND ||->ORif((subject1>=35)||(subject2>=35)){

System.out.println(“theconditionistrue”);}else{

System.out.println(“theconditionisfalse”);Thisconditionistrue.

10. WorkingwiththeswitchstatementinJAVA

WheneveryouhavetocheckmultipleinJAVA,youwillwanttoutilize

Page 38: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

theconditionsswitchstatement

Youcanalsoswitchstatementsinplaceofifelsestatements

Thebreaksinaswitchstatementacttobreakuptheresponsesyouwill

receivefromtheprogramwhenyourunit

Partofaswitchstatementincludestheuseof‘default’whichworksliketheelseinanifelsestatement

int=90;

//byte,int,short,orchar.switch(score){case90:

System.out.println(“Verygood”);break;

case60:System.out.println(“Good”);break;

case30:System.out.println(“OK”);break;

default:System.out.println(“Gradesarenotdefined”);break;

}Withthevalueoftheintegeridentifiedas90,thecase90statementistrue.When there isnobreakbetweencase statements, theprogramwill default to thenextlowestinsuccessionwhenutilizingthistypeofcode

11. WorkingwiththewhilestatementsinJAVA,alsoknownaswhileloops

WhileloopsarethemostbasicloopsinJAVA

Aloopisapieceofcodeorastatementwhichexecutessomeblockofcodeagainandagainuntilsomeconditionismet

Ifyouwanttoexecutesomecodeagainandagainwithouthavingtorewriteitoverandover,thisiswhatloopisfor:

inta=0;while(a<=10){

System.out.println(a);a++;

}12. ProceedingtothedowhilestatementsinJAVA,alsoknownasthedowhileloops

Page 39: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

Thebasicdissimilarityfromawhilelooptoadowhile loopis thateventhoughloops first evaluate the condition and then execute the code, the dowhile loopsexecutethecodefirstandthenevaluatethecondition

13. HowtolearntoimplementarraysinyourJAVAprogram

Anarrayissimilartoavariablebutitcanstoremorethanonevalueatatime–theonly condition being that even though you can storemore than one value in anarray,ithastobethesametypeofvalues

Forexample,youwouldbeabletostore10integersinanarray,butifyouwantedtostore5integersand5doubles,youwouldnotbeabletodoit

Thisisonewayofdeclaringanarray:int[]myintarray={4,2,1,5,3};

Anotherway is: intmyinarray2[] = {4,2,1,5,3}Thisway is fine but it is not thepreferredwayofdeclaringanarray

Therearethreemorewaysofdeclaringarrays:

1. int[]myIntArray=newint[3];2. int[]myIntArray={1,2,3};3. int[]myIntArray=newint[]{1,2,3};

14. HowtousetheJAVAstringinyourprogram

A string is a sequence of characters and can also be known as an array ofcharacters

InorderdeclareastringinJAVA,youjustusethekeyword‘string’

Youthennameyourstringwhateveryouwouldlike

Thenyouplaceanequalsignafterthat

Thenindoublequotes,placewhateverstringyouwanttoassignandprintitjustthesameasalltheothers:Stringmystring=“HelloWorld”;System.out.println(mystring)

15. IntroductiontousingmethodsinyourJAVAprogramming

The terms method and function can be used somewhat interchangeably, but thepreferredterminJAVAismethod

Amethod is a piece of codewhich executes some logic and you canwrap thismethodwithanameandyoucanrecall thismethodasmanytimesasyouwouldlikewheneveryouwanttouseit

Youcannameyourmethodanythingyouwish

Thisisthemostbasickindofmethod:

Page 40: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

publicstaticvoidmyFirstMethod(){}Theterm‘publicstatic’isknownasthepacifier

Ifyouwanttoprintamessageusingmethod,thisiswhatthesyntaxorcodewouldlooklike:

publicstaticvoidmyFirstMethod(){System.out.println(“HelloYoutube”);

}

Page 41: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language
Page 42: Java Programming - An Introduction, History, and the ...damon.us.to/Downloads/Java Programming - Scott Bernard.pdf · An Introduction to JAVA JAVA is a type of programming language

CONCLUSION

ThankyouagainfortakingthetimeoutofyourscheduletodownloadJAVAProgramming:AnIntroduction,History,andtheFundamentalsForCreatingYourFirstProgram!

Sinceyouhavecompletedreadingthisbook,youshouldnowhaveagoodunderstandingofJAVAprogrammingandalsopossesstheskillstocompletesomebasicJAVAcode!

IfyouhaveenjoyedthisbookasmuchasIhaveenjoyedwritingit,IaskthatyoupleasetakethetimetoleavemeareviewonAmazon.Iappreciateyourpositivefeedback!