Results 1 to 5 of 5
- 10-29-2008, 05:52 AM #1
Member
- Join Date
- Oct 2008
- Posts
- 3
- Rep Power
- 0
String Object equality with == operator
String str ="Arun"+"Kumar";
String str1="Arun"+"Kumar";
String c = str+str1
String d= str+str1;
According to String Immutability in nature, i have tested for (str==str1) it gives true, but at the same time if i test for (c==d) it gives false why is it so? can any one explain me about this.
- 10-29-2008, 06:19 AM #2
Senior Member
- Join Date
- Sep 2008
- Posts
- 564
- Rep Power
- 5
I believe that str and str1 are referring to the same string in the string constant pool. However, c and d are initialized as string objects of two strings concatenated together.
This may not be correct, so perhaps someone else with more knowledge about this can shed some light?
- 10-29-2008, 06:30 AM #3
Member
- Join Date
- Oct 2008
- Posts
- 24
- Rep Power
- 0
boolean equals(Object anObject) Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.
boolean equalsIgnoreCase(String anotherString) Returns true if and only if the argument is a String object that represents the same sequence of characters as this object, ignoring differences in case.
- 10-29-2008, 06:49 AM #4
Member
- Join Date
- Oct 2008
- Posts
- 24
- Rep Power
- 0
Java Code:public class NewClass { public static void main(String[] args){ String str ="Arun"+"Kumar"; String str1="Arun"+"Kumar"; String c = str.concat(str1); String d = str.concat(str1); if(c.equals(d)){ System.out.println("C and D are equal. C equals ".concat(c) + ". " + "D equals ".concat(d) + ". ");} } }
- 10-29-2008, 06:57 AM #5
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
There is no major relation with immutable and the == operator.
Once you define a string, VM check on string constant pool, and if it's found make a reference to it. So str and str1 refer the same and == return true. Once you concatenating strings and assign to another string object it want happen, VM keep to reference to that, and == operator return false.
Read more about == and equals() on Java docs.
Similar Threads
-
Operator < cannot be applied to java.lang.Object, Object
By Albert in forum Advanced JavaReplies: 2Last Post: 11-26-2010, 02:12 AM -
Object to String.
By Gelembjuk in forum New To JavaReplies: 6Last Post: 10-29-2008, 10:19 PM -
Object from String
By Java Tip in forum Java TipReplies: 0Last Post: 02-16-2008, 09:20 PM -
JSTL -- Comparing two strings for equality
By trinkets in forum JavaServer Pages (JSP) and JSTLReplies: 0Last Post: 02-12-2008, 04:39 PM -
String vs Object
By Gilgamesh in forum New To JavaReplies: 1Last Post: 11-28-2007, 10:26 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks