Sie sind auf Seite 1von 11

The java programming language

Thejavaprogramminglanguageisahighlevellanguagethatcanbecharacterizedby
thefollowinggivencharacteristics

Simple
ObjectOriented
Platformindependent
Secured
Robust
Architectureneutral
Portable
Dynamic
Interpreted
HighPerformance
Multithreaded
Distributed

Amongallthesepropertiesthemostimportantpropertyisplatformindependency.

Note:Platformisacombinationoftwothingsi.eoperatingsystemandHardware(processor).

Platform Independency in java


javaisplatformindependentandallotherlanguagesareplatformdependent
SupposetakeanexampleofClanguage.writeaCprogramononeOSsay
OS1
andcompileit.
amachinecodewillbegenerated.NowwhatificarrythesourcecodefromOS1toOS2and
runitaftercompilation.Willitrun?
IfthissourcescodecanrunontheOS2thendefinitelyCcanbesaidtobeplatform
independentlanguage,butitsnot.
Heretheproblemwilloccurthat,supposeifwemakeananalogwatchinConthe
OS1(WindowsXP)andcarrythesourcesonOS2(Linux)thenthesourcecodewillgivethe
compilationerroronLinuxbecausesomeoftheheaderfilesofthecompilerareOSdependent.
sothegraphic.hoftheWindowsXPwillnotbesupportedbyLinuxandsotheerrorwillappear.

Note:Everymachinecodeisdependentonitsoperatingsystemenvironment.

Anotherreasonwhichexplainthatallotherlanguagesexceptjavaareplatformdependentis
thatthemachinecodeofallotherlanguageareOSdependentaswellasProcessordependent.
ButthemachinecodeofjavaisnodoubtOSdependentbutalsoProcessorIndependent.
TheperformanceofCwillvaryatdifferentconfigurationbutjavagivesthesameperformanceat
allkindofprocessor.

Need of Java Language


Beforegoingfurtherweneedtorealisetheneedofthejavalanguage.whatweretheproblems
whichthedifficulttosolvebeforejavawascreated?Weallknowthatnecessityisthemotherof

CopyrightOSAHUB2014

invention,sowhatwasthenecessityforwhichjavawascreated?Theanswerliesinthehistory
ofthelanguages.letsstartwiththefirsteverlanguageandthenthesecondthenthirdandso
onandseethatwhatweretheproblemswhichcausetheinventionofJavalanguage.

Machine Language (1st language)


