Java Forum / General / August 2006
str.equals(null) or str==null ?
David Segall - 31 Jul 2006 15:43 GMT Is there a difference between the two tests on the object str:
if (str == null) {... and if (str.equals(null)) {...
I have always used the first one and it seems to return true for a null String but should I be using the second one?
Stefan Ram - 31 Jul 2006 15:41 GMT >if (str.equals(null)) {... What do you think will happen here if str==null?
Bhanu - 02 Aug 2006 07:53 GMT > >if (str.equals(null)) {... > > What do you think will happen here if str==null? "null" is not an object of any class null implies that it does not refers to any object. So u can not do obj.eqals(null) for any object. U need to pass as an object as the argument.
AndrewMcDonagh - 02 Aug 2006 19:18 GMT >>> if (str.equals(null)) {... >> What do you think will happen here if str==null? > > "null" is not an object of any class null implies that it does not > refers to any object. So u can not do obj.eqals(null) for any object. > U need to pass as an object as the argument. in this case you can, as the String.equals() method will return false if passed a null.
Oliver Wong - 03 Aug 2006 19:43 GMT >> >if (str.equals(null)) {... >> [quoted text clipped - 3 lines] > refers to any object. So u can not do obj.eqals(null) for any object. > U need to pass as an object as the argument. If you actually try it in your compiler, you'll see that obj.equals(null) compiles just fine, and produces the expected result of returning false (assuming obj is also not null).
- Oliver
Ingo R. Homann - 31 Jul 2006 15:44 GMT Hi,
> Is there a difference between the two tests on the object str: > > if (str == null) {... > and > if (str.equals(null)) {... Of course: If str is null, the first one will exeute the if-block while the latter one will throw a NullPointerException.
Or am I missing something?
Ciao, Ingo
David Segall - 31 Jul 2006 16:01 GMT >Hi, > [quoted text clipped - 8 lines] > >Or am I missing something? You aren't. I am! However, is null really the same object as str... ?
Rogan Dawes - 31 Jul 2006 16:22 GMT >> Hi, >> [quoted text clipped - 8 lines] >> Or am I missing something? > You aren't. I am! However, is null really the same object as str... ? Key point to understand: The difference between a reference and the actual object.
str is not an Object, it is a reference to an object. Sometimes, that reference may not actually be referring to an object. In those cases, "str" will refer to "null".
The following line:
String str = new String("a string");
creates a new String object, and saves a reference to the object in the variable "str".
String str2 = str;
creates a new variable "str2" that also refers to the same String that "str" was referring to.
Hope this helped.
Rogan
Mark Space - 31 Jul 2006 21:33 GMT >>> Hi, >>> [quoted text clipped - 31 lines] > > Rogan But the question I think that is being asked is:
Will equals(null) ever return true?
I think (not sure) the answer is no. There is no actual string object that is ever null. However, equals("") might return true, and is perhaps what you should be using. But I think length() == 0 might be even better.
So I think better code should be something like
boolean nullStringOrRef( String s ) { if( s == null || s.length() == 0) return true; else return false; }
Did that answer your question?
Lars Enderin - 31 Jul 2006 23:07 GMT Mark Space skrev:
>>>> Hi, >>>> [quoted text clipped - 51 lines] > > Did that answer your question? I think that's not very elegant. boolean nullStringOrRef(String s) { return s == null || s == ""; } is much better. Learn to use boolean expressions.
AndrewMcDonagh - 31 Jul 2006 23:10 GMT > Mark Space skrev: >>>> [quoted text clipped - 60 lines] > } > is much better. Learn to use boolean expressions. best learn how to do a string equality check then.
S == ""
should be
s.equals("");
Mark Space - 31 Jul 2006 23:40 GMT >> I think that's not very elegant. >> boolean nullStringOrRef(String s) { [quoted text clipped - 9 lines] > > s.equals(""); Collectively, a good point. I stand corrected in the aggregate! :-)
Lars Enderin - 01 Aug 2006 09:03 GMT >> I think that's not very elegant. >> boolean nullStringOrRef(String s) { [quoted text clipped - 9 lines] > > s.equals(""); It's equivalent if there is only one instance of the empty string "" in the system.
Chris Brat - 01 Aug 2006 09:47 GMT Maybe not..
String s1 = "myString";
String s2 = new String("myString");
if (s1 == s2){; // false Syste.out.println("Will never print"); }
if (s1.equals(s2)){ // true System.out.println("This will print"); }
> >> I think that's not very elegant. > >> boolean nullStringOrRef(String s) { [quoted text clipped - 12 lines] > It's equivalent if there is only one instance of the empty string "" in > the system. Lars Enderin - 01 Aug 2006 10:03 GMT Lars Enderin skrev:
>>> I think that's not very elegant. >>> boolean nullStringOrRef(String s) { [quoted text clipped - 12 lines] > It's equivalent if there is only one instance of the empty string "" in > the system. But that seems not to be the case. I goofed.
Patricia Shanahan - 01 Aug 2006 15:36 GMT > Lars Enderin skrev: >> [quoted text clipped - 16 lines] > > But that seems not to be the case. I goofed. There will be only one string constant with value "", but there may be many non-constant strings with the same value.
Patricia
Stefan Ram - 01 Aug 2006 15:46 GMT >There will be only one string constant with value "", but there >may be many non-constant strings with the same value. If I'd try to nit-pick, I might reply that »""« is not a string constant, but a string literal (JLS 3.10.5) and that string objects are always constant (immutable).
So which wording would I use?
The string literal »""« always refers to the same object, while there might be several different string objects of length 0.
Patricia Shanahan - 01 Aug 2006 16:38 GMT >> There will be only one string constant with value "", but there >> may be many non-constant strings with the same value. [quoted text clipped - 7 lines] > while there might be several different string objects of > length 0. I was using "string constant", rather sloppily, where I meant "compile-time constant expression of type String", and "non-constant strings" to mean "String expressions that are not compile-time constant expressions".
"" is both a literal and a compile-time constant expression. See the first bullet under "15.28 Constant Expression": "Literals of primitive type and literals of type String".
All String objects are immutable. Many String reference expressions are not compile-time constant expressions.
What you say about String literals is true, but far from the whole story. As the section you referenced says "Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals."
public class StringConstantDemo { private final String stringField = ""; private static final String stringStatic = "";
public static void main(String[] args){ final String stringLocal = ""; final StringConstantDemo demo = new StringConstantDemo();
System.out.println("" == (""+""+"")); System.out.println("" == stringLocal); System.out.println("" == StringConstantDemo.stringStatic); System.out.println("" == demo.stringField); } }
Each comparison has a non-literal right hand side, yet the JLS requires a true result because each right hand side is a compile-time constant expression.
Patricia
Hendrik Maryns - 01 Aug 2006 08:28 GMT Ingo R. Homann schreef:
> Hi, > [quoted text clipped - 8 lines] > > Or am I missing something? Yes, from String.java:
public boolean equals (Object object) { if (object == this) return true; if (object instanceof String) { String s = (String)object; if (count != s.count || (hashCode != s.hashCode && hashCode != 0 && s.hashCode != 0)) return false; return regionMatches(0, s, 0, count); } return false; }
This will return false if object is null.
H. - -- Hendrik Maryns
================== http://aouw.org Ask smart questions, get good answers: http://www.catb.org/~esr/faqs/smart-questions.html
Ingo R. Homann - 01 Aug 2006 10:19 GMT Hi,
>>>Is there a difference between the two tests on the object str: >>> [quoted text clipped - 10 lines] > ... > This will return false if object is null. I think, you missed something! :-) The question was not what happens if 'object' is null. The question was what happens if 'str' is null.
Ciao, Ingo
kito - 01 Aug 2006 09:46 GMT I think the following two programs explain all: public class Test{ public static void main(String[] args){ String a = "hallo"; System.out.println("Comparison with null: " + a.equals(null)); System.out.println("Comparison with different String: " + a.equals("ciao")); System.out.println("Comparison with same String: " + a.equals("hallo")); } }
public class Test{ public static void main(String[] args){ String a = null; System.out.println("Comparison with null: " + a.equals(null)); System.out.println("Comparison with different String: " + a.equals("ciao")); System.out.println("Comparison with same String: " + a.equals("hallo")); } }
Clearly in the second case a NullPointerException will be launched, since "a" does not hold an actual reference to an object and therefore no comparison can be invoked.
In general for reference types the "==" compares the operands on both sides for the same reference value, i.e. if not both operance are referencing to the same object in memory the result will be false. Example: public class Test{ public static void main(String[] args){ String a = new String("hallo"); String b = new String("hallo"); System.out.println(a==b); } } It will return false, even if both strings contain the same value.
The "equals()" on the other side is an instance method. The equals() method implementation of the String class checks whether the content, i.e. the string of the receiver String object is the same as that of the passed String object. Same example as above with equals(): public class Test{ public static void main(String[] args){ String a = new String("hallo"); String b = new String("hallo"); System.out.println(a.equals(b)); } } Now it will return true, since it doesn't check for the references but for the content.
But ATTENTION: If you declare the Strings like this String a = "hallo"; Then also the "==" operator will return true! Example: public class Test{ public static void main(String[] args){ String a = "hallo"; String b = "hallo"; System.out.println(a==b); } } This is because the JVM manages this kind of String a little different. It don't threats them as objects but as some kind of "native" datatype (but I'm not really sure here)
In general it is to say, that whenever Strings have to be compared, the equals() method should be used. The "== null" should only be used to check whether the variable really references to a String object to be sure not to get a NullPointerException
kito
> Is there a difference between the two tests on the object str: > [quoted text clipped - 4 lines] > I have always used the first one and it seems to return true for a > null String but should I be using the second one? Morten Alver - 01 Aug 2006 14:34 GMT > But ATTENTION: > If you declare the Strings like this [quoted text clipped - 11 lines] > It don't threats them as objects but as some kind of "native" datatype > (but I'm not really sure here) Look up the method String.intern(). Java automatically calls this method for string literals, and basically the result is that two equal literals will be represented by the same object. You can intern your own strings if you like, so there's nothing magical about this.
 Signature Morten
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|