Java程序设计(中英双语版).pdf

随着互联网技术的发展及应用的普及,众多高等院校的计算机和非计算机专业均将

Java程序设计课程作为程序设计的入门课程或者程序设计的进阶课程。

全书共11章,内容主要为:Introduction(简介);JavaFoundation(Java基础);

ClassesandObjects(类和对象);Packages(包);Inheritance(继承);AbstractClass,

Interface(抽象类、接口);GenericsandCollections(泛型与集合);ExceptionHandling

(异常处理);I/O(输入/输出);Multi-threading(多线程);Networking(网络)。

本书适合作为计算机及计算机相近专业的Java程序设计课程的教材,也可作为普通

高等院校面向对象程序设计语言课程的教材和参考书,还可作为软件开发人员及其他有关

人员自学的参考教材或培训教材。

图书在版编目(CIP)数据

Java程序设计:中英双语版/田玉昆,陈伟,谢文兰

主编.—北京:中国铁道出版社有限公司,2019.9

普通高等院校计算机类专业规划教材

ISBN978-7-113-26185-6

Ⅰ.①J…Ⅱ.①田…②陈…③谢…Ⅲ.①JAVA

语言-程序设计-高等学校-教材-汉、英Ⅳ.

①TP312.8

中国版本图书馆CIP数据核字(2019)第181377号

书名:Java程序设计(中英双语版)

作者:田玉昆陈伟谢文兰

责任编辑:唐旭李学敏

封面设计:尚明龙

封面制作:刘颖

责任校对:张玉华

责任印制:郭向伟

出版发行:中国铁道出版社有限公司(100054,北京市西城区右安门西街8号)

网址:/51eds/

印刷:三河市航远印刷有限公司

版次:2019年9月第1版2019年9月第1次印刷

开本:787mm×1092mm1/16印张:14.5字数:346千

书号:ISBN978-7-113-26185-6

定价:45.00元

前言

PREFACE

Java语言具有面向对象、跨平台、安全性、多线程等特点,这使得Java成为许多应用

系统的理想开发语言。Java应用程序运行在众多计算机、手机和智能卡上,并为无数的可兼

容的应用服务器提供了功能强大的平台。未来发展中,Java将成为IT从业者必须掌握的一

门语言,而且在金融、电信、制造、银行、移动通信、电力、交通、市政服务、政务管理等

行业的应用日益广泛。为了满足高校对Java程序设计语言课程和双语课程教材的需求,满足

普通高等院校学生和编程爱好者希望快速掌握Java程序开发的基本知识和开发原理的需求,

我们编写了本书。

本书采用中英文对照的方式,将较难理解的英文叙述翻译成对应的汉语(部分简单的英

文内容未作翻译),为读者在基本概念的理解上提供方便。对于书中复杂的知识点则辅以简单、

清晰的代码,并将运行结果附于代码之后,方便读者比较学习。

全书共11章:Chapter1Introduction(简介),主要介绍Java语言的特点、工

作环境与Java的基本工作原理,使读者对Java语言有一个基本的了解;Chapter2Java

Foundation(Java基础),主要介绍数据类型、常量与变量、表达式和流程控制语句等;

Chapter3ClassesandObjects(类和对象),主要介绍Java类与对象的基本概念、构造方法、

对象的初始化等内容,包括Java面向对象的特征等;Chapter4Packages(包),介绍了包

的概念和组织结构,在此基础上,讲述了包的创建、导入及使用;Chapter5Inheritance(继

承),继承是OOP的一个重要内容,本章在类的基础上介绍了继承的基本概念及构造方法的

调用,对不同类型访问控制符的作用进行了比较,最后对OOP的另一个重要内容多态作了简

要介绍;Chapter6AbstractClass,Interface(抽象类、接口),阐述了抽象方法、抽象类

的定义与使用,接口的定义与实现,接口与抽象类的比较以及内部类的定义与使用等内容;

Chapter7GenericsandCollections(泛型与集合),介绍了泛型的概念、泛型类、泛型接

口与泛型方法的定义与使用,以及集合类的概念、框架结构和几种常用的容器的使用方法;

Chapter8ExceptionHandling(异常处理),介绍了异常产生的原因、异常的类型,以及

如何抛出和处理异常;Chapter9I/O(输入/输出),介绍了输入/输出流的概念,以及如

何通过输入流读取数据,向输出流写入数据;Chapter10Multithreading(多线程),阐述

了多线程的概念,线程与进程的区别,线程的生命周期与创建方法、线程同步与线程间的通信

等;Chapter11Networking(网络),介绍了Java网络编程技术,描述了Java的网络编

程功能。全书对不易理解的内容的细致分析,从学生学习的角度阐述核心概念,具有很强的实

用性和适用性。

本书由田玉昆、陈伟、谢文兰任主编,徐光明、崔彦君、魏文芬任副主编,黄国范、张艳梅、

曾兰参与编写。吴学曼对本书的编写给予了专业性的指导,在此表示感谢。

本书的出版得到了广东培正学院教材立项支持,在此表示衷心的感谢。

编者

2019年6月

目录

CONTENTS

Chapter1Introduction(简介)1

