• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question #4 in selft-test chapter 4 [K&B7]

 
John Lerry
Ranch Hand
Posts: 145
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a doubt with System.out.println and concatenation.
Given this code:


I did not understand why the last System.out.println would print 86foo and not 4244foo.
System.out.print others are clear to me.

 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Lerry wrote:I did not understand why the last System.out.println would print 86foo and not 4244foo.
System.out.print others are clear to me.

I really start to wonder if you actually read/study the chapters or just immediately take the practice exams. Because the reason why you'll see this behaviour is clearly mentioned in the String Concatenation Operator section on page 237 of K&B7.

The rule you should definitely remember (otherwise you might even fail the exam):
K&B7, page 237, String Concatenation Operator wrote:If either operand is a String, the + operator becomes a String concatenation operator. If both operands are numbers, the + operator is the addition operator.


Hope it helps!
Kind regards,
Roel
 
John Lerry
Ranch Hand
Posts: 145
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, I had heard this but I can not understand why then System.out.println on line 5 goes to concatenate two numbers rather than summing them.
I think because there is " " which is the equivalent of a string (blank space) but then the same argument had to be done on line 7 because the foo method returns a string.

EDIT: I understood now, stupid question because the operands, of course, must be considered two at a time from left to right. Sorry.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Lerry wrote:EDIT: I understood now, stupid question because the operands, of course, must be considered two at a time from left to right. Sorry.

Spot-on! You indeed need to consider operands from left to right.

On line5: 1st operand (" ") is a String, 2nd one (7) an int => String concatenation (will result in another String)
On line6: exactly same as line5 (although 1st operand is a method invocation, the return type is String)
On line7: 1st operand (x) is a long, 2nd one (y is a long as well => addition operator (will result in another long)

Hope it helps!
Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic