Tải bản đầy đủ - 0 (trang)
Chapter 4.  The Java Language

Chapter 4.  The Java Language

Tải bản đầy đủ - 0trang

4.1.TextEncoding

JavaisalanguagefortheInternet.SincethepeopleoftheNet

speakandwriteinmanydifferenthumanlanguages,Javamust

beabletohandlealargenumberoflanguagesaswell.Oneof

thewaysinwhichJavasupportsinternationalizationisthrough

theUnicodecharacterset.Unicodeisaworldwidestandardthat

supportsthescriptsofmostlanguages.[*]Javabasesits

characterandstringdataontheUnicode4.0standard,which

uses16bitstorepresenteachsymbol.

[*]FormoreinformationaboutUnicode,seehttp://www.unicode.org.Ironically,oneofthescriptslistedas

"obsoleteandarchaic"andnotcurrentlysupportedbytheUnicodestandardisJavaneseahistoricallanguageof

thepeopleoftheIslandofJava.



JavasourcecodecanbewrittenusingUnicodeandstoredin

anynumberofcharacterencodings,rangingfromitsfull16-bit

formtoASCII-encodedUnicodecharactervalues.Thismakes

Javaafriendlylanguagefornon-English-speakingprogrammers

whocanusetheirnativelanguageforclass,method,and

variablenamesjustastheycanforthetextdisplayedbythe

application.

TheJavachartypeandStringobjectsnativelysupportUnicode

values.Butifyou'reconcernedabouthavingtolaborwithtwobytecharacters,youcanrelax.TheStringAPImakesthe

characterencodingtransparenttoyou.Unicodeisalsovery

ASCII-friendly(ASCIIisthemostcommoncharacterencoding

forEnglish).Thefirst256charactersaredefinedtobeidentical

tothefirst256charactersintheISO8859-1(Latin-1)character

set,soUnicodeiseffectivelybackward-compatiblewiththe

mostcommonEnglishcharactersets.Furthermore,themost

commonencodingforUnicode,calledUTF-8,preservesASCII

valuesintheirsinglebyteform.Thisencodingisusedin

compiledJavaclassfiles,soforEnglishtext,storageremains

compact.



Mostplatformscan'tdisplayallcurrentlydefinedUnicode

characters.Asaresult,Javaprogramscanbewrittenwith

specialUnicodeescapesequences.AUnicodecharactercanbe

representedwiththisescapesequence:

\uxxxx



xxxxisasequenceofonetofourhexadecimaldigits.Theescape



sequenceindicatesanASCII-encodedUnicodecharacter.Thisis

alsotheformJavausestooutput(print)Unicodecharactersin

anenvironmentthatdoesn'totherwisesupportthem.Javaalso

comeswithclassestoreadandwriteUnicodecharacterstreams

inspecificencodings,includingUTF-8.



4.2.Comments

JavasupportsbothC-styleblockcommentsdelimitedby/*and

*/andC++-stylelinecommentsindicatedby//:

/*Thisisa

multiline

comment.*/

//Thisisasingle-linecomment

//andso//isthis



Blockcommentshavebothabeginningandendsequenceand

cancoverlargerangesoftext.However,theycannotbe

"nested";meaningthatyoucan'thaveablockcommentinside

ofablockcommentwithoutthecompilergettingconfused.

Single-linecommentshaveonlyastartsequenceandare

delimitedbytheendofaline;extra//indicatorsinsideasingle

linehavenoeffect.Linecommentsareusefulforshort

commentswithinmethods;theydon'tconflictwithblock

comments,soyoucanstillcomment-outlargerchunksofcode

includingthem.



4.2.1.JavadocComments

Ablockcommentbeginningwith/**indicatesaspecialdoc

comment.Adoccommentisdesignedtobeextractedby

automateddocumentationgenerators,suchastheJDK's

javadocprogram.Adoccommentisterminatedbythenext*/,

justaswitharegularblockcomment.Withinthedoccomment,

linesbeginningwith@areinterpretedasspecialinstructionsfor

thedocumentationgenerator,givingitinformationaboutthe



sourcecode.Byconvention,eachlineofadoccommentbegins

witha*,asshowninthefollowingexample,butthisisoptional.

Anyleadingspacingandthe*oneachlineareignored:



/**

*Ithinkthisclassispossiblythemostamazingthingyo

*eversee.Letmetellyouaboutmyownpersonalvisiona

*motivationincreatingit.

*



*ItallbeganwhenIwasasmallchild,growinguponthe

*streetsofIdaho.Potatoesweretherage,andlifewasg

*

*@seePotatoPeeler

*@seePotatoMasher

*@authorJohn'Spuds'Smith

*@version1.00,19Dec2006

*/

