java basics System.out.print

I have the following code:

    class Baap {
    public int h = 4;
    public int getH() {
        System.out.println("Baap " + h);
        return h;
    }
}

public class Beta extends Baap {
    public int h = 44;
    public int getH() {
        System.out.println("Beta " + h);
        return h;
    }

    public static void main(String[] args) {
        Baap b = new Beta();
        System.out.println("testing"  + b.getH());

    }
}

Can someone explain why is this code printing: Output:

Beta 44
testing44

Why is not printing testing first?

EDIT: I see it now, i have a println and inside a method who call another printn. Thanks ERAN

Jon Skeet
people
quotationmark

Method arguments are always completely evaluated before the method is called. So this line:

System.out.println("testing"  + b.getH());

is evaluated as:

String lhs = "testing";
String rhs = b.getH();
String argument = lhs + rhs;
System.out.println(argument);

The second line of that expansion prints out "Beta 44", hence the result you're seeing.

As I noted in the comments, you don't need any inheritance to demonstrate this - you don't even need an instance, although that isn't complicating things. Here's a simpler example which shows the same thing:

public class Test {
    public static String printAndReturn() {
        System.out.println("In printAndReturn");
        return "bar";
    }

    public static void main(String[] args) {
        System.out.println("left " + printAndReturn());
    }
}

Output:

In printAndReturn
left bar

(For further experimentation, try having two different methods, and use method1() + method2()... you'll find that method1() is always executed before method2().)

people

See more on this question at Stackoverflow