Win a copy of Rust Web Development this week in the Other Languages forum!
  • 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

String Comparison.

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Certification book by Ioworski states that
when you compare s1 and s2 they are not equal..Pls see the below pgm for explanation..but its very simple
***Pgm***
String s1 = "ab";
String s = s1 + "cd";
String s2 = "abcd";
System.out.println( s1 == s2 );
********
According to my knowledge, s1 == s2 will return true and the output will be true.
But Iowroski says the output will be false.

------------------
 
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you compare two objects, only the references are compared. (not the content)
So, you get false.
But, if there is something like this,

then s1 == s2 is true. Because when String objects have same value when constructed (without using new ), the references are same.
 
Magesh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's what I have told there..look at my
code...Am doing the same..

------------------
 
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'll have a go at explaining this.
First you need to know that there are two ways to test if one Java object is the same as another. The first is the == operator, and the second is the equals method.
Next you need to understand that any Java object is really just a reference to some data. In other words, what you know as the variable is really the address of the data in memory.
The == operator compares the references (memory adresses), and the equals method compares the actual data.
Now for some concrete examples. Imagine three text Strings: "aaa", "bbb" and "aaabbb". For the purposes of this example let's say they are located at memory locations 1000, 2000 and 3000 respectively.
Let's assign these strings to some variables: We now have 3 strings:
<pre>
a = "aaa" // memory address 1000
b = "bbb" // memory address 2000
c = "aaabbb" // memory address 3000</pre>
and compare them:
<pre>
a == b //false compare 1000 with 2000)
a.equals(b) //false (compare "aaa" with "bbb")
a == c //false compare 1000 with 3000)
a.equals(c) //false (compare "aaa" with "aaabbb")</pre>
Nothing unexpected so far.
Now create a new string. Remember that the + operator for strings is just a shortcut for
creating a new StringBuffer.
so we say:
<pre>d = "aaa" + "bbb"</pre>
and Java does:
<pre>
StringBuffer temp = new StringBuffer("aaa");
temp.append("bbb");
d = temp.toString();</pre>
If you notice, there is a "new" in there, so a new variable has been created. Let's assume that the final contents of the StringBuffer are created at memory address 4000. We now have 4 strings:
<pre>
a = "aaa" // memory address 1000
b = "bbb" // memory address 2000
c = "aaabbb" // memory address 3000
d = "aaabbb" // memory address 4000</pre>
let's compare some of them:
<pre>
a == b //false (compare 1000 with 2000)
a.equals(b) //false (compare "aaa" with "bbb")
c == d //false (compare 3000 with 4000)
c.equals(d) //true (compare "aaabbb" with "aaabbb")</pre>
So your example
<pre>
String s1 = "ab";
String s = s1 + "cd";
String s2 = "abcd";
System.out.println( s1 == s2 );</pre>
is like comparing c and d above. The contents are the same, but the memory addresses (references) are different.
Has this helped?
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Excellent!!
 
Desperado
Posts: 3226
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is there a "typo" in this question!?
(s = ...)?
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Strangely, both Heller and Brigden's book makes representation that String when used as :
String a = "xxx";
String b = "bbb";
uses 1 memory location only (memory pool).
While when used as :
String a = new String("xxx");
String b = new String("bbb");
each String is created in their own memory space.
Therefore ..
using '==' on String will always yield yes.
Any opinion on this ?
 
Trailboss
Posts: 23418
IntelliJ IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you have
String a = "xxx";
String b = "xxx";
Then both a and b are pointing to the exact same place. A little optimization that the compiler is required to do for you.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A small clarification needed in the Paul's explanation above.
As understood by me form Paul's explanation. For the below decls.
String a = "aaaa";
String b = "aaa" + "a";
String c = "a"
String d = c + "aaa";
(a == b) should be false acc to explanation .....But actually it is returning TRUE.
and
(a == d) is returning FALSE.
Please someone acknowledge if I am right/wrong ???
cics


 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
The basic question is how to find out if an object has been created on the heap or is on the String pool.
i use the logic that if we use the intern() method and the problem gives the opposite answer then the String has been created as an object.
i give a sample below to illustrate
class demo
{
public static void main(String[] args)
{String a = "aaaa";
String b = "aaa" + "a";
String c = "a" ;
String d = (c + "aaa");
if (a==d)// prints out false
{
System.out.println("true");
}
else
System.out.println("false!");
}
String d = (c + "aaa").intern();
if (a==d)// prints out true
{
System.out.println("true");
}
else
System.out.println("false!");
}

}
to clarify if an expression
like
String a="abc";
String s= a+"xyz";
contains a variable then the object is created on the heap. if however it involves two or more string literals like "XX" + "X" then this string is created on the String pool.
Hope this helps.
regds
Rahul.

[This message has been edited by rahul_mkar (edited June 21, 2000).]
 
Ranch Hand
Posts: 277
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Before the question asked by cics i was kind of sure that i can handle question on String. But now once again i am confuse becasue i tried to run the following code and got output as said by cics.
public class Test {
String a = "aaaa";
String b = "aaa" + "a";
String c = "a";
String d = c + "aaaa";
public static void main(String arg[]){
System.out.println(new Test().f());
}
private int f(){
if ( a==b)
System.out.println("True1");
else
System.out.println("else1");

if ( a==d)
System.out.println("True2");
else
System.out.println("else2");
return 1;
}
}

print :
True1
else2
please some one put some light here.
vivek
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Vivek,
please read my earlier post. If something is unclear do tell me.
Regds.
Rahul
 
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is another explanation.
For the strings
String a = "aaaa";
String b = "aaa" + "a";
a and b both refer to same string literal in the string pool
as the compiler will optimize the code to:
String a = "aaaa";
String b = "aaaa";
Refer to JLS 3.10.5 String Literals
-----Begin JLS------
The following are examples of string literals:
"This is a string" // a string containing 16 characters
"This is a " + // actually a string-valued constant expression,
"two-line string" // formed from two string literals
-----End JLS-------
For the strings
String c = "a";
String d = c + "aaaa";
They will refer to two distinct strings as compiler will not treat
c + "aaa"
as a string literal.
Hence a != d
To verify I compiled following code

when executed, it produces
a == b
a != d
now, I decompiled it. The decompiled code follows.
Please note that
String b = "aaa" + "a";
has been changed to
String b;
....
b = "aaaa";


Hope this explains.
 
reply
    Bookmark Topic Watch Topic
  • New Topic