Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Related to String  RSS feed

 
padmaratna kamble
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between the underlying two String objet creation.

public class pa{
public static void main(String args[]){
String s1="Sachin";
String s2=new String("Sachin");

}
}
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One uses the literal pool, the other forces a new instance to be created.
 
Aum Tao
Ranch Hand
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
s1 == s2; // false

s1.equals(s2); // true
 
samir Sadiki
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding to what previous posters have written, whenever I see something like

new String("Sachin")

in Java code, I'm inclined to assume that either:

1. The programmer is new to Java and doesn't know that they can simply write "Sachin", or...

2. Some horrible hack involving the string pool or equality versus identity is about to be attempted.

Either way, my spidey senses are tingling.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!