The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
The Java programming language is statically-typed, which means that all variables must first be declared before they can be used.Java编程语言是静态类型的,这意味着必须先声明所有变量,然后才能使用它们。This involves stating the variable's type and name, as you've already seen:这涉及到声明变量的类型和名称,正如您已经看到的:
int gear = 1;
Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1".这样做会告诉您的程序,一个名为“gear”的字段存在,它保存数值数据,初始值为“1”。A variable's data type determines the values it may contain, plus the operations that may be performed on it.变量的数据类型决定了它可能包含的值,以及可能对其执行的操作。In addition to 除了int
, the Java programming language supports seven other primitive data types.int
之外,Java编程语言还支持其他七种基本数据类型。A primitive type is predefined by the language and is named by a reserved keyword.基元类型由语言预定义,并由保留关键字命名。Primitive values do not share state with other primitive values.基本值不与其他基本值共享状态。The eight primitive data types supported by the Java programming language are:Java编程语言支持的八种基本数据类型是:
byte: The :byte
data type is an 8-bit signed two's complement integer.byte
数据类型是一个8位有符号2的补码整数。It has a minimum value of -128 and a maximum value of 127 (inclusive).它的最小值为-128,最大值为127(含)。The byte
data type can be useful for saving memory in large arrays, where the memory savings actually matters.byte
数据类型对于在大型数组中节省内存非常有用,而实际上节省内存很重要。They can also be used in place of 它们也可以用来代替int
where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.int
,因为它们的限制有助于澄清代码;变量的范围是有限的这一事实可以作为文档的一种形式。
short: The :short
data type is a 16-bit signed two's complement integer.short
数据类型是一个16位有符号2的补码整数。It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).它的最小值为-32768,最大值为32767(含)。As with 与byte
, the same guidelines apply: you can use a short
to save memory in large arrays, in situations where the memory savings actually matters.byte
一样,同样的准则也适用:在内存节省非常重要的情况下,可以使用short
来在大型数组中节省内存。
int: By default, the :默认情况下,int
data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1.int
数据类型是32位带符号2的补码整数,最小值为-231,最大值为231-1。In Java SE 8 and later, you can use the 在Java SE 8及更高版本中,可以使用int
data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1.int
数据类型表示无符号32位整数,该整数的最小值为0,最大值为232-1。Use the Integer class to use 使用int
data type as an unsigned integer.Integer
类将int
数据类型用作无符号整数。See the section The Number Classes for more information.有关更多信息,请参阅数字类一节。Static methods like 向compareUnsigned
, divideUnsigned
etc have been added to the Integer
class to support the arithmetic operations for unsigned integers.Integer
类添加了静态方法,如compareUnsigned
、divideUnsigned
等,以支持无符号整数的算术运算。
long: The :long
data type is a 64-bit two's complement integer.long
数据类型是64位2的补码整数。The signed long has a minimum value of -263 and a maximum value of 263-1.有符号long的最小值为-263,最大值为263-1。In Java SE 8 and later, you can use the 在Java SE 8及更高版本中,可以使用long
data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1.long
数据类型来表示无符号的64位long
,其最小值为0,最大值为264-1。Use this data type when you need a range of values wider than those provided by 当需要比int
.int
提供的值更宽的值范围时,请使用此数据类型。The Long
class also contains methods like compareUnsigned
, divideUnsigned
etc to support arithmetic operations for unsigned long.Long
类还包含compareUnsigned
、divideUnsigned
等方法,以支持无符号长整型的算术运算。
float: The :float
data type is a single-precision 32-bit IEEE 754 floating point.float
数据类型是单精度32位IEEE 754浮点。Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification.它的值范围超出了本文讨论的范围,但在Java语言规范的浮点类型、格式和值部分中有详细说明。As with the recommendations for 与byte
and short
, use a float
(instead of double
) if you need to save memory in large arrays of floating point numbers.byte
和short
的建议一样,如果需要在大型浮点数数组中保存内存,请使用float
(而不是double
)。This data type should never be used for precise values, such as currency.此数据类型不应用于精确值,如货币。For that, you will need to use the java.math.BigDecimal class instead.为此,您将需要使用java.math.BigDecimal类。Numbers and Strings covers 数字和字符串讲解了BigDecimal
and other useful classes provided by the Java platform.BigDecimal
和Java平台提供的其他有用类。
double: The :double
data type is a double-precision 64-bit IEEE 754 floating point.double
数据类型是双精度64位IEEE 754浮点。Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification.它的值范围超出了本文讨论的范围,但在Java语言规范的浮点类型、格式和值部分中有详细说明。For decimal values, this data type is generally the default choice.对于十进制值,此数据类型通常是默认选择。As mentioned above, this data type should never be used for precise values, such as currency.如上所述,此数据类型不应用于精确值,如货币。
boolean: The :boolean
data type has only two possible values: true
and false
.boolean
数据类型只有两个可能的值:true
和false
。Use this data type for simple flags that track true/false conditions.将此数据类型用于跟踪真/假条件的简单标志。This data type represents one bit of information, but its "size" isn't something that's precisely defined.此数据类型表示一位信息,但其“大小”并不是精确定义的。
char: The :char
data type is a single 16-bit Unicode character.char
数据类型是单个16位Unicode字符。It has a minimum value of 它的最小值为'\u0000'
(or 0) and a maximum value of '\uffff'
(or 65,535 inclusive).'\u0000'
(或0),最大值为'\uffff'
(或65535)。
In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class.除了上面列出的八种基本数据类型之外,Java编程语言还通过java.lang.String类提供对字符串的特殊支持。Enclosing your character string within double quotes will automatically create a new 将字符串括在双引号内将自动创建一个新的String
object; for example, String s = "this is a string";
.String
对象;例如,String s = "this is a string";
。String
objects are immutable, which means that once created, their values cannot be changed.String
对象是不可变的,这意味着一旦创建,它们的值就不能更改。The String
class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such.String
类在技术上不是一种原始数据类型,但是考虑到该语言对它的特殊支持,您可能会这样认为。You'll learn more about the 您将在简单数据对象中了解有关String
class in Simple Data ObjectsString
类的更多信息
It's not always necessary to assign a value when a field is declared.声明字段时并不总是需要赋值。Fields that are declared but not initialized will be set to a reasonable default by the compiler.已声明但未初始化的字段将由编译器设置为合理的默认值。Generally speaking, this default will be zero or 一般来说,此默认值将为零或null
, depending on the data type.null
,具体取决于数据类型。Relying on such default values, however, is generally considered bad programming style.然而,依赖这些默认值通常被认为是糟糕的编程风格。
The following chart summarizes the default values for the above data types.下图总结了上述数据类型的默认值。
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | '\u0000' |
String (or any object) | null |
boolean | false |
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable.局部变量略有不同;编译器从不为未初始化的局部变量指定默认值。If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it.如果无法在声明局部变量的位置初始化它,请确保在尝试使用它之前为其赋值。Accessing an uninitialized local variable will result in a compile-time error.访问未初始化的局部变量将导致编译时错误。
You may have noticed that the 您可能已经注意到,初始化基元类型的变量时不使用new
keyword isn't used when initializing a variable of a primitive type.new
关键字。Primitive types are special data types built into the language; they are not objects created from a class.基元类型是语言中内置的特殊数据类型;它们不是从类创建的对象。A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation.文字是固定值的源代码表示形式;文本直接在代码中表示,无需计算。As shown below, it's possible to assign a literal to a variable of a primitive type:如下图所示,可以将文本分配给基元类型的变量:
boolean result = true; char capitalC = 'C'; byte b = 100; short s = 10000; int i = 100000;
An integer literal is of type 如果整型文字以字母long
if it ends with the letter L
or l
; otherwise it is of type int
.L
或l
结尾,则其类型为long
;否则它是int
类型。It is recommended that you use the upper case letter 建议您使用大写字母L
because the lower case letter l
is hard to distinguish from the digit 1
.L
,因为小写字母l
很难与数字1
区分。
Values of the integral types 整型byte
, short
, int
, and long
can be created from int
literals.byte
、short
、int
和long
的值可以从int文本创建。Values of type 超过long
that exceed the range of int
can be created from long
literals.int
范围的long
类型的值可以从long
文本创建。Integer literals can be expressed by these number systems:整数文字可以用以下数字系统表示:
For general-purpose programming, the decimal system is likely to be the only number system you'll ever use.对于通用编程来说,十进制可能是您唯一使用的数字系统。However, if you need to use another number system, the following example shows the correct syntax.但是,如果需要使用其他数字系统,下面的示例将显示正确的语法。The prefix 前缀0x
indicates hexadecimal and 0b
indicates binary:0x
表示十六进制,0b
表示二进制:
// The number 26, in decimal int decVal = 26; // The number 26, in hexadecimal int hexVal = 0x1a; // The number 26, in binary int binVal = 0b11010;
A floating-point literal is of type 如果浮点文字以字母float
if it ends with the letter F
or f
; otherwise its type is double
and it can optionally end with the letter D
or d
.F
或f
结尾,则它的类型为float
;否则它的类型是double
,并且可以选择以字母D
或d
结尾。
The floating point types (浮点类型(float
and double
) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).float
和double
)也可以使用E
或e
(用于科学记数法)、F
或f
(32位浮点文字)和D
或d
(64位double
文字;这是默认值,按照惯例省略)。
double d1 = 123.4; // same value as d1, but in scientific notation double d2 = 1.234e2; float f1 = 123.4f;
Literals of types char
and String
may contain any Unicode (UTF-16) characters.char
和String
类型的文本可以包含任何Unicode(UTF-16)字符。If your editor and file system allow it, you can use such characters directly in your code.如果编辑器和文件系统允许,可以直接在代码中使用这些字符。If not, you can use a "Unicode escape" such as 如果不允许,您可以使用“Unicode转义”,例如'\u0108'
(capital C with circumflex), or "S\u00ED Se\u00F1or"
(Sí Señor in Spanish).'\u0108'
(大写字母C加扬抑符)或"S\u00ED Se\u00F1or"
(西班牙语中的Sí Señor)。Always use 'single quotes' for 始终对char
literals and "double quotes" for String
literals.char
文本使用“单引号”,对String
文本使用“双引号”。Unicode escape sequences may be used elsewhere in a program (such as in field names, for example), not just in Unicode转义序列可以在程序的其他地方使用(例如在字段名中),而不仅仅是在char
or String
literals.char
或String
文本中。
The Java programming language also supports a few special escape sequences for Java编程语言还支持char
and String
literals: \b
(backspace), \t
(tab), \n
(line feed), \f
(form feed), \r
(carriage return), \"
(double quote), \'
(single quote), and \\
(backslash).char
和String
文本的一些特殊转义序列:\b
(退格),\t
(制表符),\n
(换行符),\f
(换行符),\r
(回车符),\"
(双引号),\'
(单引号)和\\
(反斜杠)。
There's also a special 还有一个特殊的null
literal that can be used as a value for any reference type.null
文本,可以用作任何引用类型的值。null
may be assigned to any variable, except variables of primitive types.null
可以分配给任何变量,但基元类型的变量除外。There's little you can do with a 除了测试null
value beyond testing for its presence.null
值的存在性之外,您对null
值几乎无能为力。Therefore, 因此,null
is often used in programs as a marker to indicate that some object is unavailable.null
通常在程序中用作标记,表示某些对象不可用。
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending "最后,还有一种特殊的文本,称为类文本,它是由类型名和附加“.class"
; for example, String.class
..class
”组成的;例如,String.class
。This refers to the object (of type 这是指表示类型本身的对象(Class
) that represents the type itself.Class
类型)。
In Java SE 7 and later, any number of underscore characters (在JavaSE7及更高版本中,数字文字中数字之间的任意位置都可以出现任意数量的下划线字符(_
) can appear anywhere between digits in a numerical literal._
)。This feature enables you, for example. to separate groups of digits in numeric literals, which can improve the readability of your code.例如,此功能使您能够,以数字文字分隔数字组,这可以提高代码的可读性。
For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.例如,如果代码包含多个数字的数字,则可以使用下划线字符将数字分成三组,类似于使用逗号或空格等标点符号作为分隔符。
The following example shows other ways you can use the underscore in numeric literals:以下示例显示了在数字文本中使用下划线的其他方法:
long creditCardNumber = 1234_5678_9012_3456L; long socialSecurityNumber = 999_99_9999L; float pi = 3.14_15F; long hexBytes = 0xFF_EC_DE_5E; long hexWords = 0xCAFE_BABE; long maxLong = 0x7fff_ffff_ffff_ffffL; byte nybbles = 0b0010_0101; long bytes = 0b11010010_01101001_10010100_10010010;
You can place underscores only between digits; you cannot place underscores in the following places:只能在数字之间加下划线;不能在以下位置放置下划线:
F
or L
suffixF
或L
后缀之前The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:以下示例演示了数字文字中有效和无效的下划线位置(突出显示):
// Invalid: cannot put underscores // adjacent to a decimal point float pi1 = 3_.1415F; // Invalid: cannot put underscores // adjacent to a decimal point float pi2 = 3._1415F; // Invalid: cannot put underscores // prior to an L suffix long socialSecurityNumber1 = 999_99_9999_L; // OK (decimal literal) int x1 = 5_2; // Invalid: cannot put underscores // At the end of a literal int x2 = 52_; // OK (decimal literal) int x3 = 5_______2; // Invalid: cannot put underscores // in the 0x radix prefix int x4 = 0_x52; // Invalid: cannot put underscores // at the beginning of a number int x5 = 0x_52; // OK (hexadecimal literal) int x6 = 0x5_2; // Invalid: cannot put underscores // at the end of a number int x7 = 0x52_;