i++
面试例题1:下面程序的输出结果是多少?
public class DataPractice03 {
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;
}
}
解析:1. // 在第一次被载入JVM的时运行,但由于是局部变量,x=5不影响后面的值
2.// 初始化时 x = 0,y = 0;
3.// 在运行myMethod()的之前;x = -10
// 开始调用myMethod(),之后 x = 1; y = 0.
// 1 + 0 + 1 = 2
面试例题3:下列程序到的输出结果是( )
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);
}
}
A. 0 B.99 C.100 D.101
解析:因为Java采用了中间缓存变量的机制,所以,j=j++可以换成下面的写法
temp = j;
j = j + 1;
j = temp;
运算符
面试例题2:下面程序的输出结果是( )。
public class Test {
public static void main(String[] args) {
boolean b = true?false:true == true?false:true;
System.out.println(b);
}
}
A. true B.false C.null D.以上答案都不对
解析:三目运算符是右结合的,所以应该理解为:
boolean b = true?false: ((true == true)?false:true);