[Go to site: main page, start]

0% found this document useful (0 votes)
31 views19 pages

Java (Programming Language)

Java is a general-purpose programming language that is concurrent, class-based, object-oriented and designed to have few implementation dependencies. It allows applications to write once and run anywhere on any platform that supports Java without recompilation. Java code is compiled to bytecode that runs on a Java virtual machine, making it portable across architectures. It was created in the early 1990s by James Gosling at Sun Microsystems.

Uploaded by

maomedalid
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views19 pages

Java (Programming Language)

Java is a general-purpose programming language that is concurrent, class-based, object-oriented and designed to have few implementation dependencies. It allows applications to write once and run anywhere on any platform that supports Java without recompilation. Java code is compiled to bytecode that runs on a Java virtual machine, making it portable across architectures. It was created in the early 1990s by James Gosling at Sun Microsystems.

Uploaded by

maomedalid
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java(programminglanguage)

FromWikipedia,thefreeencyclopedia

Javaisageneralpurposecomputerprogramming
languagethatisconcurrent,classbased,object
oriented,[14]andspecificallydesignedtohaveasfew
[Link]
toletapplicationdevelopers"writeonce,runanywhere"
(WORA),[15]meaningthatcompiledJavacodecanrun
onallplatformsthatsupportJavawithouttheneedfor
recompilation.[16]Javaapplicationsaretypically
compiledtobytecodethatcanrunonanyJavavirtual
machine(JVM)[Link]
of2016,Javaisoneofthemostpopularprogramming
languagesinuse,[17][18][19][20]particularlyforclient
serverwebapplications,withareported9million
[Link]
GoslingatSunMicrosystems(whichhassincebeen
acquiredbyOracleCorporation)andreleasedin1995as
acorecomponentofSunMicrosystems'Javaplatform.
ThelanguagederivesmuchofitssyntaxfromCand
C++,butithasfewerlowlevelfacilitiesthaneitherof
them.
TheoriginalandreferenceimplementationJava
compilers,virtualmachines,andclasslibrarieswere
[Link]
ofMay2007,incompliancewiththespecificationsofthe
JavaCommunityProcess,SunrelicensedmostofitsJava
technologiesundertheGNUGeneralPublicLicense.
Othershavealsodevelopedalternativeimplementations
oftheseSuntechnologies,suchastheGNUCompilerfor
Java(bytecodecompiler),GNUClasspath(standard
libraries),andIcedTeaWeb(browserpluginforapplets).
ThelatestversionisJava8,whichistheonlyversion
currentlysupportedforfreebyOracle,althoughearlier
versionsaresupportedbothbyOracleandother
companiesonacommercialbasis.

Java

Paradigm

Multiparadigm:Objectoriented
(classbased),structured,
imperative,generic,reflective,
concurrent

Designedby

JamesGosling

Developer

SunMicrosystems(nowacquired
byOracleCorporation)

Firstappeared May23,1995[1]
Typing
discipline

Static,strong,safe,nominative,
manifest

License

GNUGeneralPublicLicense,Java
CommunityProcess

Filename
extensions

.java,.class,.jar

Website

