Documentation

The Java™ Tutorials
Hide TOC
Primitive Data Types基本数据类型
Trail: Learning the Java Language
Lesson: Language Basics
Section: Variables

Primitive Data Types基本数据类型

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编程语言支持的八种基本数据类型是:

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 Objects您将在简单数据对象中了解有关String类的更多信息

Default Values默认值

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.下图总结了上述数据类型的默认值。

Data Type数据类型 Default Value (for fields)默认值(用于字段)
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.访问未初始化的局部变量将导致编译时错误。

Literals直接常量

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;

Integer Literals整数文字

An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int.如果整型文字以字母Ll结尾,则其类型为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.整型byteshortintlong的值可以从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;

Floating-Point Literals浮点文字

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.如果浮点文字以字母Ff结尾,则它的类型为float;否则它的类型是double,并且可以选择以字母Dd结尾。

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).浮点类型(floatdouble)也可以使用Ee(用于科学记数法)、Ff(32位浮点文字)和Dd(64位double文字;这是默认值,按照惯例省略)。

double d1 = 123.4;
// same value as d1, but in scientific notation
double d2 = 1.234e2;
float f1  = 123.4f;

Character and String Literals字符和字符串文本

Literals of types char and String may contain any Unicode (UTF-16) characters.charString类型的文本可以包含任何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 '\u0108' (capital C with circumflex), or "S\u00ED Se\u00F1or" (Sí Señor in Spanish).如果不允许,您可以使用“Unicode转义”,例如'\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 char or String literals.Unicode转义序列可以在程序的其他地方使用(例如在字段名中),而不仅仅是在charString文本中。

The Java programming language also supports a few special escape sequences for char and String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash).Java编程语言还支持charString文本的一些特殊转义序列:\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.classThis refers to the object (of type Class) that represents the type itself.这是指表示类型本身的对象(Class类型)。

Using Underscore Characters in Numeric Literals在数字文本中使用下划线字符

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal.在JavaSE7及更高版本中,数字文字中数字之间的任意位置都可以出现任意数量的下划线字符(_)。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:只能在数字之间加下划线;不能在以下位置放置下划线:

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_;

Previous page: Variables
Next page: Arrays