1.1CharacteristicsofJava(Java的特点)1

1.2Developingtools(开发工具)2

1.2.1Interpretedlanguagevscompiledlanguage(解释性语言与编译性语言)2

1.2.2JavaVirtualMachine(虚拟机)3

1.2.3JavaRuntimeEnvironment(运行环境)4

1.2.4JavaDevelopmentKit(开发工具)4

1.3AsimpleJavaprogram(一个简单的Java程序)5

1.3.1HowtorunaJavaprogram(如何运行Java程序?)5

1.3.2RulesofnamingaJavasourcefile(Java源文件的命名规则)6

1.3.3Rulesofnamingclasses,variablesandmethods(类、变量和方法的命名规则)7

Exercises8

Chapter2JavaFoundation(Java基础)9

2.1Primitivedatatypes(基本数据类型)9

2.1.1Integerandoatingpointtypes(整型与浮点型)10

2.1.2Booleantype(布尔型)11

2.1.3Charactertype(字符型)11

2.2Referencetypes(引用型)12

2.2.1Aclassisadatatype(类是数据类型)13

2.2.2Aclasstypevariableisareference(类类型的变量是引用)14

2.2.3Interfacetype(接口类型)16

2.3Identiers(标识符)16

2.4Defaultvaluesofelds(成员变量的默认值)16

2.5Wheredatastore(数据存储在何处?)18

2.6Operators(运算符)19

2.6.1Arithmeticoperators(算术运算符)19

2.6.2Logicaloperators(逻辑运算符)19

I

Java程序设计(中英双语版)

2.6.3Bitwiseoperators(位运算符)20

2.6.4Leftshift(<<)andsignedrightshift(>>)operators(移位运算符)21

2.6.5Assignmentandconditionaloperators(赋值运算符和条件运算符)22

2.6.6Stringoperator“+”and“+=”(字符串运算符“+”和“+=”)22

2.6.7Specialoperators(特殊运算符)23

2.7Casting(类型转换)23

2.7.1Wideningandnarrowing(拓宽与缩窄)23

2.7.2Char,byteandshortproduceintresults(Char,byte和short转换为int型)25

2.8Flowingcontrol(流程控制)25

2.8.1Basiccontrollingstatements(基本控制语句)26

2.8.2Foreachstatement(foreach语句)26

2.9Arrays(数组)28

2.9.1Definearrays(定义数组)28

2.9.2Initializearrays(初始化数组)28

2.9.3Arraysactasargumentsofmethods(数组做方法的参数)29

2.10Commandlinearguments(命令行参数)30

Exercises31

Chapter3ClassesandObjects(类和对象)33

3.1ConceptsofOOP(面向对象的概念)33

3.1.1EverythingisanObject(万物皆对象)33

3.1.2Definingclasses(定义类)34

3.2Usefulclasses(常用类)34

3.3Methodoverloading(方法重载)39

3.4Constructors(构造方法)40

3.5Defaultconstructor(默认构造方法)43

3.6Staticeldsandmethods(静态成员变量与静态方法)45

3.7Thiskeyword(this关键字)51

3.7.1Anon-staticmethodhasahidden“this”(隐藏参数this的非静态方法)51

3.7.2Astaticmethodhasnoargument“this”(没有this的静态方法)54

3.7.3Callingconstructorsformconstructors(在构造方法里调用其他构造方法)56

3.8Variableargumentlists(可变参数列表)56

3.9Garbagecollection(垃圾回收)58

3.10Enumtype(枚举类型)60

Exercises61

II

Chapter4Packages(包)64

4.1Conceptofpackages(包的概念)64

4.2Javalibraryanditspackagestructure(类库与Java类的包组织结构)65

4.3Createpackages(创建包)66

4.4Importpackages(导入包)68

4.5Packagejava.lang(java.lang包)70

4.6Usefulclassesinpackagejava.lang(java.lang包中常用的类)71

4.6.1ObjectclassanditstoStringmethod(Object类和它的toString方法)71

4.6.2Systemclass(系统类)72

Exercises72

Chapter5Inheritance(继承)74

5.1Whatisinheritance(什么是继承?)74

5.1.1RootclassObject(根类对象)75

5.1.2Definingsubclasses(定义子类)76

5.2Superkeyword(super关键字)78

5.2.1Supercorrespondingtodefaultconstructor(默认构造方法的super)78

5.2.2Supercorrespondingtoconstructorswitharguments(有参构造方法的super)80

5.3Orderofconstructorcalls(构造方法的调用次序)82

5.4Finalkeyword(nal关键字)84

5.4.1Finalfields(final成员)84

5.4.2Finalarguments(常参数)86

5.4.3Finalmethods(常方法)86

5.5Accessspeciers(访问说明符)86

5.6Polymorphism(多态)91

5.6.1Methodoverriding(方法重写)92

5.6.2Upcastinganddynamicpolymorphism(升级转换与动态多态)93

5.6.3Referringtoamemberofthesuperclassbysuperkeyword(用super指向

基类成员)96

5.6.4Hidingfieldsandstaticmethodsofthebaseclass(隐藏静态方法和fields的基类)98

Exercises100

Chapter6AbstractClassandInterface(抽象类和接口)104

6.1Abstractclass(抽象类)105

6.1.1Abstractmethod(抽象方法)105

III

6.1.2Abstractclass(抽象类)105

6.2Interface(接口)106

6.2.1Introduction(简介)106

6.2.2Defininginterfaces(接口的定义)107

6.2.3Implementationofinterfaces(接口的实现)108

6.2.4Comparationofinterfacesandabstractclasses(接口与抽象类的比较)109

6.3Innerclass(内部类)110

6.3.1Membersininnerclass(内部类成员)110

6.3.2Localinnerclass(局部内部类)112

6.3.3Anonymousinnerclass(匿名内部类)113

Exercises115

Chapter7GenericsandCollections(泛型与集合)117

7.1Generics(泛型)117

7.1.1Conceptofgenerics(泛型的概念)117

7.1.2Genericclasses(泛型类)118

7.1.3Typeparametersuse“extends”and“super”keywords(类型参数中

使用extends和super关键字)121

7.1.4Wildcardintypeparameters(类型参数里的通配符)122

7.2Genericinterfaces(泛型接口)122

7.3Genericmethods(泛型方法)122

7.4Collectionclasses(集合类)123

7.4.1Conceptofcollection(container)classes[集合(容器)类的概念]124

7.4.2Thehierarchyofthecollectionframework(集合框架的层次结构)124

7.5List(列表)126

7.6Queue(队列)131

7.7Set(集合)131

7.8Map(映射)133

Exercises135

Chapter8ExceptionHanding(异常处理)137

8.1Conceptsofexception(异常的概念)137

8.1.1Whatisanexception(什么是异常?)137

8.1.2Howtodealwithexceptions(如何处理异常?)138

8.2Exceptionclasses(异常类)140

IV

8.2.1Errorclass(Error类)141

8.2.2Exceptionclass(Exception类)141

8.3Catchanddealwithanexception(捕获与处理异常)144

8.4Throwanexception(抛出一个异常)148

8.5Deneyourownexceptions(用户自定义异常类)152

Exercises153

Chapter9I/O(输入/输出)155

9.1ConceptofI/Ostream(输入/输出流的概念)155

9.2Bytestream(字节流)156

9.2.1InputStream/OutputStream(InputStream/OutputStream类)157

9.2.2FileInputStream/FileOutputStream(FileInputStream/FileOutputStream类)159

9.2.3FilterInputStream/FilterOutputStream(FilterInputStream/

FilterOutputStream类)163

9.2.4DataInputStream/DataOutputStream(DataInputStream/

DataOutputStream类)164

9.2.5BufferedInputStream/BufferedOutputStream(BufferedInputStream/

BufferedOutputStream类)165

9.2.6PrintStream(PrintStream类)166

9.3Characterstreams(字符流)169

9.3.1TextfilevsBinaryfile(文本文件与二进制文件)170

9.3.2Reader/Writer(Reader/Writer类)171

9.3.3InputStreamReader/OutputStreamWriter(InputStreamReader/

OutputStreamWriter类)172

9.3.4FileReader/FileWriter(FileReader/FileWriter类)175

9.3.5BufferReader/BufferWriter(BufferReader/BufferWriter类)178

9.3.6PrintWriter(PrintWriter类)181

9.4Fileclass(文件类)181

Exercises184

Chapter10Multi-threading(多线程)186

10.1Conceptofmulti-threading(多线程的概念)186

10.1.1What’sathread(什么是线程?)186

10.1.2Threadvsprocess(线程与进程)186

10.2Lifecycleofathread(线程的生命周期)188

V

10.3Creatingthreads(创建线程)190

10.3.1Directapproachofcreatingathread(直接法创建线程)190

10.3.2Indirectapproachofcreatingathread(间接法创建线程)192

10.4Mainthread(主线程)194

10.5MethodsofThreadclass(线程类的方法)196

10.6Threadsynchronization(线程同步)199

10.7Communicationbetweenthreads(线程间的通信)202

Exercises203

Chapter11Networking(网络)205

11.1Conceptofnetworking(网络的概念)205

11.2URLclass(URL类)206

11.3Socketscommunication(套接字通信)209

11.3.1HowSocketcommunicationworks(套接字通信是如何进行的?)209

11.3.2Ports(端口)210

11.4ServerSocketandSocketclasses(ServerSocket和Socket类)210

11.4.1Tasksofeachside(双方的任务)211

11.4.2Datatransmission(数据传输)212

11.5Servingmultipleclients(服务多个客户)217

Exercises219

References222

VI

Chapter1Introduction(简介)

Chapter1

Introduction(简介)

Javaisaprograminglanguage.SunreleasedJavain1995.Afteryearsdeveloping,

nowadays,JavaplaysmoreimportantruleinInternet,gameplayandmobile

communicationprogramming.JavaisbasedonC++,isa“pure”object-oriented

programinglanguage.JavainheritstheclassconceptofC++andaddsmulti-thread,

exceptiondealingandotheradvancedtechniques,meanwhileabandonedthepointer

operatorofC++language.

Java是一种程序设计语言,Sun公司于1995年首次发布,经过多年发展,今天Java在互联

