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+Swing图书管理系统2.0java四、其它1.其他系统实现2.获取源码一、系统介绍该系统实现了用户: 书籍查询,借书,还书功能。用户能够查询自己的借书记录。管理员: 上架图书,下架图书,添加图书类别,添加图书信息,修改图书信息,添加借书证信息、查询借书证信息、删除除借书证,查询图书借阅归还记录。二、功能展示 1.管理员登陆 2.图书https://blog.csdn.net/pangjiaqian/article/details/144179557
2.javalibrary情报图书馆mob64ca12f09e0c的技术博客LibraryUserLibraryUseraddBook("Java Programming")addBook("Data Structures")findBook("Java Programming")truefindBook("Algorithm Design")false 通过以上步骤,你已经成功搭建了“javalibrary 情报图书馆”。希望这篇教程能帮助你更好地理解和应用Java编程技术。如果有任何问题,欢迎随时向我提问!https://blog.51cto.com/u_16213432/10641820
3.嘘偷偷告诉你JavaLibrary最新版本号的藏身之处嘿嘿,是不是又在满世界找Java Library的最新版本号?别急,今儿个哥儿们就带你探探这神秘的地界。 “版本号,你躲哪儿去了?” 话说这版本号啊,它就跟那顽皮的孩子似的,最爱跟你玩捉迷藏。你说你找它容易吗?它偏不,非得让你满头大汗、焦急万分。 http://m.omtfs.com/fszx/4176041c93.html
4.javalibrary中文[沉默的糕点]2024最新更新最新章节列表javalibrary中文由沉默的糕点创作,代表作有?,内容简介:又是一次双方满意的会面,不过在最后分别的时候,杨晨却又给了毛启一个不确定的答复:“少门主的丹药好说,不过五转灵芝玉露丹,在下也不敢保证一次成功,所以,时间上可能会拖长几年,千万谅解。”拓者阁免费提供https://tuozhe8.com/Inews3ab/20241116_057gi
5.通学技术/JavaLibrary本藏馆主要珍藏Java体系核心技术书籍:涵盖Java核心基石(Java核心技术,并发编程,JVM)Java助辅要员(设计模式,linux内核,TCP/IP协议,Netty,Tomcat,Mysql) 上古单体架构 分布式朝代 微服务纪元 云原生前沿 架构演进 自动化运维 Star 1 Watch 1 README.md JavaLibrary 重磅推出:Java体系知识图谱,持续完善中。。。 本https://gitee.com/alvin33/JavaLibrary/
6.www.jxmzxx.com/appnews/017379据央视新闻报道,11月14号,国际金价直接跌破了每盎司2600美元的大关,这可是两个月以来的最低价了! 咱们国内的黄金珠宝品牌也没能幸免,跟着国际金价一起跳水。比如周生生,11月14号的时候报价是774元/克,比11月1号的时候整整跌了51元/克;周大福呢,足金饰品也从826元/克掉到了775元/克,也是跌了51元/克。 http://www.jxmzxx.com/appnews/017379
7.www.sjzyl99.com/moken54718.html老鹰队,小南斯16分4篮板3助攻2抢断,里萨谢10分4篮板,卡佩拉9分10篮板,出现5次犯规,难以限制约基奇的内线单打。特雷杨15分4篮板10助攻3抢断,前3节仅仅得到3分。丹尼尔斯18分4篮板6助攻5抢断,展现了全能的身手。奥孔武14分9篮板,亨特20中7得到20分3篮板,进攻效率有待提升。 http://www.sjzyl99.com/moken54718.html
8.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
9.java框架在人工智能应用中的优势有哪些?java教程java 框架因其健壮性、可扩展性和易用性而成为人工智能应用开发的理想选择,它提供自动化和效率,集成和互操作性,定制灵活性,以及性能和可扩展性。实战案例包括apacheopennlp(nlp)、deepjavalibrary(图像识别)和 weka(机器学习)。java 框架为人工智能应用提供了强大的基础,使其成为 ai 开发人员的首选语言。 https://m.php.cn/faq/814571.html
10.IMSLJavaLibraryJava应用程序的高等数学和统正版价格技术支持:正版软件版本类型:商业、 教育中文名称:Java应用程序的高等数学和统计学 产品介绍Product introduction 使用IMSL Java Library可节省高达 95% 的源代码开发时间,以及数千美元的设计、开发、文档、测试和维护成本。 IMSL Java Library为跨所有行业的应用程序、数据库和商业智能解决方案提供了一组经过验证的 Javahttp://reachsoft.cn.china.cn/supply/5046585906.html
11.使用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/
12.JavaPDFLibraryandB2BPDFSoftwareSolutionsBig Faceless Graph Library Version 2.4.9, released 25 May 2023 What our clients say: Support team was excellent. Fast to respond. Admioson theBig Faceless Report Generator Our Products: Big Faceless PDF Library A Java class library for creating, editing, displaying and printing PDF http://big.faceless.org/
13.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
14.《javalibrary》免费在线观看高清完整版javalibrary简介:javalibrary简介讲诉了藤沼悟是一个三流漫画家,但是他却拥有着名为“再上映”(可以穿越到事件发生之前的时间点,阻止事件发生,但失败了会一直重复)的能力。详情 立即播放 无需安装任何插件 草莓视频 第01集 第02集 《javalibrary》剧情简介 【javalibrary】 https://www.xueshanlinghu.com/cover/211549.html
15.javalibrary.zipAlgorithm-codelibrary.zip,算法和数据结构的集合,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。 上传者:weixin_38744153时间:2019-09-17 javacv-platform-1.5.4-bin.zip javacv-platform-1.5.4-bin,javacv运行所需jar包,包含samples https://www.iteye.com/resource/weixin_42696192-11987057
16.《javalibrary》动作,剧情,惊悚,英国,2015简介:javalibrary简介讲诉了在广袤的荣耀国,辛巴和娜娜的第二个孩子——凯安。在一次玩耍时无意之间唤醒了自己体内的强大力量——至尊狮吼。于是,他便在爸爸的命令之下,和他的朋友们组建了一支新的队伍—— 立即播放剧情简介 关键词:梅格雷探案 第二季 探案 探长 西默农 杀人案 侦破 该剧 javalibrary简介讲诉了https://www.azs.org.cn/cover/208966.html
17.javalibrary转发抽3本 @博文视点Broadview 的新书《编程导航,全栈项目实战课——从零带做 Java 代码生成器平台》。@微博抽奖平台 11月23日从转发里抽3人各得一本。Java基础入门书。想学好编程,就必须多实践。“卷王”作者鱼皮,善于把Java全栈项目讲得通俗易懂,积累了几十个独立项目的开发经验,GitHub中国区 全文 127 https://m.weibo.cn/search?containerid=100103&q=javalibrary
18.javalibrary最新HD国语高清在线观看视频大全手机免费观看简介:距离死亡大桥还有一段距离,冲/锋/枪扫射和手/榴/弹炸开的声音应接不暇。远远望去,大桥桥面上已经成了停车场,几辆几辆残破成废铁的车辆还在冒火。韩雪感觉她可以吃下详情 立即播放收藏 javalibrary最新剧情简介 距离死亡大桥还有一段距离,冲/锋/枪扫射和手/榴/弹炸开的声音应接不暇。远远望去,大桥https://www.xdyy8.com/tags/gerenanquanchengnuoduanju.html
19.TheJavaLibraryPluginThe Java Library plugin expands the capabilities of theJava Plugin (java)by providing specific knowledge about Java libraries. In particular, a Java library exposes an API to consumers (i.e., other projects using the Java or the Java Library plugin). All the source sets, tasks and configuratihttps://docs.gradle.org/current/userguide/java_library_plugin.html
20.《javalibrary最新》在线观看免费4k完整版javalibrary最新上映于2014年,由玛塔·马祖雷克,郑善京,Duvauchelle,保罗·穆勒,雅太郎,Savoy,Emile,小林龙树,Pervine,凯瑞·福克斯,章小蕙,Edy,杉浦峰夫主演;影片讲述:此时的苏青,将自己的父亲苏焕然更是恨了个底朝天,起初自己也是不理她的,毕竟在幽冥山这样献殷勤的弟https://www.gotuky5.com/kaoyan/2670.html
21.javalibrary新地址在哪–手机爱问javalibrary新地址在哪: 演示机型:华为MateBook X系统版本:win10APP版本:IntelliJ IDEAhttps://m.iask.sina.com.cn/b/new1z8xeycLGZ3F.html