Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string + int

 
javi cervera
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this code compile:
String s = "hello" + 7 ;
ok
but this compile also?
String s = 7 + "hello";
in my compiler yes, but i have read in certification books that this code not compile. What is the answer in the exam?

Thanks in advance.
 
manasa teja
Ranch Hand
Posts: 325
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes. In both the cases, 7 will be converted into string and will be concatenated to hello

Originally posted by wasarta:
this code compile:
String s = "hello" + 7 ;
ok
but this compile also?
String s = 7 + "hello";
in my compiler yes, but i have read in certification books that this code not compile. What is the answer in the exam?

Thanks in advance.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wellcome to the Ranch wasarta.
Please read our namimg policy and change your displayed name accordingly.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java compiler treats + as string concatenation if either operand is a String.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The order is important, though. See this sample code:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic