This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String addition  RSS feed

 
mi te
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is happenning when you add two string?

code:

public class StringAddition{

public static void main(String args[]){

String a = "a";
String b = "b";
String ab = "ab";

ab = a + b;
System.out.println(ab == "ab");
System.out.println(ab == ab);
System.out.println((a+b) == ab);
}
}

output:

false
true
false

I understand why the first and second output are as they are, but why the third one is false? What is the difference between the objects of ab and (a + b)? Please someone explain. I read about String on sites but I don`t still get it.
 
mambe nanje
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well (a+b) is adding the two stings objects and passing it in a constructor of a new string and such that a new string object is created which is not equal to the former, remember strings are immutable, but if they were in the pool it will be different
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!