What is the priority of static blocks in Java?

public class Static
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;
    }
}

Can someone help me, why is the display output 3?

Solution

static
static
  {
        int x = 5;
  }

You redeclare x here to make it a locally scoped variable (not a class member) This assignment has no impact whenever it is run

Now, you asked about static blocks, and that's my answer If you are confused about why the value 3 is output, even if it is assumed that no assignment is made, this becomes a problem with the incremental operators (x and x)

Complete explanation

I like Paulo's explanation very much, but let's see if we can simplify the code First, let's forget to set X and y as static fields (set them locally and initialize to the default value of static int: 0) and inline mymethod():

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

First, we should eliminate complex expressions. We can do this by extracting each sub expression into temporary variables in the correct order (expressions are evaluated from left to right):

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);

Now we can mark the values of X, y and any temporary variables at each step:

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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>