Printing something in a return method

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 conclusion to be

 The square of the number 7 is 549 

However, the actual conclusion

 5The square of the number 7 is 49 

Why is this happening?

+5
source share
4 answers

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

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

Thus, it calls the square(7) call, which then calls System.out.print(5) first, before calling System.out.print .

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

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

 String toPrint = "The square of the number "+7+" is "+square(7); System.out.print(toPrint); 
+10
source

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

In combination with your square() method, you will see a sequence of method calls if you went through the code using the debugger:

 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 
+4
source

The result you get is correct.

 5The square of the number 7 is 49 

If you take the time to learn how to use the step debugger, you will understand that you type 5 and then type The square of the number 7 is 49

So, the result you get is correct.

If you need what you ask, you need to do.

 System.out.print("The square of the number "+7+" is 5"+square(7)) 
-1
source

You have two options: you return the value you want to print, or you simply execute System.out.print inside the method.

Are you sure you want to print 5 from square ?

-2
source

Source: https://habr.com/ru/post/1235422/


All Articles