java学习资料.docx
- 文档编号:3274837
- 上传时间:2022-11-21
- 格式:DOCX
- 页数:20
- 大小:37.64KB
java学习资料.docx
《java学习资料.docx》由会员分享,可在线阅读,更多相关《java学习资料.docx(20页珍藏版)》请在冰豆网上搜索。
java学习资料
JAVAvsC++
Contents
∙SimpleExampleJavaProgram
oTestYourself#1
∙Files
oTestYourself#2
∙JavaTypes
oC++ArraysvsJavaArrays
▪TestYourself#3
▪TestYourself#4
oC++ClassesvsJavaClasses
oAliasingProblemsinJava
▪TestYourself#5
oTypeConversion
▪TestYourself#6
∙AnswerstoSelf-StudyQuestions
InJava,everyvariable,constant,andfunction(includingmain)mustbeinsidesomeclass.Here'sasimpleexampleprogram:
classTest{
publicstaticvoidmain(String[]args)
{
System.out.println("Helloworld!
");
}
}
Thingstonote:
1.Thereisnofinalsemi-colonattheendoftheclassdefinition.
2.FunctionmainisamemberofclassTest.
3.Ingeneral,mainmust:
oBeinsidesomeclass(therecanbemorethanonemainfunction--therecanevenbeoneineveryclass!
)
oBepublicstaticvoid.
oHaveoneargument:
anarrayofString.Thisarraycontainsthecommand-linearguments.Youcanuseargs.lengthtodeterminethenumberofarguments(thenumberofStringsinthearray).
4.Towritetostandardoutput,youcanuseeitherofthefollowing:
5.System.out.println(...)
6.System.out.print(...)
Theformerprintsthegivenexpressionfollowedbyanewline,whilethelatterjustprintsthegivenexpression.
LiketheC++< System.out.print("hello");//printaString System.out.print(16);//printaninteger System.out.print(5.5*.2);//printafloating-pointnumber The+operatorcanbeusefulwhenprinting.ItisoverloadedtoworkonStringsasfollows: IfeitheroperandisaString,it 1.convertstheotheroperandtoaString(ifnecessary) 2.createsanewStringbyconcatenatingbothoperands Example intx=20,y=10; System.out.println("x: "+x+"\ny: "+y); Theoutputis: x: 20 y: 10 Thisisbecausetheargumenttoprintlnisanexpressionoftheform: op1+op2+op3+op4 Theonlyoperatoris+,sotheexpressionisevaluatedleft-to-right(iftherewereanotheroperatorwithhigherprecedence,thesub-expressioninvolvingthatoperatorwouldbeevaluatedfirst).Theleftmostsub-expressionis: "x: "+x Oneoperand(theleftone)isaString,sotheotheroperandisconvertedfromaninttoaString,andthetwostringsareconcatenated,producingthevalue: "x: 20" Evaluationoftheargumenttoprintlncontinues,producingasthefinalvaluetheStringshownabove(notethat\nmeansthenewlinecharacter): x: 20 y: 10 TESTYOURSELF#1 Assumethefollowingdeclarationshavebeenmade: intx=20,y=10; Whatisprintedwheneachofthefollowingstatementsisexecuted? System.out.println(x+y); System.out.println(x+y+"! "); System.out.println("printing: "+x+y); System.out.println("printing: "+x*y); solution C++FilesvsJavaFiles AC++programmerdealswithsourcefiles,objectfiles,andexecutablefiles: SourceFiles: .hand.cc(or.cppor.C) createdby: you(theprogrammer) contain: C++sourcecode twokinds: .h(headerfiles) containclassdefinitionsandfunctionspecifications (justheaders-nobodies) mustbeincludedbyeveryfilethatusestheclass/callsthe functions .cccontainimplementationsofclassmemberfunctionsand"free"functions, includingthemainfunction ObjectFiles: .o createdby: thecompiler,whencalledw/-cflag;forexample: g++-cmain.cc compilesmain.cccreatingmain.o contain: objectcode(notexecutable) sourcecodeiscompiled,butnotlinked/loaded ExecutableFiles createdby: thecompiler(no-cflag) contain: executablecode Codeiscompiledifnecessary,thenlinkedandloaded. Thesearethefilesthatyoucanactuallyrun,justbytyping thenameofthefile. name: default=a.out anyothernameispossibleviathe-oflag;forexample: g++main.o-otest createsanexecutablenamed"test" AJavaprogrammerdealswithsourcefilesandbytecodefiles(noexecutablefiles): SourceFiles: .java createdby: you(theprogrammer) contain: Javasourcecode(oneormoreclassesperfile) restrictions: (1)eachsourcefilecancontainatmostonepublicclass (2)ifthereisapublicclass,thentheclassnameandfilenamemustmatch Examples Ifasourcefilecontainsthefollowing: publicclassTest{...} classFoo{...} classBar{...} thenitmustbeinafilenamedTest.java Ifasourcefilecontainsthefollowing: classTest{...} classFoo{...} classBar{...} thenitcanbeinany".java"file Smalldigression: ∙Everyfunctionmustbepartofaclass. ∙Everyclassispartofapackage(packagesarediscussedinalatersetofnotes.). ∙Apublicclasscanbeusedinanypackage. ∙Anon-publicclasscanonlybeusedinitsownpackage. Endofdigression. BytecodeFiles: .class createdby: theJavacompiler contain: Javabytecodes,readytobe"executed"--reallyinterpreted--by theJavainterpreter names: foreachclassinasourcefile(bothpublicandnon-publicclasses), thecompilercreatesone".class"file,wherethefilenameisthe sameastheclassname Example Ifasourcefilecontainsthefollowing: publicclassTest{...} classFoo{...} classBar{...} thenaftercompilingyouwillhavethreefiles: Test.class Foo.class Bar.class Here'showtocompileandruntheexample"helloworld"programgivenabove,assumingthatitisinafilenamed"tst.java": 1.tocompilethesourcecode,type: javactst.java 2.toruntheinterpreterusingthenameoftheclasswhosemainfunctionyouwanttorun,type: javaTest Remember,whencompilingaprogram,youtypethefullfilename,includingthe".java"extension;whenrunningaprogram,youjusttypethenameoftheclasswhosemainfunctionyouwanttorun. TESTYOURSELF#2 WriteacompleteJavaprogramthatusesalooptosumthenumbersfrom1to10andprintstheresultlikethis: Thesumis: xxx Note: Usevariabledeclarations,andafororwhileloopwiththesamesyntaxasinC++. Makesurethatyouareabletocompileandexecuteyourprogram! solution JavaTypes InJava,therearetwo"categories"oftypes: primitivetypesandreferencetypes: PrimitiveTypes boolean sameasboolinC++ char holdsonecharacter byte 8-bitsignedinteger short 16-bitsignedinteger int 32-bitsignedinteger long 64-bitsignedinteger float floating-pointnumber double doubleprecisionfloating-pointnumber ReferenceTypes arrays classes Notes: 1.nostruct,union,enum,unsigned,typedef 2.arraysandclassesarereallypointers! ! C++ArraysvsJavaArrays ∙InC++,whenyoudeclareanarray,storageforthearrayisallocated.InJava,whenyoudeclareanarray,youarereallyonlydeclaringapointertoanarray;storageforthearrayitselfisnotallocateduntilyouuse"new": ∙C++ ∙ ∙intA[10];//Aisanarrayoflength10 ∙A[0]=5;//setthe1stelementofarrayA ∙ ∙ ∙JAVA ∙ ∙int[]A;//Aisapointertoanarray ∙A=newint[10];//nowApointstoanarrayoflength10 ∙A[0]=5;//setthe1stelementofthearraypointedtobyA ∙InbothC++andJavayoucaninitializeanarrayusingvaluesincurlybraces.Here'sexampleJavacode: ∙int[]A={1,222,0};//Apointstoanarrayoflength3 ∙//containingthevalues1,222,and0 ∙InJava,adefaultinitialvalueisassignedtoeachelementofanewlyallocatedarrayifnoinitialvalueisspecified.Thedefaultvaluedependsonthetypeofthearrayelement: Type Value boolean false char '\u0000' byte,int,short,int,long,float,double 0 anypointer null ∙InJava,anout-of-boundsarrayindexalwayscausesaruntimeerror. ∙InJava,youcandeterminethecurrentlengthofanarray(atruntime)using".length": ∙int[]A=newint[10]; ∙...A.length...//thisexpressionevaluatesto10 ∙A=newint[20]; ∙...A.length...//nowitevaluatesto20 TESTYOURSELF#3 WriteaJavafunctioncalledNonZeros,usingtheheadergivenbelow.NonZerosshouldcreateandreturnanarrayofintegerscontainingallofthenon-zerovaluesinitsparameterA,inthesameorderthattheyoccurinA. publicstaticint[]NonZeros(int[]A) WriteacompleteJavaprogramthatincludesamainfunctionaswellastheNonZerosfunction.ThemainfunctionshouldtestNonZerosbycreatingseveralarrays,andcallingNonZeroswitheacharray.ItshouldprintthearrayitpassestoNonZerosaswellasthereturnedarray.Soforexample,whenyourunyourprogram,youroutputmightlooklikethis(ifyourNonZerosfunctionisimplementedcorrectly): passing[0,1,2,3,2]gotback[1,2,3,2] passing[0,0]gotback[] passing[22,0,-5,0,126]gotback[22,-5,126] passing[1,0]gotback[1] solution ∙InJava,youcancopyanarrayusingthearraycopyfunction.Liketheoutputfunctionprintln,arraycopyisprovidedinjava.lang.System,soyoumustusethenameSystem.arraycopy.Thefunctionhasfiveparameters: src: thesourcearray(thearrayfromwhichtocopy) srcPos: thestartingpositioninthesourcearray dst: thedestinationarray(thearrayintowhichtocopy) dstPos: thestartingpositioninthedestinationarray count: howmanyvaluestocopy Here'sanexample: int[]A,B; A=newint[10]; --codetoputvaluesintoA-- B=newint[5]; System.arraycopy(A,0,B,0,5)//copiesfirst5valuesfromAtoB System.arraycopy(A,9,B,4,1)//copieslastvaluefromAinto //lastelementofB Notethatthedestinationarraymustalreadyexist(i
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- java 学习 资料