网、游戏、移动通信等领域发挥着重要的作用。Java在C++的基础上,成为“完全”的面向对

象的程序设计语言。它继承了C++类的概念,增加了线程、异常处理等先进技术,同时摒弃

了C++语言的“指针”。

1.1CharacteristicsofJava(Java的特点)

ThemaincharacteristicsofJavaareasbelow:

Simple

Object-oriented

Robust

Sophisticatedcompiler

Runtimeexception-handling

Secure

Multi-thread

Cross-platform

1

TherearethreedifferentversionsofJava:

JavaSE(StandardEdition)

JavaEE(EnterpriseEdition)

JavaME(MiniatureEdition)

JavaSEisthestandardversionofJava,whichisusedinthisbook.JavaEEisthe

enterpriseversionofJava.JavaMEistheminiatureversionofJava,whichisappliedto

embedded,mobilephoneandothermobilecommunicationapplications.

JavaSE是Java的标准版,本书使用这个版本。JavaEE是企业版,JavaME是微型版,用

于嵌入式、手机和移动通信方面的应用开发。

1.2Developingtools(开发工具)

InordertodesignaJavaprogram,somedevelopingtoolsareneeded.Javaisan

interpretivelanguage,sothedevelopingtoolsshouldbeadaptedtoit.

1.2.1Interpretedlanguagevscompiledlanguage(解释性语

言与编译性语言)

TorunJavaprograms,thesourcefilesarecompiledtoproducebytecodefiles.The

bytecodeismachine-independent.Torunbytecodefiles,aJavainterpreter,whichispartof

theJavaVirtualMachine(JVM)isneeded.

Tomakeitclear,what“interpretive”means,let’sgobacktoC++language.C++is

acompiledlanguage,allcodesareoncecompiledintoanativemachinelanguagebefore

running.SupposeaC++sourcefilemycpp.cppisprovided,whichiscompiledtoproduce

anobjectfile,amachine-dependent(machinelanguage)file,mycpp.obj.Linkingmycpp.

objwithsomelibraryobjectfiles,anexecutablefilemycpp.exeisproduced,whichcanonly

runonacertainkindofOperatingSystemwhereitiscompiledandlinked.Theconverting

procedureofaC++program,fromasourcefiletoanexecutablefileisasshowninFigure1-1.

运行Java程序前,需要将源程序编译成字节码文件。字节码文件与机器无关,由Java虚

拟机里的解释程序解释后执行。

为了弄清楚什么是“解释性”,让我们回到C++语言。C++是编译性语言,运行前,对源

目标文件为mycpp.obj文件,将mycpp.obj与库文件连接,生成可执行文件mycpp.exe。这个可

执行文件只能运行在对源文件进行编译和连接的那类机器上。源文件到可执行文件的转换过程

如图1-1所示。

2

mycpp.cppcompilermycpp.objlinkermycpp.exerun

Libraryobjectfiles

Figure1-1ConvertingofC++files

Ontheotherhand,aJavasourcefileiscompiledtoproducebytecode(.class)filesonly,

whichcan’trundirectlyonanOperatingSystem.

SupposeaJavasourcefilemyjava.javaisprovided,whichiscompiledtoproduce

oneorseveralbytecodefiles,butunlikeC++executablefiles,theycan’trundirectlyon

anOperatingSystem.Thebytecodefilesarebinarycodefiles,whichmustbeinterpreted

byaJVM,thatis,theyrelyonaJVM.AJavaVirtualMachineexplainsbytecodefiles

andexecutestheexplainedcodes.Withbytecodefiles,Javarealizesthecross-platform

characteristic,“compilationonce,executioneverywhere”.Bytecodefilescanrunondifferent

JVMs,LinuxJVM,WindowsJVM,…,UnixJVM.

TheconvertingprocedureofJavaprogramfilesisshowninFigure1-2.

myjava.javaJavaconeorseveral.classfilesJVM1

JVM2

.

JVMN

Figure1-2ConvertingofJavafiles

Java源程序仅仅被编译成字节码文件,即一个或多个.class文件。字节码文件是二进制文件,

不能直接在某个操作系统上运行,它必须由Java虚拟机JVM解释并运行。只要有JVM,字节

码文件可以在任何类型的机器上运行,具有一次编译、处处运行的跨平台特性。

1.2.2JavaVirtualMachine(虚拟机)

AJavavirtualmachine(JVM)isasoftwarecomputingmachinethatenablesacomputer

torunaJavaprogram.ThearchitectureofaJVMisshowninFigure1-3.Therearefourmain

unitsinit.

ClassLoader

BytecodeVerifier

Interpreter

Just-in-timecompiler(JIT)

JVM是Java虚拟机,是用软件实现的处理器,用于运行Java程序,其组成如图1-3所示,

它包含4个主要模块。

3

InterpreterJust-in-timeCompiler

Figure1-3StructureofJavavirtualmachine

Abytecode(.class)filecontainsbinarycodesofaJavaclass.Theclassloaderrecognizes

andloadsJava.classfilestomemory.Thebytecodeverifierverifiesallbytecodebeforeitis

interpretedandexecuted.

Fordifferentmachines,differentJVMsareneeded.AslongasacorrespondingJVMis

