Java String Comparison...easy question...detail needed...no link please...

1)
String s1 = "hello world";
String s2 = "hello world";

if(s1==s2)
System.out.println("Yes");
else
System.out.println("No");

2)
String s1 = "hi";
String s2 = "bye";

if(s1==s2)
System.out.println("ok");
else
System.out.println("bad");


Could you give me detailed explanation of this 2 questions...
LVL 12
jazzIIIloveAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

manuel_mCommented:
The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the == operator does not compare the content of the text present in the String objects. It only compares the references the 2 Strings are pointing to. That's why in the first example the result is "Yes" and in the second the result is "bad".
0
manuel_mCommented:
You should use equals method to check if the strings contain the same values.
0
mnrzCommented:
The first if statement will print our "Yes" and the second one will print out "bad"
so what do you want to know?

however it's better to use equals() method instead.

I think your question is because you are wondered why using == operator works fine for Strings but not for other objects, if this is the case let me tell you that strings in java will be kept in a string pool and if you set a string value then in your code ahead you set another string value, Java will look up the pool to see if there is already a string just like you are setting now, if yes, no new object will be created and your new string will be the same as you already set and have in your string pool

even if you use any kind of method for strings the pool will be populated, consider following:

"Hello World".substring(0,9).relace("Wo", "WA);

Although there is no variable in the left, but your string pool contains following objects of string:

Hello World
Hello Wor
Hello WAr


0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

jazzIIIloveAuthor Commented:
Hi there;

<< It only compares the references the 2 Strings are pointing to.
1)
You mean?:
  *s1  -> hello world
  *s2     _|

The pointers are showing same object? Is there ANY slightest chance that s2 cannot show the same object?
2)
You mean?:
 *s1 -> hi
 *s2 ->bye
The pointers are not showing the same object? Is there ANY slightest chance that s2 or s1 can show the same object?

Best regards...
0
jazzIIIloveAuthor Commented:
of course i know to compare strings via String class functions...Just reviving pointer stuff and logic here...
0
mnrzCommented:
1)
yes, no

2)
yes, no

But you should not rely on this comparison you are recommended to use equals() method
0
jazzIIIloveAuthor Commented:
Plese be specific and confirm:

1)
yes, no

The pointers are showing same object? Is there ANY slightest chance that s2 cannot show the same object?

2)
yes, no

The pointers are not showing the same object? Is there ANY slightest chance that s2 or s1 can show the same object?

0
Kevin CrossChief Technology OfficerCommented:
Sounds like you know you are not comparing the text of the strings in your example but instead the pointers; therefore, to answer your question from that object perspective, these will not necessarily hold true.

This works for strings, because since the String object is immutable it can optimize things but pointing to reference of String that already has same value instead of creating a new one.  It then does comparison/equals operation based on that type and for Strings it compares the text; however, what if you are dealing with an object that  has multiple string values and other integers that happen to be alike, see if test holds true.

Kev
0
jazzIIIloveAuthor Commented:
my pointer notation is valid or any other notation?
0
Kevin CrossChief Technology OfficerCommented:
See what I mean here:
public class PointerTest {
	public static void main(String[] args) {
		PointerTest p = new PointerTest();
		p.testCase1();
		p.testCase2();
		p.testCase3("hello world");
		
		p.testCase4(p.new MyString("hello world"), p.new MyString("hello world"));
	}
	
	class MyString {
		String value;
		
		public MyString(String value) {
			this.value = value;
		}
	}
	
	void testCase1() {
		String s1 = "hello world";
		String s2 = "hello world";
 
		if(s1==s2)
		System.out.println("Yes");
		else
		System.out.println("No");
 
	}
	
	void testCase2() {
		String s1 = "hi";
		String s2 = "bye";
 
		if(s1==s2)
		System.out.println("ok");
		else
		System.out.println("bad");
 
	}
	
	void testCase3(String s2) {
		String s1 = "hello world";
		
		if(s1==s2)
		System.out.println("Yes");
		else
		System.out.println("No");
 
	}
	
	void testCase4(MyString s1, MyString s2) {
		if(s1==s2)
		System.out.println("ok");
		else
		System.out.println("bad");
 
	}
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Kevin CrossChief Technology OfficerCommented:
And actually to be more correct in my statement, the object references will NOT be equal in most cases for different objects that are equal in values.  In order to test equality of values as mentioned you must use .equals().

The reason again this works with Strings is that it being immutable the storage of the object references are a little different but still in comparison of values you should .equals().

What you are seeing is coincidence that object references equal.

Here is probably a better same code.  These should equal but they do not.  Since s2 doesn't start out the same string, it gets a different object reference than s1.
void testCase1() {
		String s1 = "hello world";
		String s2 = "hello world ";
 
		if(s1.trim()==s2.trim())
		System.out.println("Yes");
		else
		System.out.println("No");
 
	}

Open in new window

0
sciuriwareCommented:
mnrz, jazzIIIlove,

if(a == b)  is only valid for String LITERALS!!!

as soon as you 'create' a String it is only (as above stated) a pointer comparison.

The literal case is true, because JAVA still allocates special space for the same literals,
although that doesn't make sense any more. So,

String a = "Today";
String b = "Today";

indeed a == b here, because JAVA creates only ONE instance of the immutable constant literal.

Please, in ALL cases use String.equals() or String.equalsIgnoreCase() to avoid confusion.

;JOOP!
0
jazzIIIloveAuthor Commented:
another thing:

1)
String s1 = "hello world";
String s2 =new String ("hello world");

if(s1==s2)
System.out.println("Wow");
else
System.out.println("Confused");

What is the logic underneath?
0
sciuriwareCommented:
new-> create something: copy the literal while running.

"hello world" exists at the start, but rigid references also.

s2 will point at a copy of the literal.

;JOOP!
0
jazzIIIloveAuthor Commented:
sorry...
for the above
not 1)
4)


0
jazzIIIloveAuthor Commented:
>>Sounds like you know you are not comparing the text of the strings in your example but instead the >>pointers; therefore, to answer your question from that object perspective, these will not necessarily >>hold true.

Yes...
and lastly:
5)
static String s1 = "hello world";
static String s2 ="hello world";

if(s1==s2)
System.out.println("Well");
else
System.out.println("Who knows");

6)
static String s1 = "hello world";
static String s2 =new String ("hello world");

if(s1==s2)
System.out.println("Foo;
else
System.out.println("Baz");

??

I am going to summarize what i understand according to your replies and allocate the points after your approval...and raising the points to 300...
0
mbodewesCommented:
The storing of an equal but elsewhere defined value within one reference (only for immutable instances as noted) is called "interning". You may look that up for more information.

From the String API documentation:

intern

public String intern()

    Returns a canonical representation for the string object.

    A pool of strings, initially empty, is maintained privately by the class String.

    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

    All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification

    Returns:
        a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

0
mbodewesCommented:
On second thought, my explanation only makes it worse, just keep to the String API :)
0
jazzIIIloveAuthor Commented:
ok...any answers for 5) and 6)
so i can conclude the question...
0
sciuriwareCommented:
I answered 5 & 6 already in the beginning, so what are you waiting for?
A repeat?

;JOOP!
0
jazzIIIloveAuthor Commented:
5 and 6 has the declaration of static...The others has not...Does it make any difference?
0
sciuriwareCommented:
No
0
jazzIIIloveAuthor Commented:
cool...
0
sciuriwareCommented:
static means the reference is not an instance variable.
We are here talking about what it points at.

;JOOP!
0
jazzIIIloveAuthor Commented:
thanks for your interest guys!
0
jazzIIIloveAuthor Commented:
thank you!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.