This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes System.out.println Strange output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "System.out.println Strange output" Watch "System.out.println Strange output" New topic
Author

System.out.println Strange output

Supun Lakshan Dissanayake
Ranch Hand

Joined: Oct 26, 2012
Posts: 132

When i compile and run Example.java the output was ba5
I need to know why the output was ba5 ??
[ my imagination = according to the sequence of line 11 output should be ab5 ]



Regards!!!


Are you better than me? Then please show me my mistakes..
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11169
    
  16

Step through the code.

On line 11, you start to build your string, which has to complete before you can do the printing from this line.

you now step into the DoSomething() method. on line 3, you say "print the string "b"". That completes, putting the 'b' on the console.

you then return the 5.

that gets concatenated to the 'a', giving you the string "a5", which is then printed to the console, behind the 'b'.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Kemal Sokolovic
Bartender

Joined: Jun 19, 2010
Posts: 825
    
    5

This is the result of operator precedence (priority). If no parentheses are used in complex expressions, operators with higher precedence are executed before those of a lower precedence. The method call operator has the highest precedence (along with indexing, postfix increment and decrement operator) so it's executed first. Since the method is invoked first, 'b' character is sent to the output and value 5 is returned from method. After that 'a' is concatenated to '5' and sent to the output so you get the result "ba5".


The quieter you are, the more you are able to hear.
Supun Lakshan Dissanayake
Ranch Hand

Joined: Oct 26, 2012
Posts: 132

THANKS GUYS!!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: System.out.println Strange output
 
Similar Threads
Using Lists and converting them to arrays problem
synchronized on System.out.toString()
String addition
Overloading
Conversion toArray and asList problem