首页 新闻 会员 周边

求解这题原理是什么

0
[待解决问题]

What will happen when you attempt to compile and run the following code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
 }
}

 

飞鱼(Chris)的主页 飞鱼(Chris) | 初学一级 | 园豆:116
提问于:2016-03-05 13:56
< >
分享
所有回答(1)
0

static{int x = 5;}用static修饰的代码块表示静态代码块,当Java虚拟机(JVM)加载类时,就会执行该代码块。但是这个x的作用范围在static{}之内, 不影响static int x, y;中的x, main里面的x是第二个x。

public class Test{
static{
int x=5;
System.out.println("x = " + x);
}
static int x,y;
public static void main(String args[]){
x--; //x = -1
myMethod( );
System.out.println(x+y+ ++x); // 1 + 0 + 2
}
public static void myMethod( ){
y=x++ + ++x; // y = -1 + 1 ; x = 1
}
}

Chaofan34 | 园豆:202 (菜鸟二级) | 2016-03-05 16:12
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册