installedonacomputer,thecomputercanrunanyJavabytecodeprograms.

一个字节码文件对应一个Java类的二进制代码,它由JVM的类装载器(ClassLoader)装

入指定的存储空间,并被字节码检验器(JavaVerifier)检查,再由JVM的解释器(Interpreter)

解释并执行。

不同类型的计算机需要不同的JVM。只要计算机安装了对应的JVM,就可以运行任意

Java字节码程序。

Javabytecodeexecuteswhileinterpreting,theexecutionwillalwaysbeslowerthanthe

executionofthecodesthatarecompiledintoanativemachinelanguage.Thisproblemis

solvedbythejust-in-time(JIT)compiler.AJITcompilercantranslateJavabytecodeintoa

nativemachinelanguagewhileexecutingtheprogram.Forsomefrequentlyusedcodes,the

translatedpartsoftheprogramcanbeexecutedmuchmorequickly.

1.2.3JavaRuntimeEnvironment(运行环境)

JavaRuntimeEnvironment(JRE)isasoftwarepackage,whichcontainstheJavavirtual

machineandtheJavaclasslibrary.

Java运行环境是个软件包,包含JVM和Java类库。

1.2.4JavaDevelopmentKit(开发工具)

Ifyouwanttowriteprograms,youneedtoprepareJavaDevelopmentKit(JDK).JDK

containsJavaRuntimeEnvironment(JRE)anddevelopingtools:Javacompiler“Javac”

forcompilingaJavasourcefile,Javainterpreter“Java”forexplainingandrunningJava

bytecode.JDKisasupersetofaJRE.Itisfreeofcharge.Thelatestversion1.8ofJDKis

availableat/

JDK是开发Java程序的开发工具,包含Java运行环境JRE,Java编译器“Javac”和Java

解释器“Java”。

4

1.3AsimpleJavaprogram(一个简单的Java程序)

【Example1-1】HelloWorld.java

