加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java中静态块的优先级是什么?

发布时间:2020-12-15 05:23:11 所属栏目:Java 来源:网络整理
导读:public class Static{ 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; }} 请问有人帮助我,为什么显示输出是3? 解
public class Static
{
    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;
    }
}

请问有人帮助我,为什么显示输出是3?

解决方法

static
  {
        int x = 5;
  }

你在这里重新声明x,使它成为一个本地范围的变量(不是类成员).无论何时运行,此分配都不会产生任何影响.

现在,您询问了静态块,这就是我的答案.如果您对为什么输出值3的原因感到困惑,即使假设没有进行赋值,那么这也成为关于增量运算符(x和x)的问题.

完整的解释

我非常喜欢Paulo的解释,但让我们看看我们是否可以简化代码.首先,让我们忘记将x和y设为静态字段(将它们设置为本地,初始化为静态int:0的默认值)和内联myMethod():

int x = 0,y = 0;
x--;
y = x++ + ++x;
System.out.println(x + y + ++x);

首先,我们应该消除复杂的表达我们可以通过以正确的顺序将每个子表达式提取到临时变量中来做到这一点(表达式从左到右评估):

int x = 0,y = 0;
x--;

int yOperand1 = x++;
int yOperand2 = ++x;
y = yOperand1 + yOperand2;

int resultOperand1 = x;
int resultOperand2 = y;
int resultOperand3 = ++x;
int result = resultOperand1 + resultOperand2 + resultOperand3;
System.out.println(result);

现在我们可以在每一步标记x,y和任何临时变量的值:

int x = 0,y = 0;           //x: 0   y: 0
x--;                        //x: -1  y: 0

int yOperand1 = x++;        //x: 0   y: 0  yOperand1: -1
int yOperand2 = ++x;        //x: 1   y: 0  yOperand1: -1  yOperand2: 1
y = yOperand1 + yOperand2;  //x: 1   y: 0

int resultOperand1 = x;     //x: 1   y: 0  resultOperand1: 1
int resultOperand2 = y;     //x: 1   resultOperand1: 1  resultOperand2: 0
int resultOperand3 = ++x;   //x: 2   resultOperand1: 1  resultOperand2: 0  resultOperand3: 2
int result = resultOperand1 + resultOperand2 + resultOperand3; //result: 3
System.out.println(result);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读