Object comparison: Address vs Content
Hey guys im just messing around and I cant get this to work:
public static void main(String[] args){
Scanner input = new Scanner (System.in);
String x = "hey";
System.out.println("What is x?: ");
x = input.nextLine();
System.out.pr开发者_运维技巧intln(x);
if (x == "hello")
System.out.println("hello");
else
System.out.println("goodbye");
}
it is of course supposed to print hello hello if you enter hello but it will not. I am using Eclipse just to mess around. A little quick help please
Should be if (x.equals("hello"))
.
With java objects, ==
is used for reference comparison. .equals()
for value comparison.
Don't use ==
when testing for equality of non basic types, it will test for reference equality. Use .equals(..)
instead.
Look at the following diagram:
When using ==
you're comparing the addresses of the boxes, when using equals
you're comparing their content.
You can't compare a string like that.Because String is a class.So if you want to compare its content use equals
if (x.equals("hello"))
System.out.println("hello");
else
System.out.println("goodbye");
x=="hello" compares the references not values , you will have to do x.equals("hello").
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
Use "hello".equals(x)
and never reverse since it does not handle null.
== operator checks equality of references (not values). In your case you have 2 String type object which have different reference but same value "hello". String class has "equals" method for checking values equality. The syntax is if(str1.equals(str2)).
Try this as the comparison:
if (x.equals("hello"))
Use x.equals("hello");
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
Take this sample program:
public class StringComparison {
public static void main(String[] args) {
String hello = "hello";
System.out.println(hello == "hello");
String hello2 = "hel" + "lo";
System.out.println(hello == hello2);
String hello3 = new String(hello);
System.out.println(hello == hello3);
System.out.println(hello3.equals(hello));
}
}
Its output would be:
true
true
false
true
Objects hello
and hello3
have different references that's why hello == hello3
is false, but they contain the same string, therefore equals
returns true.
The expression hello == hello2
is true because Java compiler is smart enough to perform concatenation of two string constants.
So to compare String objects, you have to use equals
method.
精彩评论