• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

Strings and Things

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between making a String this way:
public class TestClass {
public static void main(String args[]) {
String s1 = new String("abc");
String s2 = new String("abc");
if(s1==s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
and this way:
public class TestClass {
public static void main(String args[]) {
String s1 = "abc";
String s2 = "abc";
if(s1==s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
The 2 methods give me different results!
 
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your first example creates and stores two unique objects in memory by using keyword "new", therefore s1==s2 is false.
The second example simply shares the same object in memory that was created initially, therefore s1==s2 is true.
In both cases however s1.equals(s2) is true because it is doing a deeper comparison by looking at the string syntax of each.
Hopefully that clears it up for you :-)
Percy
reply
    Bookmark Topic Watch Topic
  • New Topic