Results 1 to 3 of 3
- 12-17-2010, 02:38 AM #1
Senior Member
- Join Date
- Dec 2010
- Location
- Indiana
- Posts
- 202
- Rep Power
- 3
Understanding String vs new String()
This is odd, but there must be a reason.
This code returns "Does NOT"
Java Code:String str1 = new String("String One"); String str2 = new String("String One"); if (str1 == str2) { System.out.println("Equals"); } else { System.out.println("Does NOT"); }
This code returns "Equals"
Java Code:String str1 = "String One"; String str2 = "String One"; if (str1 == str2) { System.out.println("Equals"); } else { System.out.println("Does NOT"; }
-
== tests to see if the object referred to by one variable is the same object as that referred to by the other variable, and with Strings (and most other objects), you really don't care about this. What you want to know instead is are strings themselves, the characters, order of characters and case the same for one String vs another, and this is where equals(...) and equalsIgnoreCase(...) come in.
You'll want to read up on the String pool too to find out why you're getting different results in your two cases above.
- 12-17-2010, 07:23 AM #3
Member
- Join Date
- May 2010
- Posts
- 90
- Rep Power
- 0
when we assign a value to string variable compiler checks if it is already used in the same program. if it is used it assign same object to reference
so
String str1 = "hello";
String str2 = "hello;
is equivalent to
String str1, str2;
str1 = "hello";
str2 = str1;
both str1,str2 points to same object.
but in the case of new operator it create new object of string with same value.
Similar Threads
-
Binary-algorithm -> Insert String to sorted String-ArrayList
By Muskar in forum Advanced JavaReplies: 12Last Post: 11-26-2010, 08:33 AM -
Test for all empty Strings in LinkedHashMap<String,ArrayList<String>
By albertkao in forum New To JavaReplies: 1Last Post: 11-04-2010, 06:53 PM -
combine string[] into string like perl's join function
By tekberg in forum Advanced JavaReplies: 9Last Post: 02-23-2009, 01:05 PM -
Let eclipse warn about a semicolon after an if statement and string == string?
By foobar.fighter in forum EclipseReplies: 5Last Post: 01-11-2009, 10:12 AM -
Using java.util.Scanner to search for a String in a String
By Java Tip in forum Java TipReplies: 0Last Post: 11-20-2007, 04:59 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks