Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question from MindQ Mock Exam

 
Ray Chang
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
11. The statement ...
String s = "Hello" + "Java";
yields the same value for s as ...
String s = "Hello";
String s2= "Java";
s.concat( s2 );
True
False

I thought + here is overloaded to concatenate the strings, but I thought it's a easier way for concat(). so my answer was true. but the correct answer is false. Is it correct?
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String functions do not actually change the String that invokes them. In your second example, what actually happened was that s.concat(s2) created a new String with value equivalent to "HelloJava" and returned it, but since no String reference received this return value, the change was not apparent. Note that the String s is still equivalent to "Hello". Try this:
String newString = s.concat(s2);
System.out.println("String s is " + s);
System.out.println("String newString is " + newString);
 
Ray Chang
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know the s.concat("java");
gives no change to s.
but does
String s="Hello" + "java";
give us the same as
String s="Hellojava" ?
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, of course. Besides, you can see it for yourself by compiling it...
 
Ray Chang
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you very much.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you're welcome too
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic