对象将它的状态存储在变量中。
变量 是一个由标志符命名的数据项。变量有三个属性:
1. 名称: 程序通过变量的名称引用变量的值。
2. 数据类型: 每个变量都必须有一个数据类型。变量的数据类型决定此变量可以包含的
值 以及可以在它上面执行的
操作 。
3. 作用范围: 可以在其中使用此变量的简单名称来引用它的程序区域。Java支持的
原始数据类型 及默认值:
| Data Type | Default Value (for fields,not for local variables) |
|---|
| byte | 0 |
| short | 0 |
| int | 0 |
| long | 0L |
| float | 0.0f |
| double | 0.0d |
| char | "u0000" |
| String (or any object) | null |
| boolean | false |
与原始类型相比,引用类型变量的值是对由此变量代表的一个或一组值的引用 (也就是地址),也就是C语言中的指针(内存地址 )。在final变量被初始化后,它的值不能被修改。声明变量时要显示地设置变量的名称和类型。原始类型的变量包含一个值。引用类型的变量包含对一个或一组值的引用。操作符 在一个、两个或三个操作数上执行一种操作,并返回一个值。Java中含有的操作符,如下表:
Operator Precedence | Operators | Precedence |
|---|
| postfix | expr ++ expr -- |
| unary | ++expr --expr +expr -expr ~ ! |
| multiplicative | * / % |
| additive | + - |
| shift | << >> >>> |
| relational | < > <= >= instanceof |
| equality | == != |
| bitwise AND | & |
| bitwise exclusive OR | ^ |
| bitwise inclusive OR | | |
| logical AND | && |
| logical OR | || |
| ternary | ? : |
| assignment | = += -= *= /= %= &= ^= |= <<= >>= >>>= |
表达式 是一系列变量、操作符和方法调用,用于求出单个值。
语句 组成了一个完整的执行单元。The
if statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code
only if a particular test evaluates to
true .
The
switch statement can have a number of possible execution paths. A
switch works with the
byte ,
short ,
char , and
int primitive data types. It also works with
enumerated types , the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer. The
while statement continually executes a block of statements while a particular condition is
true . Its syntax can be expressed as:
- while (expression)
- {
- statement(s)
- }
The
for statement provides a compact way to iterate over a range of values. The general form of the
for statement can be expressed as follows:
- for (initialization; termination; increment)
- {
- statement(s)
- }
An unlabeled
break statement terminates the innermost
switch ,
for ,
while , or
do-while statement, but a labeled
break terminates an outer statement.
- class BreakWithLabelDemo
- {
- public static void main(String[] args)
- {
- int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 },
- { 622, 127, 77, 955 } };
- int searchfor = 12;
- int i;
- int j = 0;
- boolean foundIt = false;
- search: for (i = 0; i < arrayOfInts.length; i++)
- {
- for (j = 0; j < arrayOfInts[i].length; j++)
- {
- if (arrayOfInts[i][j] == searchfor)
- {
- foundIt = true;
- break search;
- }
- }
- }
- if (foundIt)
- {
- System.out.println("Found " + searchfor + " at " + i + ", " + j);
- }
- else
- {
- System.out.println(searchfor + " not in the array");
- }
- }
- }
The
continue statement skips the current iteration of a
for ,
while , or
do-while loop. The
return statement exits from the current method, and control flow returns to where the method was invoked.