I do not understand the order of execution of a code

4
public class Rope {
    static String result = "";
    {result += "c";}
    static
    {result += "u";}
    {result += "r";}

    public static void main(String[] args) {
        System.out.print(Rope.result + " ");
        System.out.print(Rope.result + " ");
        new Rope();
        new Rope();
        System.out.print(Rope.result + " ");

    }
}

The answer to this question is: u ucrcr

I just do not understand why in the end it prints only the cr, I can not find a logic, by my logic it should be: u u ucrucr. Why is this last u omitted?

    
asked by anonymous 09.11.2017 / 22:06

1 answer

3

When the application starts running at some point it will initialize the static members. This is guaranteed to occur before any class instance is initialized. Then it creates the variable result with empty text. Then add the letter u to it. This value is printed twice. The static part is this:

static {result += "u";}

There you create an instance of the class. At this point two blocks are executed that are not static, they are:

{result += "c";}
{result += "r";}

Then u already exists concatena cr . Now result contains ucr

Next creates another instance that again concatenates another cr . Now result contains ucrcr .

It will print this and the result is correct. Do not omit last u some. I inverted the question, why do you think it would have a u there? I do not see logic in that.

I did a table test to find out. Of course, knowing how static and instance blocks are executed. But you can learn how Java behaves just by doing the bench test.

They probably did this as a catch to see if the person understands how it runs even with a poorly readable syntax. Or they wanted to know if the person understands how Java works, or if they can figure it out by doing the bench test. This is more important.

So it would be easier if one understood how Java works:

public class Rope {
    static String result = "";
    static {result += "u";}
    {result += "c";}
    {result += "r";}

    public static void main(String[] args) {
        System.out.print(Rope.result + " ");
        System.out.print(Rope.result + " ");
        new Rope();
        new Rope();
        System.out.print(Rope.result + " ");
    }
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

    
09.11.2017 / 22:23