java学习资料Word文档下载推荐.docx
- 文档编号:16180384
- 上传时间:2022-11-21
- 格式:DOCX
- 页数:20
- 大小:37.64KB
java学习资料Word文档下载推荐.docx
《java学习资料Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《java学习资料Word文档下载推荐.docx(20页珍藏版)》请在冰豆网上搜索。
}
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++<
<
operator,thesefunctionscanbeusedtoprintvaluesofanytype.Forexample,allofthefollowingarefine:
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
Oneoperand(theleftone)isaString,sotheotheroperandisconvertedfromaninttoaString,andthetwostringsareconcatenated,producingthevalue:
20"
Evaluationoftheargumenttoprintlncontinues,producingasthefinalvaluetheStringshownabove(notethat\nmeansthenewlinecharacter):
y:
TESTYOURSELF#1
Assumethefollowingdeclarationshavebeenmade:
Whatisprintedwheneachofthefollowingstatementsisexecuted?
System.out.println(x+y);
System.out.println(x+y+"
!
printing:
+x+y);
+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
thecompiler,whencalledw/-cflag;
forexample:
g++-cmain.cc
compilesmain.cccreatingmain.o
objectcode(notexecutable)
sourcecodeiscompiled,butnotlinked/loaded
ExecutableFiles
thecompiler(no-cflag)
executablecode
Codeiscompiledifnecessary,thenlinkedandloaded.
Thesearethefilesthatyoucanactuallyrun,justbytyping
thenameofthefile.
name:
default=a.out
anyothernameispossibleviathe-oflag;
g++main.o-otest
createsanexecutablenamed"
test"
AJavaprogrammerdealswithsourcefilesandbytecodefiles(noexecutablefiles):
.java
createdby:
Javasourcecode(oneormoreclassesperfile)
restrictions:
(1)eachsourcefilecancontainatmostonepublicclass
(2)ifthereisapublicclass,thentheclassnameandfilenamemustmatch
Examples
Ifasourcefilecontainsthefollowing:
publicclassTest{...}
classFoo{...}
classBar{...}
thenitmustbeinafilenamedTest.java
Ifasourcefilecontainsthefollowing:
classTest{...}
thenitcanbeinany"
.java"
file
Smalldigression:
∙Everyfunctionmustbepartofaclass.
∙Everyclassispartofapackage(packagesarediscussedinalatersetofnotes.).
∙Apublicclasscanbeusedinanypackage.
∙Anon-publicclasscanonlybeusedinitsownpackage.
Endofdigression.
BytecodeFiles:
.class
theJavacompiler
Javabytecodes,readytobe"
executed"
--reallyinterpreted--by
theJavainterpreter
names:
foreachclassinasourcefile(bothpublicandnon-publicclasses),
thecompilercreatesone"
.class"
file,wherethefilenameisthe
sameastheclassname
Example
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"
extension;
whenrunningaprogram,youjusttypethenameoftheclasswhosemainfunctionyouwanttorun.
TESTYOURSELF#2
WriteacompleteJavaprogramthatusesalooptosumthenumbersfrom1to10andprintstheresultlikethis:
Thesumis:
xxx
Note:
Usevariabledeclarations,andafororwhileloopwiththesamesyntaxasinC++.
Makesurethatyouareabletocompileandexecuteyourprogram!
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
//setthe1stelementofthearraypointedtobyA
∙InbothC++andJavayoucaninitializeanarrayusingvaluesincurlybraces.Here'
sexampleJavacode:
∙int[]A={1,222,0};
//Apointstoanarrayoflength3
∙//containingthevalues1,222,and0
∙InJava,adefaultinitialvalueisassignedtoeachelementofanewlyallocatedarrayifnoinitialvalueisspecified.Thedefaultvaluedependsonthetypeofthearrayelement:
Type
Value
false
'
\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]
∙InJava,youcancopyanarrayusingthearraycopyfunction.Liketheoutputfunctionprintln,arraycopyisprovidedinjava.lang.System,soyoumustusethenameSystem.arraycopy.Thefunctionhasfiveparameters:
src:
thesourcearray(thearrayfromwhichtocopy)
srcPos:
thestartingpositioninthesourcearray
dst:
thedestinationarray(thearrayintowhichtocopy)
dstPos:
thestartingpositioninthedestinationarray
count:
howmanyvaluestocopy
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 学习 资料
![提示](https://static.bdocx.com/images/bang_tan.gif)