Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing something in a value-returning method

Tags:

java

methods

Suppose I have a method:

public static int square(int x) {
    System.out.print(5);
    return x*x;
}

I call this method in the main method as follows:

System.out.print("The square of the number "+7+" is "+square(7));

I expect the output to be

The square of the number 7 is 549

However, the actual output is

5The square of the number 7 is 49

Why does this happen?

like image 476
Siddhartha Avatar asked Nov 07 '15 16:11

Siddhartha


2 Answers

When you call a function, all the arguments get evaluated first before the function is called.

So "The square of the number "+7+" is "+square(7) gets evaluated before the System.out.print that prints it.

Thus square(7) gets called, which then calls System.out.print(5) first - before the calling System.out.print.

After square(7) returns 49, the string evaluates to "The square of the number 7 is 49", which then gets printed.

To make it even more explicit it's as if you did this:

String toPrint = "The square of the number "+7+" is "+square(7);
System.out.print(toPrint);
like image 142
Claudiu Avatar answered Nov 15 '22 11:11

Claudiu


The line System.out.print("The square of the number "+7+" is "+square(7)); compiles to:

System.out.print(new StringBuilder()
                 .append("The square of the number ")
                 .append(7)
                 .append(" is ")
                 .append(square(7))
                 .toString());

Combined with your method square(), the sequence of method calls you would see if you stepped through the code with a debugger is:

new StringBuilder()
append("The square of the number ")
append(7)
append(" is ")
square(7)
  print(5)
append(49)                                 <-- value returned by square
toString()
print("The square of the number 7 is 49")  <-- value returned by toString

As you can see, it calls print(5), then print("The square of the number 7 is 49"), resulting in the output:

5The square of the number 7 is 49
like image 4
Andreas Avatar answered Nov 15 '22 09:11

Andreas