I don’t understand the order to execute a code

Asked

Viewed 106 times

5

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

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

1 answer

4


When the application starts running at some point it will initialize the static members. It is guaranteed that this occurs before any class instance is initialized. Then creates the variable result using an empty string. Then add the letter u on it. This value is printed twice. The static part is this:

static {result += "u";}

There is created an instance of the class. At this moment two blocks are executed that are not static, they are:

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

Then to the u concatenate already exists cr. Now result contains ucr

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

Print this and the result is correct. Do not omit last u some. I reverse the question, because you think you would have a u there? I see no logic in that.

I did a table test to find out. And of course, knowing how the static and instance blocks run. But you can learn how Java behaves just by doing the table test.

They probably did this as a trick to see if the person understands how it is executed even with a barely readable syntax. Or they wanted to know if the person understands how Java works, or if they can figure it out by doing the table 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 + " ");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Now I understand, my hesitation was to think that when creating new Rope(), I was adding again the u, but it does not call the Static block, only the block with the cr. It was a bit of inattention. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.