例题1:下列程序的输出结果是多少?
public class Test {
static {
int x = 5;
}
static int x, y;
public static void main(String[] args) {
x--;
myMethod();
System.out.println(x + y++ + x);
}
public static void myMethod() {
y = x++ + ++x;
}
}
解析
public class Test {
static {
int x = 5;//在第一次被载入JVM时运行,但由于是局部变量,x = 5不影响后面的值
}
static int x, y;//初始化 x = 0; y = 0
public static void main(String[] args) {
x--;//x = -1
myMethod();
System.out.println(x + y++ + x);//1 + 0 + 1 = 2;
}
public static void myMethod() {
y = x++ + ++x;//y = -1 + 1;
}
}
//输出结果为2
例题2:下列程序的输出结果是多少?
import java.util.*;
public class Test {
public static void main(String[] args) {
int j = 0;
for (int i = 0; i < 100; i++) {
j = j++;
}
System.out.println(j);
}
}
解析:因为Java用了中间缓存变量的机制,所以j=j++可换成如下写法:
temp = j;
j = j + 1;
j = temp;
//所有输出结果为0
例题3:下列代码的执行结果是多少?
import java.util.*;
public class Test {
public static void main(String[] args) {
int i = 0;
i = i++ + ++i;
int j = 0;
j = ++j + j++ + j++ + j++;
int k = 0;
k = k++ + k++ + k++ + ++k;
int h = 0;
h = ++h + ++h;
int p1 = 0, p2 = 0, q1 = 0, q2 = 0;
q1 = ++p1;
q2 = p2++;
System.out.println("i " + i);
System.out.println("j " + j);
System.out.println("k " + k);
System.out.println("h " + h);
System.out.println("p1 " + p1);
System.out.println("p2 " + p2);
System.out.println("q1 " + q1);
System.out.println("q2 " + q2);
}
}
//输出结果:i = 2, j = 7, k = 7, h = 3, p1 = 1, p2 = 1, q1 = 1, q2 = 0