[Solved] in java while working on eclipse IDE,


The only difference in your two cases, is the parameter passed to you “println” function:

In CASE1:

System.out.println(" result");

Here the parameter ” result” (double quote should not be omited) is a string literal. It represents the word itself you typed between the double quote symbol and do not related with the int variable result you have defined in the previous line.

Thus when you call prinln, the function received an String variable and print to the console as it is.

In CASE2:

System.out.println(" result = " + result);

And in the above case, however, you passed an expression "result = " + result to the println function, in your case, which is a String “plus” an int variable operation. Java compiler will firstly convert your expression " result = " + result into a String " result = 30" and then pass it to the println function.

What the compiler do to the above expression is just like replacing it with the following code:

new StringBuilder(" result = ").append(result).toString();

Which will generate some kind of java bytecode like the following:

12: invokespecial #26                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
15: iload_1       
16: invokevirtual #29                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
19: invokevirtual #33                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;

Also find this answer useful if you have interest in how the compiler dealing with the expression:

How does the String class override the + operator?

solved in java while working on eclipse IDE,