Java notes.docx
- 文档编号:30215863
- 上传时间:2023-08-07
- 格式:DOCX
- 页数:31
- 大小:524.41KB
Java notes.docx
《Java notes.docx》由会员分享,可在线阅读,更多相关《Java notes.docx(31页珍藏版)》请在冰豆网上搜索。
Javanotes
《CoreJavaI9th》
1.Thestandardnamingconventionisthatclassnamesarenounsthatstartwithanuppercaseletter.Ifanameconsistsofmultiplewords,useaninitialuppercaseletterineachofthewords.(Thisuseofuppercaselettersinthemiddleofawordissometimescalled“camelcase”or,self-referentially,“CamelCase”.)
2.Youneedtomakethefilenameforthesourcecodethesameasthenameofthepublicclass,withtheextension.javaappended.Thus,youmuststorethiscodeinafilecalledFirstSample.java.(Again,caseisimportant—don’tusefirstsample.java.)Ifyouhavenamedthefilecorrectlyandnotmadeanytypos(错别字)inthesourcecode,thenwhenyoucompilethissourcecode,youendupwithafilecontainingthebytecodes(字节码)forthisclass.TheJavacompilerautomaticallynamesthebytecodefileFirstSample.classandstoresitinthesamedirectoryasthesourcefile.Finally,launchtheprogrambyissuingthefollowingcommand:
javaFirstSample(Remembertoleaveoffthe.classextension.)Whentheprogramexecutes,itsimplydisplaysthestringWewillnotuse'Hello,World!
'ontheconsole.WhenyouusejavaClassNametorunacompiledprogram,theJavavirtualmachinealwaysstartsexecutionwiththecodeinthemainmethodintheclassyouindicate.(youmusthaveamainmethodinthesourcefileforyourclassforyourcodetoexecute)。
themainmethodmustbedeclaredpublic.
3.asinC/C++,thevoidkeywordindicatesthatthismethoddoesnotreturnavalue.UnlikeC/C++,themainmethoddoesnotreturnan“exitcode”totheoperatingsystem.Ifthemainmethodexitsnormally,theJavaprogramhastheexitcode0,indicatingsuccessfulcompletion.Toterminate(使终止)theprogramwithadifferentexitcode,usetheSystem.exitmethod.
4.Javausesthegeneralsyntax:
object(对象).method(parameters(参数))asitsequivalentofafunctioncall.
5./**/commentsdonotnest(嵌套)inJava.Thatis,youmaynotbeabletodeactivatecodesimplybysurroundingitwith/*and*/becausethecodeyouwanttodeactivatemightitselfcontaina*/delimiter.
6.Byte:
1字节(-128_127)short:
2字节(-32768_32767)int:
4字节(-2147483648_2147483647)long:
8字节(-9223372036854775808_9223372036854775807)
7.UnderJava,therangesoftheintegertypesdonotdependonthemachineonwhichyouwillberunningtheJavacode.Thisalleviates(减轻)amajorpainfortheprogrammerwhowantstomovesoftwarefromoneplatformtoanother,orevenbetweenoperatingsystemsonthesameplatform.Javadoesnothaveanyunsignedtypes
8.Longintegernumbershaveasuffix(后缀)L(forexample,4000000000L).Hexadecimal(十六进制)numbershaveaprefix(前缀)0x(forexample,0xCAFE).Octal(八进制)numbershaveaprefix0.Forexample,010is8.Naturally,thiscanbeconfusing,sowerecommendagainsttheuseofoctalconstants.StartingwithJava7,youcanwritenumbersinbinary,withaprefix0b.Forexample,0b1001is9.AlsostartingwithJava7,youcanaddunderscorestonumberliterals,suchas1_000_000(or0b1111_0100_0010_0100_0000)todenote(标志)onemillion.Theunderscoresareforhumaneyesonly.TheJavacompilersimplyremovesthem.Float:
4字节(+_3.40282347E+38F6-7位有效数字)double:
8字节(15位有效数字)
9.Thenamedoublereferstothefactthatthesenumbershavetwicetheprecision(精度)ofthefloattype.(Somepeoplecallthesedouble-precisionnumbers.)Here,thetypetochooseinmostapplicationsisdouble.NumbersoftypefloathaveasuffixF(forexample,3.14F).Floating-pointnumberswithoutanFsuffix(suchas3.14)arealwaysconsideredtobeoftypedouble.YoucanoptionallysupplytheDsuffix(forexample,3.14D).Youcanspecify(指定,规定)floating-pointliteralsinhexadecimal(十六进制的).Forexample,0.125=2–3canbewrittenas0x1.0p-3.Inhexadecimalnotation,youuseap,notane,todenotetheexponent.(Aneisahexadecimaldigit.)Note(注意)thatthemantissa(浮点数)iswritteninhexadecimalandtheexponent(指数)indecimal(十进制).Thebaseoftheexponentis2,not10.
10.Allfloating-pointcomputationsfollowtheIEEE754specification.Inparticular,therearethreespecialfloating-pointvaluestodenoteoverflowsanderrors:
•Positiveinfinity(正无穷大)•Negativeinfinity(负无穷大)•NaN(notanumber)Forexample,theresultofdividingapositivenumberby0ispositiveinfinity.Computing0/0orthesquarerootofanegativenumberyieldsNaN.
11.Theconstants(常量)Double.POSITIVE_INFINITY,Double.NEGATIVE_INFINITY,andDouble.NaN(aswellascorrespondingFloatconstants)representthesespecialvalues,buttheyarerarelyusedinpractice.Inparticular,youcannottestif(x==Double.NaN)//isnevertruetocheckwhetheraparticularresultequalsDouble.NaN.All“notanumber”valuesareconsidereddistinct.However,youcanusetheDouble.isNaNmethod:
if(Double.isNaN(x))//checkwhetherxis"notanumber".Floating-pointnumbersarenotsuitableforfinancialcalculationsinwhichroundofferrorscannotbetolerated.Forexample,thecommandSystem.out.println(2.0-1.1)prints0.8999999999999999,not0.9asyouwouldexpect.Suchroundofferrorsarecausedbythefactthatfloating-pointnumbersarerepresentedinthebinarynumbersystem.Thereisnoprecisebinaryrepresentationofthefraction1/10,justasthereisnoaccuraterepresentationofthefraction1/3inthedecimalsystem.Ifyouneedprecisenumericalcomputationswithoutroundofferrors,usetheBigDecimalclass,whichisintroducedlaterinthischapter.
12.Thechartypeisusedtodescribeindividualcharacters.Mostcommonly,thesewillbecharacterconstants.Forexample,'A'isacharacterconstantwithvalue65.Itisdifferentfrom"A",astringcontainingasinglecharacter.Unicodecodeunitscanbeexpressedashexadecimalvaluesthatrunfrom\u0000to\uFFFF.Forexample,\u2122isthetrademarksymbol(™)and\u03C0istheGreekletterpi(π).Besidesthe\uescapesequences(转义字符)thatindicatetheencoding(编码)ofUnicodecodeunits,thereareseveralescapesequencesforspecialcharacters,asshowninTable3.3.Youcanusetheseescapesequencesinsidequotedcharacterconstantsandstrings,suchas'\u2122'or"Hello\n".The\uescapesequence(butnoneoftheotherescapesequences)canevenbeusedoutsidequotedcharacterconstantsandstrings.Forexample,publicstaticvoidmain(String\u005B\u005Dargs)
Important:
isperfectlylegal—\u005Band\u005Daretheencodingsfor[and].
13.Youcannotconvertbetweenintegersandbooleanvalues.YoualsocannotuseaJavareservedwordforavariablename.Youcanhavemultipledeclarationsonasingleline:
inti,j;//bothareintegers.Asyousaw,namesarecasesensitive,forexample,hiredayandhireDayaretwoseparatenames.Ingeneral,youshouldnothavetwonamesthatonlydifferintheirlettercase.
14.Afteryoudeclareavariable(变量),youmustexplicitly(明确的)initialize(初始化)itbymeansofanassignment(赋值)statement—youcanneverusethevalueofanuninitializedvariable.
15.Thekeywordfinalindicatesthatyoucanassigntothevariableonce,andthenitsvalueissetonceandforall.Itiscustomarytonameconstantsinalluppercase.ItisprobablymorecommoninJavatocreateaconstantsoit’savailabletomultiplemethodsinsideasingleclass.Theseareusuallycalledclassconstants.Setupaclassconstantwiththekeywordsstaticfinal.Hereisanexampleofusingaclassconstant:
publicclassConstants2
{
publicstaticfinaldoubleCM_PER_INCH=2.54;
publicstaticvoidmain(String[]args)
{
^^^^^^;
}
}
Notethatthedefinitionoftheclassconstantappearsoutsidethemainmethod.Thus,theconstantcanalsobeusedinothermethodsofthesameclass.Furthermore,iftheconstantisdeclared,asinourexample,public,methodsofotherclassescanalsouseit—inourexample,asConstants2.CM_PER_INCH.
16.Thereisaconvenientshortcutforusingbinary(二元运算符)arithmeticoperatorsinanassignment.Forexample,x+=4;isequivalenttox=x+4;(Ingeneral,placetheoperator(运算符)totheleftofthe=sign,suchas*=or%=.)
inta=2*++m;//nowais16,mis8
intb=2*n++;//nowbis14,nis8
17.Totestforequalityyouuseadoubleequalsign,==.Forexample,thevalueof3==7isfalse.Usea!
=forinequality.Forexample,thevalueof3!
=7istrue.Finally,youhavetheusual<(lessthan),>(greaterthan),<=(lessthanorequal),and>=(greaterthanorequal)operators.Javauses&&forthelogical“and”operatorand||forthelogical“or”operator.Asyoucaneasilyrememberfromthe!
=operator,theexclamationpoint!
isthelogicalnegationoperator.The&&and||operatorsareevaluatedin“shortcircuit”fashion:
Thesecondargumentisnotevaluatedifthefirstargumentalreadydeterminesthevalue.Ifyoucombinetwoexpressionswiththe&&operator,expression1&&expression2andthetruthvalueofthefirstexpressionhasbeendeterminedtobefalse,thenitisimpossiblefortheresulttobetrue.Thus,thevalueforthesecondexpressionisnotcalculated.Thisbehaviorcanbeexploited(利用)toavoiderrors.Forexample,intheexpressionx!
=0&&1/x>x+y//nodivisionby0thesecondpartisneverevaluatedifxequalszero.Thus,1/xisnotcomputedifxiszero,andnodivide-by-zeroerrorcanoccur.Similarly,thevalueofexpression1||expression2isautomaticallytrueifthefirstexpressionistrue,withoutevaluatingthesecondexpression.Whenappliedtobooleanvalues,the&and|operatorsyieldabooleanvalue.Theseoperatorsaresimilartothe&&and||operators,exceptthatthe&and|operatorsarenotevaluatedin“shortcircuit”fashion.Thatis,bothargumentsareevaluatedbeforetheresultiscomputed.Finally,Javasupportstheternary(三元运算符)?
:
operatorthatisoccasionallyuseful.Theexpressioncondition?
expression1:
expression2evalu
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Java notes