面试例题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--;//步骤1.此时x=-1
myMethod();//步骤3.调用myMethod()函数之后y=0,x=1;
System.out.println(x + y++ + x);//运行x+(y++)+x=1+0+1=2
}
public static void myMethod(){
y = x++ + ++x;//步骤2.运行y=(x++) + (++x)后y=0,x=1
}
}
答案:2
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;
面试例题3.Which of the following will compile correctly?
A.Short myshort = 99S; C.float z = 1.0;
B.int t = "abc".length(); D.char c = 17c;
解析:
A.要执行自动装箱,直接写99就可以;
B.将1.0改为1.0f就行了,因为系统默认的浮点数是double型;
C.java中length是属性,用来求数组长度。length()是方法,用来求字符串长度;
D.直接用char c=17;就好了;
面试例题4.下面代码的输出结果是()。
int i=012;
int j=034;
int k=(int)056L;
int l=078;
System.out.println(i);
System.out.println(j);
System.out.println(k);
A.输出12,34,56 C.int k=(int)056L;行编译错误
B.输出10,28,46 D.int l=078;行编译错误
解析:int l=078;行编译错误,因为078是八进制,只能选择0~7的数字,不应该有8.
答案:D
面试例题5.下列程序的输出结果是()
public class Test {
public static void main(String[] args){
boolean b = true?false:true == true?false:true;
System.out.println(b);
}
}
boolean b=true?false:((true==true)?false:true);
运算符优先级:
1级 —— . ()
2级 —— ++ --
3级 —— new
4级 —— * / %
5级 —— + -
6级 —— >> <<
7级 —— > < >= <=
8级 —— == !=
9级 —— &
10级 —— ^
11级 —— !
12级 —— &&
13级 —— ||
14级 —— ?:
15级 —— = += -= *= /= %= ^=
16级 —— &= <<= >>=