classPotato{



javadoccreatesHTMLdocumentationforclassesbyreadingthe

sourcecodeandpullingouttheembeddedcommentsand@

tags.Inthisexample,thetagscauseauthorandversion

informationtobepresentedintheclassdocumentation.The

@seetagsproducehypertextlinkstotherelatedclass

documentation.

Thecompileralsolooksatthedoccomments;inparticular,itis

interestedinthe@deprecatedtag,whichmeansthatthemethod

hasbeendeclaredobsoleteandshouldbeavoidedinnew

programs.Thefactthatamethodisdeprecatedisnotedinthe

compiledclassfilesoawarningmessagecanbegenerated

wheneveryouuseadeprecatedfeatureinyourcode(evenif

thesourceisn'tavailable).

Doccommentscanappearaboveclass,method,andvariable



definitions,butsometagsmaynotbeapplicabletoallofthese.

Forexample,the@exceptiontagcanonlybeappliedtomethods.

Table4-1summarizesthetagsusedindoccomments.

Table4-1.Doccommenttags

Tag



Description



Appliesto



@see



Associatedclassname



Class,method,orvariable



@author



Authorname



Class



@version



Versionstring



Class



@param



Parameternameanddescription



Method



@return



Descriptionofreturnvalue



Method



@exception



Exceptionnameanddescription



Method



@deprecated



Declaresanitemtobeobsolete



Class,method,orvariable



@since



NotesAPIversionwhenitemwasadded



Variable



4.2.1.1Javadocasmetadata

Javadoctagsindoccommentsrepresentmetadataaboutthe

sourcecode;thatis,theyadddescriptiveinformationaboutthe

structureorcontentsofthecodethatisnot,strictlyspeaking,

partoftheapplication.Inthepast,someadditionaltoolshave

extendedtheconceptofJavadoc-styletagstoincludeother

kindsofmetadataaboutJavaprograms.Java5.0introduceda

newannotationsfacilitythatprovidesamoreformaland

extensiblewaytoaddmetadatatoJavaclasses,methods,and



variables.We'lltalkaboutannotationsinChapter7.However,

weshouldmentionthatthereisan@deprecatedannotationthat

hasthesamemeaningasthatoftheJavadoctagofthesame

name.UsersofJava5.0willlikelypreferittotheJavadocform.



4.3.Types

Thetypesystemofaprogramminglanguagedescribeshowits

dataelements(variablesandconstants)areassociatedwith

storageinmemoryandhowtheyarerelatedtooneanother.In

astaticallytypedlanguage,suchasCorC++,thetypeofa

dataelementisasimple,unchangingattributethatoften

correspondsdirectlytosomeunderlyinghardware

phenomenon,suchasaregisterorapointervalue.Inamore

dynamiclanguagesuchasSmalltalkorLisp,variablescanbe

assignedarbitraryelementsandcaneffectivelychangetheir

typethroughouttheirlifetime.Aconsiderableamountof

overheadgoesintovalidatingwhathappensintheselanguages

atruntime.ScriptinglanguagessuchasPerlachieveeaseofuse

byprovidingdrasticallysimplifiedtypesystemsinwhichonly

certaindataelementscanbestoredinvariables,andvaluesare

unifiedintoacommonrepresentation,suchasstrings.

Javacombinesthebestfeaturesofbothstaticallyand

dynamicallytypedlanguages.Asinastaticallytypedlanguage,

everyvariableandprogrammingelementinJavahasatype

thatisknownatcompiletime,sotheruntimesystemdoesn't

normallyhavetocheckthevalidityofassignmentsbetween

typeswhilethecodeisexecuting.UnliketraditionalCorC++,

Javaalsomaintainsruntimeinformationaboutobjectsanduses

thistoallowtrulydynamicbehavior.Javacodemayloadnew

typesatruntimeandusetheminfullyobject-orientedways,

allowingcastingandfullpolymorphism(extendingoftypes).

Javadatatypesfallintotwocategories.Primitivetypes

representsimplevaluesthathavebuilt-infunctionalityinthe

language;theyarefixedelements,suchasliteralconstantsand

numbers.Referencetypes(orclasstypes)includeobjectsand

arrays;theyarecalledreferencetypesbecausethey"referto"

alargedatatypewhichispassed"byreference,"aswe'll

explainshortly.InJava5.0,generictypeswereintroducedto



thelanguage,buttheyarereallyanextensionofclassesand

are,therefore,actuallyreferencetypes.



4.3.1.PrimitiveTypes

Numbers,characters,andBooleanvaluesarefundamental

elementsinJava.Unlikesomeother(perhapsmorepure)

object-orientedlanguages,theyarenotobjects.Forthose

situationswhereit'sdesirabletotreataprimitivevalueasan

object,Javaprovides"wrapper"classes.Themajoradvantage

oftreatingprimitivevaluesasspecialisthattheJavacompiler

andruntimecanmorereadilyoptimizetheirimplementation.

Primitivevaluesandcomputationscanstillbemappeddownto

hardwareastheyalwayshavebeeninlower-levellanguages.

AsofJava5.0,thecompilercanautomaticallyconvertbetween

primitivevaluesandtheirobjectwrappersasneededtopartially

maskthedifferencebetweenthetwo.We'llexplainwhatthat

meansinmoredetailinthenextchapterwhenwediscuss

boxingandunboxingofprimitivevalues.

AnimportantportabilityfeatureofJavaisthatprimitivetypes

arepreciselydefined.Forexample,youneverhavetoworry

aboutthesizeofanintonaparticularplatform;it'salwaysa

32-bit,signed,two'scomplementnumber.Table4-2

summarizesJava'sprimitivetypes.

Table4-2.Javaprimitivedatatypes

Type



Definition



boolean



trueorfalse



char



16-bit,Unicodecharacter



byte



8-bit,signed,two'scomplementinteger



short



16-bit,signed,two'scomplementinteger



int



32-bit,signed,two'scomplementinteger



long



64-bit,signed,two'scomplementinteger



float



32-bit,IEEE754,floating-pointvalue



ThoseofyouwithaCbackgroundmaynoticethattheprimitive

typeslooklikeanidealizationofCscalartypesona32-bit

machine,andyou'reabsolutelyright.That'showthey're

supposedtolook.The16-bitcharacterswereforcedby

Unicode,andadhocpointersweredeletedforotherreasons.

Butoverall,thesyntaxandsemanticsofJavaprimitivetypes

aremeanttofitaCprogrammer'smentalhabits.



4.3.1.1Floating-pointprecision

Floating-pointoperationsinJavafollowtheIEEE754

internationalspecification,whichmeansthattheresultof

floating-pointcalculationsisnormallythesameondifferent

Javaplatforms.However,sinceVersion1.3,Javahasallowedfor

extendedprecisiononplatformsthatsupportit.Thiscan

introduceextremelysmall-valuedandarcanedifferencesinthe

resultsofhigh-precisionoperations.Mostapplicationswould

nevernoticethis,butifyouwanttoensurethatyour

applicationproducesexactlythesameresultsondifferent

platforms,youcanusethespecialkeywordstrictfpasaclass

modifierontheclasscontainingthefloating-pointmanipulation

(wecoverclassesinthenextchapter).Thecompilerthen

prohibitsplatform-specificoptimizations.



4.3.1.2Variabledeclarationandinitialization

VariablesaredeclaredinsideofmethodsorclassesinCstyle,

withatypefollowedbyoneormorecomma-separatedvariable

names.Forexample:

intfoo;

doubled1,d2;

booleanisFun;



Variablescanoptionallybeinitializedwithanappropriate

expressionwhentheyaredeclared:

intfoo=42;

doubled1=3.14,d2=2*3.14;

booleanisFun=true;



Variablesthataredeclaredasmembersofaclassaresetto

defaultvaluesiftheyaren'tinitialized(seeChapter5).Inthis

case,numerictypesdefaulttotheappropriateflavorofzero,

charactersaresettothenullcharacter(\0),andBoolean

variableshavethevaluefalse.Localvariables,whichare

declaredinsideamethodandliveonlyforthedurationofa

methodcall,ontheotherhand,mustbeexplicitlyinitialized

beforetheycanbeused.Aswe'llsee,thecompilerenforcesthis

rulesothereisnodangerofforgetting.



4.3.1.3Integerliterals

Integerliteralscanbespecifiedinoctal(base8),decimal(base

10),orhexadecimal(base16).Adecimalintegerisspecifiedby



asequenceofdigitsbeginningwithoneofthecharacters1-9:

inti=1230;



Octalnumbersaredistinguishedfromdecimalnumbersbya

leadingzero:

inti=01230;//i=664decimal



Ahexadecimalnumberisdenotedbytheleadingcharacters0x

or0X(zero"x"),followedbyacombinationofdigitsandthe

charactersa-forA-F,whichrepresentthedecimalvalues1015:

inti=0xFFFF;//i=65535decimal



IntegerliteralsareoftypeintunlesstheyaresuffixedwithanL,

denotingthattheyaretobeproducedasalongvalue:



longl=13L;

longl=13;//equivalent:13isconvertedfromtype



(Thelowercaseletterlisalsoacceptablebutshouldbeavoided

becauseitoftenlookslikethenumber1.)

Whenanumerictypeisusedinanassignmentoranexpression

involvinga"larger"typewithagreaterrange,itcanbe

promotedtothebiggertype.Inthesecondlineoftheprevious

example,thenumber13hasthedefaulttypeofint,butit's

promotedtotypelongforassignmenttothelongvariable.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 4.  The Java Language

Tải bản đầy đủ ngay(0 tr)

×