[Link]([Link]
Majorimplementations

OpenJDK,GNUCompilerforJava(GCJ),many
others

Contents
1 History
1.1 Principles
1.2 Versions
2 Practices

Dialects
GenericJava,Pizza
Influencedby

2 Practices
2.1 Javaplatform
2.1.1 Implementations
2.1.2 Performance
2.2 Automaticmemorymanagement
3 Syntax
4 Examples
4.1 "Hello,world!"program
4.2 Comprehensiveexample
5 Specialclasses
5.1 Applet
5.2 Servlet
5.3 JavaServerPages
5.4 Swingapplication
5.5 Generics
6 Criticism
7 Useonunofficialsoftwareplatforms
7.1 Google
8 Classlibraries
9 Documentation
10 Editions
11 Seealso
11.1 ComparisonofJavawithother
languages
12 Notes
13 References
14 Externallinks

Ada83,C++, [2]C#, [3]Eiffel, [4]GenericJava,


Mesa, [5]Modula3, [6]Oberon, [7]ObjectiveC, [8]
UCSDPascal, [9][10]ObjectPascal[11]
Influenced
Ada2005,BeanShell,C#,Chapel, [12]Clojure,
ECMAScript,Fantom,Groovy,Hack, [13]Haxe,J#,
JavaScript,Kotlin,PHP,Python,Scala,Seed7,
Vala
JavaProgrammingatWikibooks

History
JamesGosling,MikeSheridan,andPatrickNaughtoninitiatedtheJavalanguageprojectinJune1991.[21]
Javawasoriginallydesignedforinteractivetelevision,butitwastooadvancedforthedigitalcable
televisionindustryatthetime.[22]ThelanguagewasinitiallycalledOakafteranoaktreethatstoodoutside
Gosling'[Link],fromJava
coffee.[23]GoslingdesignedJavawithaC/C++stylesyntaxthatsystemandapplicationprogrammers
wouldfindfamiliar.[24]
SunMicrosystemsreleasedthefirstpublicimplementationasJava1.0in1995.[25]Itpromised"WriteOnce,
RunAnywhere"(WORA),[Link]
configurablesecurity,[Link]
incorporatedtheabilitytorunJavaappletswithinwebpages,andJavaquicklybecamepopular,while
mostlyoutsideofbrowsers,thatwasn'ttheoriginalplan.InJanuary2016,OracleannouncedthatJava
runtimeenvironmentsbasedonJDK9willdiscontinuethebrowserplugin.[26]TheJava1.0compilerwas
rewritteninJavabyArthurvanHofftocomplystrictlywiththeJava1.0languagespecification.[27]With
theadventofJava2(releasedinitiallyasJ2SE1.2inDecember19981999),newversionshadmultiple
configurationsbuiltfordifferenttypesofplatforms.J2EEincludedtechnologiesandAPIsforenterprise

applicationstypicallyruninserverenvironments,whileJ2MEfeatured
[Link]
J2SE.In2006,formarketingpurposes,SunrenamednewJ2versionsas
JavaEE,JavaME,andJavaSE,respectively.
In1997,SunMicrosystemsapproachedtheISO/IECJTC1standardsbody
andlatertheEcmaInternationaltoformalizeJava,butitsoonwithdrew
fromtheprocess.[28][29][30]Javaremainsadefactostandard,controlled
throughtheJavaCommunityProcess.[31]Atonetime,Sunmademostofits
Javaimplementationsavailablewithoutcharge,despitetheirproprietary
[Link]
licensesforspecializedproductssuchastheJavaEnterpriseSystem.
OnNovember13,2006,SunreleasedmuchofitsJavavirtualmachine
(JVM)asfreeandopensourcesoftware,(FOSS),underthetermsofthe
GNUGeneralPublicLicense(GPL).OnMay8,2007,Sunfinishedthe
process,makingallofitsJVM'scorecodeavailableunderfree
software/opensourcedistributionterms,asidefromasmallportionofcode
towhichSundidnotholdthecopyright.[32]
Sun'svicepresidentRichGreensaidthatSun'sidealrolewith
regardtoJavawasasan"evangelist".[33]FollowingOracle
Corporation'sacquisitionofSunMicrosystemsin200910,Oracle
hasdescribeditselfasthe"stewardofJavatechnologywitha
relentlesscommitmenttofosteringacommunityofparticipationand
transparency".[34]ThisdidnotpreventOraclefromfilingalawsuit
againstGoogleshortlyafterthatforusingJavainsidetheAndroid
SDK(seeGooglesectionbelow).Javasoftwarerunsoneverything
fromlaptopstodatacenters,gameconsolestoscientific
supercomputers.[35]OnApril2,2010,JamesGoslingresignedfrom
Oracle.[36]

Principles

Duke,theJavamascot

JamesGosling,thecreatorofJava
(2008)

TherewerefiveprimarygoalsinthecreationoftheJavalanguage:[16]
[Link]"simple,objectoriented,andfamiliar".
[Link]"robustandsecure".
[Link]"architectureneutralandportable".
[Link]"highperformance".
[Link]"interpreted,threaded,anddynamic".

Versions
Asof2015,onlyJava8issupported("publicly").MajorreleaseversionsofJava,alongwiththeirrelease
dates:

JDK1.0(January21,1996)
JDK1.1(February19,1997)
J2SE1.2(December8,1998)
J2SE1.3(May8,2000)
J2SE1.4(February6,2002)
J2SE5.0(September30,2004)
JavaSE6(December11,2006)
JavaSE7(July28,2011)
JavaSE8(March18,2014)

Practices
Javaplatform

TheTIOBEprogramminglanguage
popularityindexgraphfrom2002to
[Link]
Java(blue)andC(black)competing
forthetopposition.

OnedesigngoalofJavaisportability,whichmeansthatprograms
writtenfortheJavaplatformmustrunsimilarlyonanycombination
ofhardwareandoperatingsystemwithadequateruntimesupport.
ThisisachievedbycompilingtheJavalanguagecodetoan
intermediaterepresentationcalledJavabytecode,insteadofdirectly
[Link]
analogoustomachinecode,buttheyareintendedtobeexecutedby
avirtualmachine(VM)writtenspecificallyforthehosthardware.
EnduserscommonlyuseaJavaRuntimeEnvironment(JRE)
installedontheirownmachineforstandaloneJavaapplications,or
inawebbrowserforJavaapplets.
Standardlibrariesprovideagenericwaytoaccesshostspecific
featuressuchasgraphics,threading,andnetworking.

JavaControlPanel,version7

[Link],the
overheadofinterpretingbytecodeintomachineinstructionsmakesinterpretedprogramsalmostalwaysrun
[Link],justintime(JIT)compilersthatcompilebytecodesto
[Link],and
isadaptedtotheparticularplatformitistorunonbyaJavavirtualmachineforit,whichtranslatestheJava
bytecodeintotheplatform'smachinelanguage.[37]
Implementations
OracleCorporationisthecurrentowneroftheofficialimplementationoftheJavaSEplatform,following
theiracquisitionofSunMicrosystemsonJanuary27,[Link]
[Link](stillworks
forXP,whileonlylaterversionscurrently"publicly"supported),MacOSX,[Link]
JavalacksanyformalstandardizationrecognizedbyEcmaInternational,ISO/IEC,ANSI,orotherthird
partystandardsorganization,theOracleimplementationisthedefactostandard.
TheOracleimplementationispackagedintotwodifferentdistributions:TheJavaRuntimeEnvironment
(JRE)whichcontainsthepartsoftheJavaSEplatformrequiredtorunJavaprogramsandisintendedfor
endusers,andtheJavaDevelopmentKit(JDK),whichisintendedforsoftwaredevelopersandincludes

developmenttoolssuchastheJavacompiler,Javadoc,Jar,andadebugger.
[Link]
implementationstartedwhenSunbeganreleasingtheJavasourcecodeundertheGPL.AsofJavaSE7,
OpenJDKistheofficialJavareferenceimplementation.
[Link],Sun'strademarklicense
forusageoftheJavabrandinsiststhatallimplementationsbe"compatible".Thisresultedinalegaldispute
withMicrosoftafterSunclaimedthattheMicrosoftimplementationdidnotsupportRMIorJNIandhad
addedplatformspecificfeaturesoftheirown.Sunsuedin1997,andin2001wonasettlementofUS$20
million,aswellasacourtorderenforcingthetermsofthelicensefromSun.[38]Asaresult,Microsoftno
longershipsJavawithWindows.
PlatformindependentJavaisessentialtoJavaEE,andanevenmorerigorousvalidationisrequiredto
[Link].
Performance
ProgramswritteninJavahaveareputationforbeingslowerandrequiringmorememorythanthosewritten
inC++.[39][40]However,Javaprograms'executionspeedimprovedsignificantlywiththeintroductionof
justintimecompilationin1997/1998forJava1.1,[41]theadditionoflanguagefeaturessupportingbetter
codeanalysis(suchasinnerclasses,theStringBuilderclass,optionalassertions,etc.),andoptimizationsin
theJavavirtualmachine,suchasHotSpotbecomingthedefaultforSun'sJVMin2000.WithJava1.5,the
[Link],includingLockfree
implementationsoftheConcurrentMapsandothermulticorecollections,anditwasimprovedfurtherJava
1.6.
SomeplatformsofferdirecthardwaresupportforJavatherearemicrocontrollersthatcanrunJavain
hardwareinsteadofasoftwareJavavirtualmachine,andARMbasedprocessorscanhavehardwaresupport
forexecutingJavabytecodethroughtheirJazelleoption(whileitssupportismostlydroppedincurrent
implementationsofARM).

Automaticmemorymanagement
[Link]
determineswhenobjectsarecreated,andtheJavaruntimeisresponsibleforrecoveringthememoryonce
[Link],theunreachablememorybecomes
[Link]
occurifaprogrammer'scodeholdsareferencetoanobjectthatisnolongerneeded,typicallywhenobjects
[Link]
called,a"nullpointerexception"isthrown.[42][43]
OneoftheideasbehindJava'sautomaticmemorymanagementmodelisthatprogrammerscanbespared
[Link],memoryforthecreation
ofobjectsisimplicitlyallocatedonthestack,[Link]
[Link]
deallocateanobject,[Link]

alreadybeendeallocated,theresultisundefinedanddifficulttopredict,andtheprogramislikelyto
becomeunstableand/[Link],buttheseadd
[Link]"logical"memoryleaks,i.e.,those
wherethememoryisstillreferencedbutneverused.
[Link],[Link]
betriggeredifthereisinsufficientfreememoryontheheaptoallocateanewobjectthiscancausea
[Link].
JavadoesnotsupportC/C++stylepointerarithmetic,whereobjectaddressesandunsignedintegers(usually
longintegers)[Link]
andensurestypesafetyandsecurity.
AsinC++andsomeotherobjectorientedlanguages,variablesofJava'sprimitivedatatypesareeither
storeddirectlyinfields(forobjects)oronthestack(formethods)ratherthanontheheap,asiscommonly
truefornonprimitivedatatypes(butseeescapeanalysis).ThiswasaconsciousdecisionbyJava's
designersforperformancereasons.
[Link],HotSpotusestheparallelscavengegarbage
[Link],[Link]
90%ofapplicationsinJava,theConcurrentMarkSweep(CMS)garbagecollectorissufficient.[44]Oracle
aimstoreplaceCMSwiththeGarbageFirstcollector(G1).[45]

Syntax
ThesyntaxofJavaislargelyinfluencedbyC++.UnlikeC++,whichcombinesthesyntaxforstructured,
generic,andobjectorientedprogramming,Javawasbuiltalmostexclusivelyasanobjectoriented
language.[16]Allcodeiswritteninsideclasses,andeverydataitemisanobject,withtheexceptionofthe
primitivedatatypes,[Link],floatingpointnumbers,booleanvalues,andcharacters,whicharenot
[Link]++(suchasprintf()method).
UnlikeC++,Javadoesnotsupportoperatoroverloading[46]ormultipleinheritanceforclasses,though
multipleinheritanceissupportedforinterfaces.[47]Thissimplifiesthelanguageandaidsinpreventing
potentialerrorsandantipatterndesign.
JavausescommentssimilartothoseofC++.Therearethreedifferentstylesofcomments:asingleline
stylemarkedwithtwoslashes(//),amultiplelinestyleopenedwith/*andclosedwith*/,andtheJavadoc
commentingstyleopenedwith/**andclosedwith*/.TheJavadocstyleofcommentingallowstheuserto
runtheJavadocexecutabletocreatedocumentationfortheprogram.
Example:
//Thisisanexampleofasinglelinecommentusingtwoslashes
/*Thisisanexampleofamultiplelinecommentusingtheslashandasterisk.
Thistypeofcommentcanbeusedtoholdalotofinformationordeactivate
code,butitisveryimportanttoremembertoclosethecomment.*/
packagefibsandlies;

[Link];
/**
*ThisisanexampleofaJavadoccomment;Javadoccancompiledocumentation
*[Link],method,orfieldbeingdocumented.
*/
publicclassFibCalculatorextendsFibonacciimplementsCalculator{
privatestaticMap<Integer,Integer>memoized=newHashMap<Integer,Integer>();
/*
*ThemainmethodwrittenasfollowsisusedbytheJVMasastartingpointfortheprogram.
*/
publicstaticvoidmain(String[]args){
[Link](1,1);
[Link](2,1);
[Link](fibonacci(12));//Getthe12thFibonaccinumberandprinttoconsole
}
/**
*AnexampleofamethodwritteninJava,wrappedinaclass.
*GivenanonnegativenumberFIBINDEX,returns
*theNthFibonaccinumber,whereNequalsFIBINDEX.
*@paramfibIndexTheindexoftheFibonaccinumber
*@returnTheFibonaccinumber
*/
publicstaticintfibonacci(intfibIndex){
if([Link](fibIndex)){
[Link](fibIndex);
}else{
intanswer=fibonacci(fibIndex1)+fibonacci(fibIndex2);
[Link](fibIndex,answer);
returnanswer;
}
}
}

Examples
"Hello,world!"program
Thetraditional"Hello,world!"programcanbewritteninJavaas:[48]
classHelloWorldApp{
publicstaticvoidmain(String[]args){
[Link]("HelloWorld!");//Printsthestringtotheconsole.
}
}

Sourcefilesmustbenamedafterthepublicclasstheycontain,[Link],forexample,
[Link],usingaJavacompiler,producingafilenamed
[Link],or"launched".TheJavasourcefilemayonlycontain
onepublicclass,butitcancontainmultipleclasseswithotherthanpublicaccessandanynumberofpublic
[Link],makeoneclass"public"andnamethesource
filewiththatpublicclassname.
[Link]
[Link],[Link]
[Link],anonymousclassesaretreatedasiftheirnameweretheconcatenation

ofthenameoftheirenclosingclass,a$,andaninteger.
Thekeywordpublicdenotesthatamethodcanbecalledfromcodeinotherclasses,orthataclassmaybe
[Link]
[Link]
thekeywordsprivateandprotected.
Thekeywordstaticinfrontofamethodindicatesastaticmethod,whichisassociatedonlywiththeclass
[Link]
[Link]
designatedstaticareinstancemethods,andrequireaspecificinstanceofaclasstooperate.
[Link]
istoexitwithanerrorcode,[Link]()explicitly.
Themethodname"main"[Link]
[Link]
appletsandEnterpriseJavaBeansdonotuseorneedamain()[Link]
multipleclassesthathavemainmethods,whichmeansthattheVMneedstobeexplicitlytoldwhichclassto
launchfrom.
ThemainmethodmustacceptanarrayofString([Link]
g/[Link])[Link],itisreferencedasargsalthoughanyotherlegalidentifiernamecan
beused.SinceJava5,themainmethodcanalsousevariablearguments,intheformofpublicstaticvoid
main(String...args),allowingthemainmethodtobeinvokedwithanarbitrarynumberofString
[Link](theargsparameterisstillan
arrayofStringobjects),butitallowsanalternativesyntaxforcreatingandpassingthearray.
TheJavalauncherlaunchesJavabyloadingagivenclass(specifiedonthecommandlineorasanattribute
inaJAR)andstartingitspublicstaticvoidmain(String[])[Link]
[Link][]argsparameterisanarrayofString([Link]
e/8/docs/api/java/lang/[Link])[Link]
parameterstomainareoftenpassedbymeansofacommandline.
PrintingispartofaJavastandardlibrary:TheSystem([Link]
lang/[Link])classdefinesapublicstaticfieldcalledout([Link]
api/java/lang/[Link]#out).TheoutobjectisaninstanceofthePrintStream([Link]
com/javase/8/docs/api/java/io/[Link])classandprovidesmanymethodsforprintingdatato
standardout,includingprintln(String)([Link]
[Link]#println([Link]))whichalsoappendsanewlinetothepassedstring.
Thestring"HelloWorld!"isautomaticallyconvertedtoaStringobjectbythecompiler.

Comprehensiveexample
//[Link]
[Link];

publicclassOddEven{
privateintuserInput;//awholenumber("int"meansinteger)
/**
*[Link]
*isbeingcreated.
*/
publicOddEven(){
/*
*InmostJavaprogramsconstructorscaninitializeobjectswithdefaultvalues,orcreate
*[Link],the
*constructormaysimplybeanemptyfunctionifnothingneedstobeinitializedpriortothe
*[Link]'scase,anemptyconstructorwouldsuffice.
*Aconstructormustexist;however,iftheuserdoesn'tputoneinthenthecompiler
*willcreateanemptyone.
*/
}
/**
*[Link].
*@paramargscommandlinearguments(unused)
*/
publicstaticvoidmain(finalString[]args){
/*
*Thislineofcodecreatesanewinstanceofthisclasscalled"number"(alsoknownasan
*Object)[Link]
*the"showDialog()"method,whichbringsupaprompttoaskyouforanumber.
*/
OddEvennumber=newOddEven();
[Link]();
}
publicvoidshowDialog(){
/*
*"try"[Link],
*theinterpreterskipsto"catch"toseewhatitshoulddo.
*/
try{
/*
*ThecodebelowbringsupaJOptionPane,whichisadialogbox
*TheStringreturnedbythe"showInputDialog()"methodisconvertedinto
*aninteger,makingtheprogramtreatitasanumberinsteadofaword.
*Afterthat,thismethodcallsasecondmethod,calculate()thatwill
*displayeither"Even"or"Odd."
*/
userInput=[Link]([Link]("Pleaseenteranumber."));
calculate();
}catch(finalNumberFormatExceptione){
/*
*Gettinginthecatchblockmeansthattherewasaproblemwiththeformatof
*[Link].
*/
[Link]("ERROR:[Link].");
}
}
/**
*Whenthisgetscalled,itsendsamessagetotheinterpreter.
*Theinterpreterusuallyshowsitonthecommandprompt(ForWindowsusers)
*ortheterminal(For*nixusers).(Assumingit'sopen)
*/
privatevoidcalculate(){
if((userInput%2)==0){
[Link](null,"Even");
}else{
[Link](null,"Odd");
}
}
}

TheimportstatementimportstheJOptionPane([Link]
x/swing/[Link])[Link]([Link]
pi/javax/swing/[Link])package.
[Link]
[Link]
classcanaccess(readorwrite)theuserInputfield.
OddEven()[Link]
declaredin,andunlikeamethod,[Link]
isanewlycreatedinstanceoftheclass.
Thecalculate()[Link]
invokedusingaspecificinstanceoftheOddEvenclass.(Thereferenceusedtoinvokethemethodis
passedasanundeclaredparameteroftypeOddEvennamedthis.)Themethodteststheexpression
userInput%2==0usingtheifkeywordtoseeiftheremainderofdividingtheuserInputfield
[Link],thenitprintsEvenif
thisexpressionisfalseitprintsOdd.(Thecalculatemethodcanbeequivalentlyaccessedas
[Link],whichboth
explicitlyusetheundeclaredthisparameter.)
OddEvennumber=newOddEven();declaresalocalobjectreferencevariableinthemainmethod
[Link]
initializesnumberbyfirstcreatinganinstanceoftheOddEvenclass,usingthenewkeywordandthe
OddEven()constructor,andthenassigningthisinstancetothevariable.
[Link]();[Link]
referencedbythenumberlocalvariableisusedtoinvokethemethodandpassedastheundeclared
thisparametertothecalculatemethod.
userInput=[Link]([Link]("PleaseEnterANumber"));isa
statementthatconvertsthetypeofStringtotheprimitivedatatypeintbyusingautilityfunctionin
theprimitivewrapperclassInteger.

Specialclasses
Applet
Javaappletsareprogramsthatareembeddedinotherapplications,typicallyinaWebpagedisplayedina
webbrowser.
//[Link]
[Link];
[Link];
publicclassHelloextendsJApplet{
publicvoidpaintComponent(finalGraphicsg){
[Link]("Hello,world!",65,95);
}
}

[Link]([Link]
com/javase/8/docs/api/javax/swing/[Link])[Link]([Link]
vase/8/docs/api/java/awt/[Link])[Link]

classestobereferencedinthesourcecodeusingthesimpleclassname([Link])insteadofthefully
qualifiedclassname(FQCN,[Link]).
TheHelloclassextends(subclasses)theJApplet(JavaApplet)classtheJAppletclassprovidesthe
[Link]
JComponent(JavaGraphicalComponent)whichprovidestheappletwiththecapabilitytodisplaya
graphicaluserinterface(GUI)andrespondtouserevents.
TheHelloclassoverridesthepaintComponent(Graphics)([Link]
va/awt/[Link]#paint([Link]))method(additionallyindicatedwiththeannotation,
supportedasofJDK1.5,Override)inheritedfromtheContainer([Link]
s/api/java/awt/[Link])[Link]
paintComponent()methodispassedaGraphicsobjectthatcontainsthegraphiccontextusedtodisplaythe
[Link]()methodcallsthegraphiccontextdrawString(String,int,int)([Link]
[Link]/javase/8/docs/api/java/awt/[Link]#drawString([Link],%20int,%20in
t))methodtodisplaythe"Hello,world!"stringatapixeloffsetof(65,95)fromtheupperleftcornerin

theapplet'sdisplay.
<!DOCTYPEHTMLPUBLIC"//W3C//DTDHTML4.01//EN"
"[Link]
<![Link]>
<html>
<head>
<title>HelloWorldApplet</title>
</head>
<body>
<appletcode="[Link]"width="200"height="200">
</applet>
</body>
</html>

AnappletisplacedinanHTMLdocumentusingthe<applet>[Link]
attributesset:code="Hello"specifiesthenameoftheJAppletclassandwidth="200"height="200"setsthe
[Link]
embedelement,[49]althoughsupportfortheseelementsbywebbrowsersisinconsistent.[50]However,the
applettagisdeprecated,sotheobjecttagispreferredwheresupported.

Thehostapplication,typicallyaWebbrowser,instantiatestheHelloappletandcreatesanAppletContext(h
ttps://[Link]/javase/8/docs/api/java/applet/[Link])[Link]
applethasinitializeditself,[Link]()methodis
calledbytheAWTeventdispatchingthreadwheneverthedisplayneedstheapplettodrawitself.

Servlet
JavaServlettechnologyprovidesWebdeveloperswithasimple,consistentmechanismforextendingthe
[Link]
componentsthatgenerateresponses(typicallyHTMLpages)torequests(typicallyHTTPrequests)from
[Link].
//[Link]

[Link].*;
[Link].*;
publicclassHelloextendsGenericServlet{
publicvoidservice(finalServletRequestrequest,finalServletResponseresponse)
throwsServletException,IOException{
[Link]("text/html");
finalPrintWriterpw=[Link]();
try{
[Link]("Hello,world!");
}finally{
[Link]();
}
}
}

TheimportstatementsdirecttheJavacompilertoincludeallthepublicclassesandinterfacesfromthe
[Link]([Link]
[Link]([Link]
[Link].
TheHelloclassextendstheGenericServlet([Link]
[Link])classtheGenericServletclassprovidestheinterfacefortheservertoforwardrequeststo
theservletandcontroltheservlet'slifecycle.
TheHelloclassoverridestheservice(ServletRequest,ServletResponse)([Link]
ee/7/api/javax/servlet/[Link]#service([Link],[Link]
sponse))methoddefinedbytheServlet([Link]
[Link])[Link]()methodispassed:a
ServletRequest([Link]

containstherequestfromtheclientandaServletResponse([Link]
x/servlet/[Link])[Link]()
methoddeclaresthatitthrowstheexceptionsServletException([Link]
avax/servlet/[Link])andIOException([Link]
va/io/[Link])ifaproblempreventsitfromrespondingtotherequest.
ThesetContentType(String)([Link]
tml#setContentType([Link]))methodintheresponseobjectiscalledtosettheMIMEcontent
typeofthereturneddatato"text/html".ThegetWriter()([Link]
x/servlet/[Link]#getWriter())methodintheresponsereturnsaPrintWriter([Link]
[Link]/javase/8/docs/api/java/io/[Link])objectthatisusedtowritethedatathatis
[Link](String)([Link]
[Link]#println([Link]))methodiscalledtowritethe"Hello,world!"stringtotheresponse
andthentheclose()([Link]
methodiscalledtoclosetheprintwriter,whichcausesthedatathathasbeenwrittentothestreamtobe
returnedtotheclient.

JavaServerPages

JavaServerPages(JSP)areserversideJavaEEcomponentsthatgenerateresponses,typicallyHTML
pages,[Link]
delimiters<%and%>.AJSPiscompiledtoaJavaservlet,aJavaapplicationinitsownright,thefirsttimeit
[Link],thegeneratedservletcreatestheresponse.

Swingapplication
[Link]
[Link],GTK+andMotifare
[Link]
oftheselooksandfeelsmayhavebeenconsideredlacking,SwinginJavaSE6addressesthisproblemby
usingmorenativeGUIwidgetdrawingroutinesoftheunderlyingplatforms.
ThisexampleSwingapplicationcreatesasinglewindowwith"Hello,world!"inside:
//[Link](JavaSE5)
[Link].*;
publicclassHelloextendsJFrame{
publicHello(){
super("hello");
[Link](WindowConstants.EXIT_ON_CLOSE);
[Link](newJLabel("Hello,world!"));
[Link]();
[Link](true);
}
publicstaticvoidmain(finalString[]args){
newHello();
}
}

[Link]([Link]
com/javase/8/docs/api/javax/swing/[Link])package.
TheHelloclassextendstheJFrame([Link]
ml)classtheJFrameclassimplementsawindowwithatitlebarandaclosecontrol.
TheHello()constructorinitializestheframebyfirstcallingthesuperclassconstructor,passingthe
parameter"hello",whichisusedasthewindow'[Link](int)(h
ttps://[Link]/javase/8/docs/api/javax/swing/[Link]#setDefaultCloseOperation(int))

methodinheritedfromJFrametosetthedefaultoperationwhentheclosecontrolonthetitlebarisselected
toWindowConstants.EXIT_ON_CLOSE([Link]
[Link]#EXIT_ON_CLOSE)thiscausestheJFrametobedisposedofwhentheframeisclosed(as
opposedtomerelyhidden),whichallowstheJavavirtualmachinetoexitandtheprogramtoterminate.
Next,aJLabel([Link]
string"Hello,world!"andtheadd(Component)([Link]
[Link]#add([Link]))methodinheritedfromtheContainer([Link]
m/javase/8/docs/api/java/awt/[Link])[Link]

pack()([Link]

fromtheWindow([Link]
tosizethewindowandlayoutitscontents.
Themain()[Link]
HelloframeandcausesittobedisplayedbycallingthesetVisible(boolean)([Link]
avase/8/docs/api/java/awt/[Link]#setVisible(boolean))methodinheritedfromtheComponent
([Link]
[Link],exitingthemainmethoddoesnotcausetheprogramto
terminatebecausetheAWTeventdispatchingthreadremainsactiveuntilalloftheSwingtoplevel
windowshavebeendisposed.

Generics
In2004,genericswereaddedtotheJavalanguage,[Link],
[Link],forexample,thisisaproblem
[Link]
containeroperatesonallsubtypesofaclassorinterface,usuallyObject,oradifferentcontainerclasshasto
[Link]
manycontainerclasses,[Link],
certainruntimeexceptionsareconvertedtocompiletimeerrors,acharacteristicknownastypesafety.

Criticism
CriticismsdirectedatJavaincludetheimplementationofgenerics,[51]speed,[52]thehandlingofunsigned
numbers,[53]theimplementationoffloatingpointarithmetic,[54]andahistoryofsecurityvulnerabilitiesin
theprimaryJavaVMimplementationHotSpot.[55]

Useonunofficialsoftwareplatforms
TheJavaprogramminglanguagerequiresthepresenceofasoftwareplatforminorderforcompiled
[Link]
platform,whichallowstheuseofJava6andsomeJava7features,usesadifferentstandardlibrary(Apache
Harmonyreimplementation),differentbytecodelanguageanddifferentvirtualmachine,andisdesignedfor
lowmemorydevicessuchassmartphonesandtabletcomputers.

Google
TheJavalanguageisakeypillarinAndroid,[Link],
builtontheLinuxkernel,waswrittenlargelyinC,theAndroidSDKusestheJavalanguageasthebasisfor
[Link],AndroiddoesnotusethestandardJavavirtualmachine,insteadusingJava
[Link]
version,thisistheneitherinterpretedbytheDalvikvirtualmachine,orcompiledintonativecodebythe
AndroidRuntime.

AndroidalsodoesnotprovidethefullJavaSEstandardlibrary,althoughthe
Androidclasslibrarydoesincludeanindependentimplementationofalarge
[Link]
7,2012,aSanFranciscojuryfoundthatifAPIscouldbecopyrighted,then
GooglehadinfringedOracle'scopyrightsbytheuseofJavainAndroid
devices.[56]DistrictJudgeWilliamHaskellAlsupruledonMay31,2012,
thatAPIscannotbecopyrighted,[57]butthiswasreversedbytheUnited
StatesCourtofAppealsfortheFederalCircuitinMay2014.[58][59][60]

Classlibraries
TheJavaClassLibraryisthestandardlibrary,developedtosupport
[Link]
cooperationwithothersthroughtheJavaCommunityProcessprogram.
Companiesorindividualsparticipatinginthisprocesscaninfluencethe
[Link]
[Link]:

TheAndroidoperating
systemmakesextensiveuse
ofJavarelatedtechnology

Thecorelibraries,whichinclude:
IO/NIO
Networking
Reflection
Concurrency
Generics
Scripting/Compiler
FunctionalProgramming(Lambda,Streaming)
Collectionlibrariesthatimplementdatastructuressuchaslists,dictionaries,trees,sets,queues
anddoubleendedqueue,orstacks[61]
XMLProcessing(Parsing,Transforming,Validating)libraries
Security[62]
Internationalizationandlocalizationlibraries[63]
Theintegrationlibraries,whichallowtheapplicationwritertocommunicatewithexternalsystems.
Theselibrariesinclude:
TheJavaDatabaseConnectivity(JDBC)APIfordatabaseaccess
JavaNamingandDirectoryInterface(JNDI)forlookupanddiscovery
RMIandCORBAfordistributedapplicationdevelopment
JMXformanagingandmonitoringapplications
Userinterfacelibraries,whichinclude:
The(heavyweight,ornative)AbstractWindowToolkit(AWT),whichprovidesGUI
components,themeansforlayingoutthosecomponentsandthemeansforhandlingevents
fromthosecomponents
The(lightweight)Swinglibraries,whicharebuiltonAWTbutprovide(nonnative)
implementationsoftheAWTwidgetry
APIsforaudiocapture,processing,andplayback
JavaFX
AplatformdependentimplementationoftheJavavirtualmachinethatisthemeansbywhichthe
bytecodesoftheJavalibrariesandthirdpartyapplicationsareexecuted
Plugins,whichenableappletstoberuninwebbrowsers

JavaWebStart,whichallowsJavaapplicationstobeefficientlydistributedtoendusersacrossthe
Internet
Licensinganddocumentation

Documentation
Javadocisacomprehensivedocumentationsystem,createdbySunMicrosystems,usedbymanyJava
[Link]
commentshaveanextraasteriskatthebeginning,[Link]/**and*/,whereasthenormal
multilinecommentsinJavaaresetoffwiththedelimiters/*and*/.[64]

Editions
SunhasdefinedandsupportsfoureditionsofJavatargetingdifferentapplicationenvironmentsand
[Link]:
JavaCardforsmartcards.[65]
JavaPlatform,MicroEdition(JavaME)targetingenvironmentswithlimitedresources.[66]
JavaPlatform,StandardEdition(JavaSE)targetingworkstationenvironments.[67]
JavaPlatform,EnterpriseEdition(JavaEE)targetinglargedistributedenterpriseorInternet
environments.[68]
[Link]
setofrelatedinterfaces,[Link]
packagesavailable.
SunalsoprovidedaneditioncalledPersonalJavathathasbeensupersededbylater,standardsbasedJava
MEconfigurationprofilepairings.

Seealso
DalvikusedinoldAndroidversions,replacedbynonJITAndroidRuntime
JavaOne
Javapedia
ListofJavavirtualmachines
ListofJavaAPIs
ListofJVMlanguages
Graal(compiler),aprojectaimingtoimplementahighperformanceJavadynamiccompilerand
interpreter
SpringFramework

ComparisonofJavawithotherlanguages
Comparisonofprogramminglanguages
ComparisonofJavaandC++
ComparisonofC#andJava

Notes
[Link],Andrew(20May2015)."Java's20YearsOfInnovation".Forbes.Retrieved18March2016.
[Link](28July2014)."CrackingTheJavaProgrammingInterview::2000+JavaInterview
Que/Ans".Retrieved29May2016.
3.Java5.0addedseveralnewlanguagefeatures(theenhancedforloop,autoboxing,varargsandannotations),after
theywereintroducedinthesimilar(andcompeting)C#language[1]([Link]
5/)[2]([Link]
[Link],JamesMcGilton,Henry(May1996)."TheJavaLanguageEnvironment".
[Link],JamesJoy,BillSteele,GuyBracha,Gilad."TheJavaLanguageSpecification,2ndEdition".
6."TheAZofProgrammingLanguages:Modula3".[Link].Retrieved20100609.
[Link],[Link],Moscowin
September,2005(severalindependentfirsthandaccountsinRussianexist,[Link]:
Filippova,Elena(September22,2005)."NiklausWirth'slectureatthePolytechnicMuseuminMoscow".),that
theSunJavadesignteamlicensedtheOberoncompilersourcesanumberofyearspriortothereleaseofJavaand
examinedit:a(relative)compactness,typesafety,garbagecollection,nomultipleinheritanceforclassesall
thesekeyoveralldesignfeaturesaresharedbyJavaandOberon.
[Link],stating
thatnotabledirectderivativesincludeJavainterfaces(derivedfromObjectiveC'sprotocol)andprimitivewrapper
classes.[3]([Link]
[Link](1999)."HistoryofJava"(PDF).JavaApplicationServersReport."Theprojectwentahead
underthename"green"andthelanguagewasbasedonanoldmodelofUCSDPascal,whichmakesitpossibleto
generateinterpretivecode"
10."AConversationwithJamesGoslingACMQueue".[Link].20040831.Retrieved20100609.
11.Inthesummerof1996,SunwasdesigningtheprecursortowhatisnowtheeventmodeloftheAWTandthe
[Link]
DelphiObjectPascalandbuiltaworkingprototypeofboundmethodreferencesinordertounderstandtheir
[Link]'s"Delegates"(https://
[Link]/web/20120627043929/[Link]
12."Chapelspec(Acknowledgements)"(PDF).CrayInc.20151001.Retrieved20160114.
13."FacebookQ&A:HackbringsstatictypingtoPHPworld".InfoWorld.20140326.Retrieved20150111.
[Link].2014,p.1.
15."Writeonce,runanywhere?".ComputerWeekly.20020502.Retrieved20090727.
16."1.2DesignGoalsoftheJavaProgrammingLanguage".Oracle.19990101.Retrieved20130114.
[Link],Robert(20130801)."IsJavaLosingItsMojo?".[Link]."Javaisonthewane,atleastaccording
[Link]
decade,ithasdominatedtheTIOBEProgrammingCommunityIndex,andisbackontopasnapshotof
softwaredeveloperenthusiasmthatlooksatthingslikeinternetsearchresultstomeasurehowmuchbuzz
[Link],Javahasbeenslipping."
[Link]([Link]
O'Grady,January2015)
19."ProgrammingLanguagePopularity".[Link].20131025.Retrieved20150402."Normalized
Comparison:1stC,2ndJava,3rdPHP"
20."TIOBEProgrammingCommunityIndex".2015.Retrieved20150403.
[Link],Jon(c.1998)."Javatechnology:Theearlyyears".[Link]
fromtheoriginalon20050420.Retrieved20050422.
[Link]"TheHistoryofJavaTechnology".[Link]
20100430.
23."SowhydidtheydecidetocallitJava?([Link]
Murphy,[Link],10/04/96
[Link],HeinzOnceUponanOak([Link]
RetrievedApril29,2007.
25."TheHistoryofJavaTechnology".RetrievedOctober6,2012.

[Link]://[Link]/javaplatformgroup/entry/moving_to_a_plugin_free
[Link]:[Link].p.34.
28."JSGJavaStudyGroup".[Link].
29."WhyJavaWasNotStandardizedTwice"(PDF).
30."WhatisECMAandwhyMicrosoftcares".
31."JavaCommunityProcesswebsite".[Link].20100524.Retrieved20100609.
32."JAVAONE:SunThebulkofJavaisopensourced".[Link].Retrieved20140526.
33."Sun'sEvolvingRoleasJavaEvangelist".O'ReillyMedia.
34."OracleandJava".[Link].Retrieved20100823."Oraclehasbeenaleadingand
substantivesupporterofJavasinceitsemergencein1995andtakesonthenewroleasstewardofJavatechnology
witharelentlesscommitmenttofosteringacommunityofparticipationandtransparency."
35."LearnAboutJavaTechnology".Oracle.Retrieved21November2011.
[Link],James(April9,2010)."Timetomoveon...".OnaNewRoad.Retrieved20111116.
37."IstheJVM(JavaVirtualMachine)platformdependentorplatformindependent?Whatistheadvantageofusing
theJVM,andhavingJavabeatranslatedlanguage?".ProgrammerInterview.Retrieved20150119.
[Link],James(January23,2001)."Sun,MicrosoftsettleJavalawsuit".JavaWorld(InternationalDataGroup).
Retrieved20080709.
[Link],Dejan."WhyJavawillalwaysbeslowerthanC++".Retrieved20080215.
[Link]."LoopRecognitioninC++/Java/Go/Scala"(PDF).Retrieved20120712.
41."Symantec'sJustInTimeJavaCompilerToBeIntegratedintoSunJDK1.1".
42."NullPointerException".Oracle.Retrieved20140506.
43."ExceptionsinJava".[Link].Retrieved20100810.
44."JavaHotSpotVMOptions".[Link].20100907.Retrieved20120630.
[Link]://[Link]/javase/7/docs/technotes/guides/vm/[Link]
46."OperatorOverloading(C#vsJava)".C#[Link].Retrieved10December2014.
47."MultipleInheritanceofState,Implementation,andType".[Link].Retrieved10December
2014.
48."Lesson:ACloserLookatthe"HelloWorld!"Application".TheJavaTutorials>[Link]
Corporation.Retrieved20110414.
49."Usingapplet,objectandembedTags".[Link].Retrieved20101014.
50."DeployingAppletsinaMixedBrowserEnvironment".[Link].Retrieved20101014.
[Link],Ken."GenericsConsideredHarmful".[Link].Retrieved4July2011.
[Link],Dejan."WhyJavaWillAlwaysBeSlowerthanC++".[Link].Retrieved17October2012.
[Link],SeanR."Javaandunsignedint,unsignedshort,unsignedbyte,unsignedlong,etc.(Orrather,thelack
thereof)".Archivedfromtheoriginalon20041109.Retrieved20110704.
[Link],William."HowJava'sFloatingPointHurtsEveryoneEverywhere"(PDF).ElectricalEngineering&
ComputerScience,UniversityofCaliforniaatBerkeley.Retrieved4June2011.
55."HaveyoucheckedtheJava?".
[Link],Joe."GoogleguiltyofinfringementinOracletrialfuturelegalheadachesloom".Law&[Link]
Technica.Retrieved8May2012.
[Link](May31,2012)."GooglewinscrucialAPIruling,Oracle'scasedecimated".[Link]
20120601.
[Link]://[Link]/images/stories/opinionsorders/[Link]
[Link],Seth(May9,2014)."CourtsideswithOracleoverAndroidinJavapatentappeal".[Link]
20140510.
60."ORACLEAMERICA,INC.,PlaintiffAppellant,[Link].,DefendantCrossAppellant."(PDF).
CourtofAppealsfortheFederalCircuit.May9,2014.Retrieved20140510.
61."CollectionsFrameworkOverview".[Link].Retrieved18December2014.
62."JavaSecurityOverview".[Link].Retrieved18December2014.
63."Trail:Internationalization".[Link].Retrieved18December2014.
64."HowtoWriteDocCommentsfortheJavadocTool".[Link]
18December2014.
65."JavaCardOverview".[Link].Retrieved18December2014.

66."JavaPlatform,MicroEdition(JavaME)".[Link].Retrieved18December2014.
67."JavaSE".[Link].Retrieved18December2014.
68."JavaPlatform,EnterpriseEdition(JavaEE)".[Link].Retrieved18December
2014.

References
Gosling,JamesJoy,BillSteele,GuyBracha,GiladBuckley,Alex(2014).TheJavaLanguageSpecification
(PDF)(JavaSE8ed.).
Gosling,JamesJoy,BillSteele,GuyL.,[Link],Gilad(2005).TheJavaLanguageSpecification(3rded.).
AddisonWesley.ISBN0321246780.
Lindholm,TimYellin,Frank(1999).TheJavaVirtualMachineSpecification(2nded.).AddisonWesley.
ISBN0201432943.

Externallinks
Retrievedfrom"[Link]
title=Java_(programming_language)&oldid=723122176"

Wikiversityhaslearning
materialsaboutJava
Platform,Enterprise
Edition/JavaEETutorial

Categories: Cprogramminglanguagefamily
Classbasedprogramminglanguages Concurrentprogramminglanguages Crossplatformsoftware
Java(programminglanguage) Javaplatform Javaspecificationrequests
JVMprogramminglanguages Objectorientedprogramminglanguages Programminglanguages
Programminglanguagescreatedin1995 Staticallytypedprogramminglanguages SunMicrosystems

Thispagewaslastmodifiedon1June2016,at04:23.
TextisavailableundertheCreativeCommonsAttributionShareAlikeLicenseadditionaltermsmay
[Link],[Link]
registeredtrademarkoftheWikimediaFoundation,Inc.,anonprofitorganization.

You might also like