Thefirstevercomputerlanguagewasthemachinelanguageorbinarylanguage.Weallknow
thatcomputeronlyunderstand0or1.Theexecutionofthislanguagewasveryfastasit
directlyinteractwiththehardwareanddoesntneedanytranslator.Butthiswasaverytime
taking,difficultandboringjobasallthecodingwastobedonein0and1.(tryandconvert
yournameintobinarylanguageandyouwillknowhowmuchdifficultitistocoadthousandsof
linesinbinarylanguage.

Assembly Language or Low Level Language(2nd language)


Asthemachinelanguagewasveryhardsotherewasaneedofahumanfriendlycomputer
language.Theideawastocreatealanguagewhichshouldbeprogrammerfriendlyandcanbe
convertedintothemachinelanguageandforthattherewastheneedofatranslator.So
Assemblylanguageandfirstevertranslator(Assembler)wascreated.InAssemblylanguage
certainsymbolswereusedlike
addf
oraddition,
sub
forsubtraction
mul
formultiplicationandso
on.

Note:Assemblerwasusedtoconverttheassemblylanguagetothemachinelanguage

Thislanguagewasprocessordependentbecauseeveryprocessorhaddifferentsymbols.
Toovercomethisproblemstandardswereusedbyallprocessorstoimplementsamesymbols.
BasedonthesestandardsdifferentlanguagesweredevelopedwhichareknownasHighlevel
language.

High Level Language(3rd language)


Aftersettingthestandardhighlevellanguagewerecreated.Differentlanguagewerecreatedfor
differenttypeofapplicationslikeCOBOLwasusedtobuildbusinessapplication,FORTONwas
famousforbuildingthescientificapplications.sothiswastheerawheneachlanguagewas
designedforaspecifictask.Anotherproblemwasthatthesehighlevellanguageswerenot
goodenoughformakingthesystemsoftwares.
Sothereweremainlytwokindofproblems:
I.
Theselanguagewerenotcapableforbitlevelprogramming
II.
Differentlanguageneedtobemasteredformakingdifferenttask

Middle Level Language(C language)


ToovercomethetwogivenproblemClanguagewascreated.Clanguagewasusedforboth,
systemlevelprogrammingandtheapplicationprogramming.ButinlatertimeCwasprovedto
bethebestprogramminglanguageforthesystemlevelprogrammingandfailedinthe
applicationprogramming.Itfailedduetotwomajorproblems
I.
Codelength
II.
Datasecurity
Becauseoftheseproblemsanewlanguagewascreatedknownas
JAVA
.

CopyrightOSAHUB2014

Program execution in java


Unlikeothercompiler,thejavacompilerdonotproducethemachinecodefromthesource
code.ItproduceauniquecodewhichiscalledBytecode.
BytecodeisindependentofOS.Thewholeexecutionofjavaprogramcanbeunderstandbythe
followingdiagram

Letsdiscusstheabovefigure.firstofalljavacompilercreateabytecodebutthisbytecodeisnot
OSdependent,notasingleOSlibraryusedtocreatethisbytecode.Butkeepinmindthatthisis
notthemachinecode.machinecodeisalwaysOSdependent.Nowallweneedtodoiscarry
thisbytecodetodifferentOSandrunit.SosupposewetakeittoadifferentOSsayOS1and
andOS2,wepastethebytecodeonboththeOSandtrytorunit.
Willitrun?
NO.NighterthisbytecodeiscompatibletothenewOSnoritisamachinecodethatcanberun
bytheprocessor.TheOSenvironmentwasntcompatibletothebytecodeoitwasimpossible
thatthebytecodecanberunonthedifferentOStothatitwascreatedin.SOavirtual
environmentwascreatedforthebytecodeinsidetheOSandthisvirtualenvironment.SOnow
wastheneedofsuchasoftwarethatwillcreateavirtualenvironmentinwhichthebytecodecan
beconvertedintoamachinecodebythehelpoftheOSandthesoftwarewhichwasusedfor
thepurposeisknownasJVM(javavirtualmachine).ButJVMareOSdependent,youcantjust
copyandpasteoneJVMfromoneOSandotherOSandrunit.Nowagainthequestionwas
whowillmaketheJVMforeachOS.AsasolutionSunmicrosystemmakeagenericJVMapi
whichtheOSvendorscoulddownloadfromtheirwebsiteandafteraddingafewfile(theirOS
file)theycouldeasilymadeaJVMfortheirOS.
Laterintimeafterjava1.5javaintroducetheconceptofJRE.NowthatlittlepartoftheJVMthat
OSvendorhadtoadd,doesntneedtobedone.ALltheworkisdonebytheSunmicrosystem
only.YoucanjustgototheirwebsiteanddownloadyourOSspecificJREandrunit.itwill
createthejavavirtualenvironmentforyou.
Andsojavasolvedalltheprogrammingrelatedproblems.

Note:JVMisthepartofJRE.

CopyrightOSAHUB2014

Program execution in case of C and other similar language:

Program execution in case of Java programming language:

Compilation in Java

CopyrightOSAHUB2014

Bytecode verification in Java

Basic working of JVM

jvmhasthreestepsforexecutionoftheBytecode

step1:
Thejvmcarrythebytecodetothememoryfortheexecutionpurpose.JVMhasa
programinitwhichisknownasclassloader.classloaderisofthreetype(1)bootstraploader
(2)systemloader(3)extensionloader

step2:
Verifythecode.JVMhasanotherprogramwhichisusedtoverifythecodeforthe
securitypurpose.

step3:
Finalstepistheexecutionstepinwhichbytecodeisconvertedintothemachinecode
bytheexecutionengine.TheexecutionenginewhichisusedforthispurposeisJustintime
compiler

TheJVM:
thegivenfigureshowsthecomponentsofJVM

CopyrightOSAHUB2014

OrganizationofJVM

DetailedOrganizationofJVM

Life-cycle of a java program in five phase(high level overview)

EDITProgrammerwritestheprogramandstoreitondisk
COMPILATIONCompilercreatesthebytecodefromthesourcecode
LOADNowJAVcomesintoplayandclassloaderloadthebytecodeintothememory
VERIFICATIONVerificationisdonetoensurebytecodedoesntviolatesecurity
requirements
EXECUTIONbytecodeisconvertedintothemachinecodebytheexecution
engine(Justintimecompiler)

CopyrightOSAHUB2014

Three approaches of oops

I.
II.
III.

objectbasedprogramminglanguage
Pureobjectorientedprogramminglanguage
objectorientedprogramminglanguage

I.

Object based programming language

itdoesnotsupportthetwofeaturesofoops
(i.)Inheritance
(ii.)RuntimePolymorphism
Exampleofsuchlanguagesarejavascript,vbscript,visualbasicetc.

II.

Pure object oriented programming language


Inthisapproachofoops,foreverytaskweneedanobject.supposeiwanttouse10in
mytechnology,thenistrictlyneedtomakeanobjectofthis10toperformanyoperation
onit.Example:smalltalk

Question
:Isjavanormaloopsbasedlanguageortrulyoopsbasedlanguage?

Variable
Variableisanamegiventoamemorylocation.Justthinkabouttheneedofthevariables.Can
youmakeaprogramwhichtakestwonumbersfromtheuserandaddthemwithoutusingthe
conceptofvariable?No.Weneedtostorethethosetwovaluesandnamethembecausewe
aregonnaneedthemlaterfortheadditionoperation.Ifprocessordoesntknowaboutthe
locationofthosetwonumbersthenitwillbealmostimpossibletofindthosetwonumbersfrom
thestorage.Sotheconceptofvariablewasintroduced.Variablealsoknownascontainersoften
astheirtaskistoreservesomememoryforstoringtheinformation.

Nowsomeproblemsarrivewithvariablewhichcausestheinventionofdatatypeconcept.
supposeinitiallyavariablereserved2byteofmemorybutuserbought100byteofdatawhich
resultthedataloss.Inotherscenariovariablereserved100byteofmemorybutuserbought
only5byteofdatawhichresultthememoryloss.Sotoovercomethisproblem,theconceptof
DataTypewasintroduced.

Data Type
DataTypeconceptwasintroducedtocheckthedatalossandthememoryloss.
Thedatatypegivestwomajorinformationaboutthedata
1. Whatkindofdataisthis
2. howmuchm/mdoesitrequires

CopyrightOSAHUB2014

Question:Inallotherlanguagespriortojavacharusedtotakeonly1bytetostoresowhat
happenedinjavalanguage?

#Rule:Injava,bydefaultallthedatatypearesignedandsoonebitformabyteis
reservedforthe+orFormulaforcalculatingtherange:

2n1

=2n1

1{n=numberofbit)
81
81
2 =2 1
27

=27

1
128=127

#Rule:Injavaeverydatatypehasadefaultvalue.

byte=0boolean=false
f
short=0
float=0.0

d
int=0double=0.0
L
long=0
char=/u0000

CopyrightOSAHUB2014

Note:Injavawewriteeverythinginsideclassandtherearetwoplaceswithinaclasswhere
wecandefineavariableasshownbelow

Note:Javadoesnthaveanygarbagevalueforanyvariable.whichcanbeexplainedfromthe
belowgiventworules

#Ruleforclasslevelvariable:Theruleforthedefaultvalueofcertaindatatypeis
applicableonlyfortheclasslevelvariable.sonoclassnamevariablecanhavethe
garbagevalue

#Ruleforlocalvariable:Youmustinitializethelocalvariablebeforefirstuse.

Question:Whichofthegivenfunctionwillbecalled?

Inabovequestionwecanseethataccordingtopolymorphism10cangoinanyofthefunction
andsoambiguityerrormayoccursoforthisjavamadearulewhichisgivenbelow

#Rule:Bydefaultalltheintegerliteralsaretreatedasinteger(intdatatype)only

Note:Ifweexplicitlywantanintegertobestoredinthelongdatatypethenwehavetoputlin
thesuffixoftheinteger.

likeshow(10l
):thiswillgototheshow(longl

CopyrightOSAHUB2014

Question:

byteb=10
bytec=20
byted=b+c
Whatwillbetheoutputofthisprogram.

Ans:Whilecompilingerrorwillcome.Lookforthebelowgivencodetoknowthereason

Note:whenacalculationisdone,theresultissaidtobetheliteralbeforeitisstoredinthe
destinedvariable.

Sob+cwillgive30andthe30isconsideredasintegerandwhenwetrytostorethisinteger
valueinthebytetypevariable,atypemismatcherrorwillcomeatthecompiletime.

byted=(byte)b+c{thisiscorrect,andwhatwehavedonehereisknownastypecasting}

Question:Whichmethodwillbecalled?

Answer:Thesecondmethodwillbecalledanditcanbeexplainedbythefollowinggivenrule.

#Rule:Bydefault,allfloatingliteralsinjavaaretreatedasdouble.

Note:Ifweexplicitlywantadecimalnumbertobetreatedasthefloatingtypethenwehaveto
putfinthesuffixofthenumber.

likeshow(10.2f
):thiswillgototheshow(floatf

First java program

CopyrightOSAHUB2014

10

#Rule(convention):Alwayskeepthefirstletteroftheclassnamecapital.

Note:Eachtechnologygivesastartingpointfortheprogramandthisstartingpointisafunction
whichisknownasmainfunction.Injavathismainfunctionis

publicstaticvoidmain(String...s)
or
publicstaticvoidmain(Strings[])

#Rule(convention):Alwayskeepthenameofyourjavafilesameastheclassname.

#Rule:Thebytecodeofeveryclassisstoredinaseparate.classfileandnameof.class
filewillbethesameasyourclassname.

Question:Canwemakemorethanoneclassintoasinglejavafile?
Answer:Yes.

Question:Ifwearehavingmorethanoneclassinajavafilethencanwehavethemain
functionineveryclass?
Answer:yes

Explanation
:thebytecodeforeveryclassisstoredinseparate.classfilesoeach
Classisindependent.

#Rule(Convention):Alwayskeepaseparatejavafileforeachclass.

Question:Canwekeepmorethanonemainmainfunctioninoneclass?
Answer:Yes
Explanation:Javaisaoopsbasedlanguage,ithasapropertycalledpolymorphismaccording
towhichaclasscanhavemorethanonefunctionofsamename.Injava,mainisapartofa
classsoalltherulesoffunctionofclasscanbeappliedtomainfunction.

Question:Canwecallmain()functionofoneclassfromotherclass?How?
Answer:yes.Tryityourselfandtrycallingmainfunctionofboththesignatures
1. publicstaticvoidmain(Strings)
2. publicstaticvoidmain(Strings[]s)

Note:Thedifferencebetweenvariablelengthargumentandthearraytypeargumentisthatby
usingthevariablelengthargumentwecancallthemainfunctiondirectlywithoutusingany
argumentbutinarraytypeargumentwemustneedtocreateanarrayandpassitasa
parameter

CopyrightOSAHUB2014

11

Das könnte Ihnen auch gefallen