classHelloWorld{

publicstaticvoidmain(Stringargs[]){

System.out.println("HelloWorld!");

}

Thefunctionofthisprogramistoprint“HelloWorld!”.AJavaprogramiscomposedof

oneormoreclasses,atleastoneclass.Thisprogramcontainsaclass“HelloWorld”,which

hasamethod“main”.ThemainisthestartpointtoexecutetheJavaprogram,whichisthe

sameasC++program.Aclassthatcontainsthemethodmainisreferredtoasthemainclass.

Aclasscanhaveseveralmethods.

Amethodisacollectionofstatements,justlikeafunctionofCorC++program.Inthis

example,thereisonlyonestatementinmethodmain,whichoutputs“HelloWorld!”tothe

screen.

这个程序的功能是在显示器上输出“HelloWorld!”。Java程序由一个或多个类组成,至

少一个类。这个程序包含一个“HelloWorld”类,类里有个称为main的方法。与C++类似,

main是程序执行的入口,包含main方法的类是主类,类可以包含很多方法。

方法是语句的集合,与C或C++的函数类似。此例中,main中只有一条输出“Hello

World!”的语句。

1.3.1HowtorunaJavaprogram(如何运行Java程序?)

Figure1-4showsthestepsofaJavasourceprogramhowiscompiled,isexecutedand

outputs“HelloWorld!”tothescreen.

HelloWorld.javaJavacHelloWorld.classJavaOutput

Figure1-4ProcedureofrunningaJavafile

SupposeyouareinaMicrosoftWindowsOperatingSystem,JDKisinstalledatyour

computersuccessfully,andthesourcefileisattherootofdiskf.Youneedtogointo

commandwindow,CMDWindowfirst.Whenyouarethere,thescreenlookslike:

C:\Users\Administrator>_

Typeincommand“f:”atthecursorandpressEnterkey,youenterintotherootofdiskf.

F:\>_

Typein“javacHelloWorld.java”,callsthecompilertocompilethesourcefile

HelloWorld.java,forinstance:

F:\>javacHelloWorld.java

5

IftherearenoerrorsintheHelloWorld.java,thenabytecodefileHelloWorld.classis

produced.ToruntheHelloWorld.class,youneedtocallinterpreteroftheJVMbytyping

commandjava.

F:\>javaHelloWorld

“HelloWorld!”isseen.

1.3.2RulesofnamingaJavasourcefile(Java源文件的命名规则)

AJavasourcefileisconsistsofoneormoreclasses.Thefilenamemustfollowsome

rules.Filenamingrules:

(1)Thefilenamemustbethesameastheclassnameifonlyoneclassdeclarationexists.

(2)Atmost,onlyoneclassispublicandthefilenamemustbethenameofthepublic

class.Ifmorethanoneclassesneedtobepublic,thesourcefileshouldbesplitintoseveral

sourcefiles.

(3)Withoutthemainclass(aclassthatcontainsthemainmethodiscalledthemain

class),ifthereareseveralclassesandnoneispublicinafile,thefilenamecanbeanyoneof

theclassnames.

(4)Ifasourcefilecontainsthemainclass,thefilenamemustbethesameasthemain

class.

Java源文件包含一个或多个类,文件的命名必须遵循特定的规则。文件的命名规则如下:

(1)如果源文件里只有一个类,文件名必须是该类的类名。

(2)每个源文件里至多只能有一个public类,并且文件名必须是该public类的名字。如

果一个源文件里的多个类都需要设成public,要将这个源文件分解成多个源文件。

(3)在没有主类的情况下(含有main方法的类称为主类),如果源文件里有多个类,并

且每个类都不是public,文件名可以是其中任何一个类的类名。

(4)如果源文件里包含主类,则文件名必须是主类的类名。

【Example1-2】Twoclassesexistinafile,noneispublic

classFirst{

staticStringMessage="HelloJava!";

classSecond{

publicvoidhello(){

System.out.println(First.Message);

ThefilenamecanbeFirst.javaorSecond.java.Aftersuccessfullycompiled,two

bytecodefiles:First.classandSecond.classareproduced.Butwithoutthemainclass,they

can’trunalone.

6

【Example1-3】Twonon-publicclassesexistinafile,oneisthemainclass

staticStringmessage="HelloJava!";

System.out.println(First.message);

ThefilenamemustbeSecond.java,becausethemainmethodinit.ClassSecondisthe

mainclass.

【Example1-4】Twopublicclassesneeded,afilemustbesplitintotwo

publicclassFirst{//First.java

【Example1-5】Twopublicclassesneeded,afilemustbesplitintotwo

publicclassSecond{//Second.java

Noticethatthenumberof.classfilesisindependentofthenumberofsourcefiles,but

thenumberofclasses.Example1-3producestwo.classfiles,example1-4andexample1-5

totallyproducetwo.classfiles,First.classandSecond.class.

1.3.3Rulesofnamingclasses,variablesandmethods

(类、变量和方法的命名规则)

Choosemeaningfulnames.

1.Classes

Capitalizethefirstletterofeachwordinthename,forinstanceComputeArea.

2.Variablesandmethods

Uselowercase.Ifthenameconsistsofseveralwords,concatenateallinone,use

lowercaseforthefirstword,andcapitalizethefirstletterofeachsubsequentwordinthe

name,forinstancecomputeArea.

3.Constants

Capitalizealllettersinconstants,anduseunderscorestoconnectwords,forinstancePI,

MAX_VALUE.

名字要体现用意。

7

1.类名

大写每个单词的第一个字母,例如,ComputeArea。

2.变量和方法名

用小写字母。如果名字包含多个单词,小写第一个单词,大写其后的每个单词的第一个字母,

例如,ComputeArea。

3.常数名

大写所有字母,用下划线连接不同单词,例如,PI,MAX_VALUE。

Exercises

1.InstallJDKandconfigureenvironmentvariables.

2.Write,compileandrunprogramHelloWorld.java.

8

Chapter2JavaFoundation(Java基础)

Chapter2

JavaFoundation(Java基础)

ThischapterwillintroduceyouthebasicconceptsofJava.

SupposeallstudentshavelearntCorC++programminglanguage,sosome

subjectsinCorC++willnotberepeatedordescribedwithfewerwords,soastowe

canfocusonnewanddifferentsubjectsofJava.

2.1Primitivedatatypes(基本数据类型)

Javahastwokindsofdatatypes,referenceandprimitive.Primitivedatatypesare

providedbyJavaprogramlanguage.Javadeterminesthesizeofavariableoftheprimitive

datatype.ThereareeightprimitivedatatypesinJava(seeTable2-1).

1.Integer

(1)byte(1byte).

(2)short(2bytes).

(3)int(4bytes).

(4)long(8bytes).

2.Floatingpoint

(1)float(4bytes).

(2)double(8bytes).

3.Textual

char(2bytes).

9

4.Logical

boolean(1byte).

Thesizeofaprimitivetypevariableremainsthesameonallplatforms(standardized).

AlltheprimitivedatatypesandtheirsizesarelistedinTable2-1.

THE END
1.Java语言下载详解,入门安装与配置全攻略摘要:本篇文章提供了关于Java语言下载的详细指南,包括入门、安装与配置的全过程。文章详细介绍了如何获取Java开发环境,并成功安装与配置Java开发工具,为初学者提供了简单易懂的教程。通过阅读本文,读者可以轻松掌握Java语言的下载及安装过程,为后续的Java开发打下坚实的基础。 http://m.qiuruikeji.cn/post/86.html
2.Java资源大全中文版(Awesome最新版)javalibrary中文版Java资源大全中文版(Awesome最新版) Awesome系列的Java资源整理。awesome-java 就是akullpp发起维护的Java资源列表,内容包括:构建工具、数据库、框架、模板、安全、代码分析、日志、第三方库、书籍、Java 站点等等。 经典的工具与库 (Ancients) In existence since the beginning of time and which will continue beinghttps://blog.csdn.net/zhangguo5/article/details/62423362
3.javalibrary最新入口javalibrary中文版javalibrary最新入口 javalibrary中文版 Big Faceless Java PDF Library是一个敏捷的Java类库,用于创建、编辑、显示和打印Acrobat PDF文档。它提供的PDI API函数灵巧而快捷,方便您在您的工程中使用,并且全部是由Java编写而成的。 The Big Faceless Java PDF Library is the smartest Java class library for creating,https://blog.51cto.com/u_16099193/7488017
4.JavaLibraryJava Library API Session (for Kluis) Signature Positioning Guide PDFSigner Class Java SignatureSetting Model Licensing of Library Signer.Digital Server and SOAP API Signer.Digital Server System Requirements Signer.Digital Server Console SOAP API Settings https://help.signer.digital/java_library.htm
5.java4directories0files0 Btotal ListGrid Up 2_2_6/—10/19/2023, 12:59:27 PM 2_3_4/—10/19/2023, 12:58:35 PM 3_0_5/—11/5/2024, 3:08:27 PM 4_0_3/—11/5/2024, 2:54:17 PMhttps://mirror.sjtu.edu.cn/apache/santuario/java-library/
6.嘘偷偷告诉你JavaLibrary最新版本号的藏身之处嘿嘿,是不是又在满世界找Java Library的最新版本号?别急,今儿个哥儿们就带你探探这神秘的地界。 “版本号,你躲哪儿去了?” 话说这版本号啊,它就跟那顽皮的孩子似的,最爱跟你玩捉迷藏。你说你找它容易吗?它偏不,非得让你满头大汗、焦急万分。 http://m.omtfs.com/fszx/4176041c93.html
7.www.jxmzxx.com/appnews/017379此外,香港知名影星周润发也到场参赛,与粉丝合照。 据悉,赛事由香港机场管理局及渣打银行(香港)有限公司冠名赞助、中国香港田径总会主办,是渣打香港马拉松特别纪念版赛事,目的是庆祝香港国际机场三条跑道即将全面投入运作,巩固香港国际航运中心地位。(完) 《光明日报》(2024-11-19 03:03:08版)http://www.jxmzxx.com/appnews/017379
8.IMSLJavaLibraryJava应用程序的高等数学和统正版价格品牌:IMSL Java Library软件名称:IMSL Java Library | Java应用程序的高等数学和统计学版本语言:英文版 软件类型:编程软件版本号:***系统平台要求:Windows 系统硬件要求:-版权:正版配套附件:软件序列号 技术支持:正版软件版本类型:商业、 教育中文名称:Java应用程序的高等数学和统计学 http://reachsoft.cn.china.cn/supply/5046585906.html
9.Java程序设计(中英双语版)20240109155923.pdf海量文档 计算机 JavaJava程序设计(中英双语版).pdf 235页内容提供方:中国铁道出版社有限公司 大小:6.07 MB 字数:约42.56万字 发布时间:2024-01-09发布于四川 浏览人气:90 下载次数:仅上传者可见 收藏次数:0 需要金币:*** 金币 (10金币=人民币1元)Javahttps://m.book118.com/html/2024/0109/8045105110006024.shtm
10.《javalibrary最新》在线观看免费4k完整版javalibrary最新选集观看 第1集 第2集 第3集 第4集 第5集 第6集 第7集 第8集 第9集 第10集 第11集 第12集 第13集 第14集 第15集 第16集 第17集 第18集 第19集 第20集 第21集 第22集 第23集 第24集 第25集 第26集 第27集 第28集 第29集 第30集 第31集 第32集 第33集 第34集 https://www.gotuky5.com/kaoyan/2670.html
11.日本javalibrary官方版免费手机版版本:1.5.1 类别:二次元 大小:79MB 时间:2024-10-30 09:20 软件介绍 日本javalibrary国泰君安地产团队也较为看好央企和国企地产,其表示如严格执行资金监管并假设销售下滑,央企和国企的销售份额预计提升30%~110%,“当前某大型房企事件持续发酵,金融市场仅向央企和国企提供融资,那么具备短期偿债风险和极端假设不再https://www.yifen.com/IoS/434527821.htm
12.javalibrary蚁工厂 11-16 14:53 来自 微博网页版 转发抽3本 @博文视点Broadview 的新书《编程导航,全栈项目实战课——从零带做 Java 代码生成器平台》。@微博抽奖平台 11月23日从转发里抽3人各得一本。Java基础入门书。想学好编程,就必须多实践。“卷王”作者鱼皮,善于把Java全栈项目讲得通俗易懂,积累了几十个独立项目https://m.weibo.cn/search?containerid=100103&q=javalibrary
13.《javalibrary最新》在线观看高清完整3、《javalibrary最新》是什么时候上映/什么时候开播的? 网友:2022年,详细日期也可以去百度百科查询。 4、《javalibrary最新》如果播放卡顿怎么办? 百度贴吧网友:播放页面卡顿可以刷新网页或者更换播放源。 5、手机版免费在线点播《javalibrary最新》哪些网站还有资源? 网友:芒果TV、爱奇艺、优酷视频百度视频 6、《javahttp://www.wangdai555.com/xy/38608-2-1.html
14.javalibrary新地址在哪–手机爱问javalibrary新地址在哪: 演示机型:华为MateBook X系统版本:win10APP版本:IntelliJ IDEAhttps://m.iask.sina.com.cn/b/new1z8xeycLGZ3F.html
15.productionenvironmentswasnotfoundonthejava.libraryApache Tomcat的本地库,允许在生产环境中的最佳性能并没有发现上的java.library.path:C:\程序文件\ JAVA \ jdk1.6.0_06 \ bin中,C:\程序文件\ Apache软件基金会\ Tomcat 6.0的\ BIN 翻译结果2复制译文编辑译文朗读译文返回顶部 【目录】【首页】【上一页】【下一页】【末页】第38 http://xibolaiyu.zaixian-fanyi.com/fan_yi_5603560
16.使用SpringBoot和DJL(DeepJavaLibrary)轻松搭建企业级机器Original article:https://aws.amazon.com/blogs/opensource/adopting-machine-learning-in-your-microservices-with-djl-deep-java-library-and-spring-boot/ Author: Mikhail Shapirov Reworked by: Qing Lan 前言 许多AWS云服务的用户,无论是初创企业还是大公司,都在逐步将机器学http://aws.amazon.com/cn/blogs/china/use-spring-boot-and-djl-deep-java-library-to-easily-build-enterprise-level-machine-learning-microservices/
17.java框架在人工智能应用中的优势有哪些?java教程java 框架因其健壮性、可扩展性和易用性而成为人工智能应用开发的理想选择,它提供自动化和效率,集成和互操作性,定制灵活性,以及性能和可扩展性。实战案例包括apacheopennlp(nlp)、deepjavalibrary(图像识别)和 weka(机器学习)。java 框架为人工智能应用提供了强大的基础,使其成为 ai 开发人员的首选语言。 https://m.php.cn/faq/814571.html
18.Gradlejvm插件系列教程之JavaLibrary插件权威详解java标准Java插件和Java Library插件之间的关键区别在于后者引入了向消费者公开的API概念。Java库是供其他组件消费的Java组件。在多项目构建中这是非常常见的用例,也适用于外部依赖。 该插件公开了两个配置,用于声明依赖项:api和implementation。api配置应该用于声明由库API导出的依赖项,而implementation配置应该用于声明组件内部https://www.jb51.net/program/311054zp3.htm
19.JavaLibraryReferenceAttributeClass(Java.Interop)[System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple=true)] [System.Obsolete("This attribute is no longer supported.", true)] public class JavaLibraryReferenceAttribute : Android.ReferenceFilesAttributeInheritance Attribute ReferenceFilesAttribute JavaLibraryReferenceAttribute Attributeshttps://docs.microsoft.com/zh-hk/dotnet/api/java.interop.javalibraryreferenceattribute
20.javalibrary.zip直接在opencv官网下载windows版本下载后,即可得到opencv-451.jar和opencv_java451.dll,可以愉快的开发及测试,但是测通过之后需要部署到服务器,服务器是centos环境,jar包是跨平台的,但是dll不能,所以只能下载最新版的opencv源码,进行编译安装,并且打包成静态文件,大家只需要把libopencv_java451.so放到 java.library.pathhttps://www.iteye.com/resource/weixin_42696192-11987057
21.deepjavalibrary/djl:一款Java语言的深度学习框架中文 Java 主语言 是 活跃 123 贡献者 161 Issues 是 组织 0.31.0 最新版本 663 Forks Apache-2.0 协议 更多 介绍 这是亚马逊开源的 Java 语言深度学习框架。对于 Java 开发者而言,可以在 Java 中开发及应用原生的机器学习和深度学习模型,同时简化了深度学习开发的难度。通过 DJL 提供直观的、高级的 API,Javahttps://hellogithub.com/repository/6baca61314ce42a58fa5778de0995c5e
22.JavaPDFLibraryandB2BPDFSoftwareSolutionsBig Faceless PDF Library A Java class library for creating, editing, displaying and printing PDF Version 2.28.8, released 06 Dec 2024 Know more BFO Publisher A modern HTML to PDF converter Version 1.3, released 01 Aug 2023 Know more http://big.faceless.org/
23.JavaLibrary类代码示例本文整理汇总了Java中com.android.builder.model.Library类的典型用法代码示例。如果您正苦于以下问题:Java Library类的具体用法?Java Library怎么用?Java Library使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。 Library类属于com.android.builder.model包,在下文中一共展示了Library类的5个代码示例https://vimsky.com/examples/detail/java-class-com.android.builder.model.Library.html
24.AndroidLibrary和AndroidAPPJavaLibrary的区别以及如何删除当你需要构建不同的APK,但这些APK有共同核心功能时。例如:你的APP有免费版和付费版,但是它们有相同的核心功能。 在这两种情况下,只需将要重用的文件移动到Android Library中,然后将library添加为每个APP模块的依赖项,APP就能直接调用library中的功能,而不需要关心library的具体实现。 https://www.jianshu.com/p/959074cfe0d6
25.Library(图书馆图书管理系统)一个简化版的 C++ 学生信息管理系统的框架,包括一些基本功能,如添加、显示、搜索和删除学生信息 2024-12-06 13:55:09 积分:1 基于springboot的校园社团管理系统+高分项目+源码.7z 2024-12-06 13:10:26 积分:1 基于C# 的仓库管理系统+源码+高分项目.7z 2024-12-06 13:06:30 积分:1 在Java中从https://www.coder100.com/index/index/content/id/1184536