30 道 1.4 模拟经典题
1. What will happen when you attempt to compile and run the following code?
(Assume that the code is compiled and run with assertions enabled.)
public class AssertTest{
public void methodA(int i){
assert i >= 0 : methodB();
System.out.println(i);
}
public void methodB(){ //无返回值
System.out.println("The value must not be negative");
}
public static void main(String args[]){
AssertTest test = new AssertTest();
test.methodA(-10);
}
}
A.it will print -10
B.it will result in AssertionError showing the message-“the value must not be negative”.
C.the code will not compile.
D.None of these.
C is correct. An assert statement can take any one of these two forms -
assert Expression1;
assert Expression1 : Expression2;
Note that, in the second form; the second part of the statement must be an expression-
Expression2. In this code, the methodB() returns void, which is not an expression and hence it
results in a compile time error. The code will compile if methodB() returns any value such as int,
String etc.
Also, in both forms of the assert statement, Expression1 must have type boolean or a compile-time
error occurs.
2. What will happen when you attempt to compile and run the following code?
public class Static{
static{
int x = 5; //在 static 内有效
}
static int x,y; //初始化为 0
public static void main(String args[]){
x--; //-1
myMethod();
System.out.println(x + y + ++x);
}
public static void myMethod(){
y = x++ + ++x; //y=-1+1 x=1
}
}