Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

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

Posted on 2008-11-07
26
Medium Priority
?
748 Views
Last Modified: 2013-12-29
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...
0
Comment
Question by:jazzIIIlove
  • 12
  • 5
  • 3
  • +3
26 Comments
 
LVL 6

Assisted Solution

by:manuel_m
manuel_m earned 200 total points
ID: 22903753
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
 
LVL 6

Expert Comment

by:manuel_m
ID: 22903761
You should use equals method to check if the strings contain the same values.
0
 
LVL 8

Assisted Solution

by:mnrz
mnrz earned 500 total points
ID: 22903827
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22903841
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
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22903852
of course i know to compare strings via String class functions...Just reviving pointer stuff and logic here...
0
 
LVL 8

Assisted Solution

by:mnrz
mnrz earned 500 total points
ID: 22903873
1)
yes, no

2)
yes, no

But you should not rely on this comparison you are recommended to use equals() method
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22903966
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
 
LVL 61

Expert Comment

by:Kevin Cross
ID: 22903984
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
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22903986
my pointer notation is valid or any other notation?
0
 
LVL 61

Accepted Solution

by:
Kevin Cross earned 400 total points
ID: 22904036
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
 
LVL 61

Expert Comment

by:Kevin Cross
ID: 22904099
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
 
LVL 24

Assisted Solution

by:sciuriware
sciuriware earned 100 total points
ID: 22904128
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
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22904507
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
 
LVL 24

Expert Comment

by:sciuriware
ID: 22904608
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
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22904616
sorry...
for the above
not 1)
4)


0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22904677
>>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
 
LVL 9

Expert Comment

by:mbodewes
ID: 22909562
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
 
LVL 9

Expert Comment

by:mbodewes
ID: 22909573
On second thought, my explanation only makes it worse, just keep to the String API :)
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22912271
ok...any answers for 5) and 6)
so i can conclude the question...
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 22913010
I answered 5 & 6 already in the beginning, so what are you waiting for?
A repeat?

;JOOP!
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22913579
5 and 6 has the declaration of static...The others has not...Does it make any difference?
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 22914153
No
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22914241
cool...
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 22915310
static means the reference is not an instance variable.
We are here talking about what it points at.

;JOOP!
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 23022360
thanks for your interest guys!
0
 
LVL 12

Author Closing Comment

by:jazzIIIlove
ID: 31514304
thank you!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses
Course of the Month15 days, 4 hours left to enroll

578 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question