Java试题摘选-1

1.下面代码输出值?
1
2
3
4
5
6
7
8
9
10
11
public class Demo {

public static void main(String[] args) {

int x = 4;

System.out.println("value is " + ((x > 4) ? 99.9 : 9));

}

}

===>image
不是9而是9.0

如果将99.9改成99呢?

1
2
3
4
5
6
7
8
9
10
11
public class Demo {

public static void main(String[] args) {

int x = 4;

System.out.println("value is " + ((x > 4) ? 99 : 9));

}

}

==>image

2.下面程序输出为?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Demo {

static int x = 10;

static {

x += 5;

}

public static void main(String args[]) {

System.out.println("x=" + x);

}

static {

x /= 3;

}

}

==>image

static{}代码段先于main函数运行,且static{}代码段按顺序执行!

3.下面程序输出为?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Demo {

public static int x = 100;

public static void main(String[] args) {

Demo3 hs1 = new Demo3();

hs1.x++;

Demo3 hs2 = new Demo3();

hs2.x++;

hs1 = new Demo3();

hs1.x++;

Demo3.x--;

System.out.println("x=" + x);

}

}

==>image

static变量为所有对象共有