str.equals(null) or str==null ?

D

David Segall

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?
 
I

Ingo R. Homann

Hi,

David said:
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
 
D

David Segall

Ingo R. Homann said:
Hi,



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?
You aren't. I am! However, is null really the same object as str... ?
 
R

Rogan Dawes

David said:
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
 
M

Mark Space

Rogan said:
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

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?
 
L

Lars Enderin

Mark Space skrev:
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?
I think that's not very elegant.
boolean nullStringOrRef(String s) {
return s == null || s == "";
}
is much better. Learn to use boolean expressions.
 
A

AndrewMcDonagh

Lars said:
Mark Space skrev:
I think that's not very elegant.
boolean nullStringOrRef(String s) {
return s == null || s == "";
}
is much better. Learn to use boolean expressions.


best learn how to do a string equality check then.

S == ""

should be

s.equals("");
 
M

Mark Space

AndrewMcDonagh said:
best learn how to do a string equality check then.

S == ""

should be

s.equals("");

Collectively, a good point. I stand corrected in the aggregate! :)
 
H

Hendrik Maryns

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Ingo R. Homann schreef:
Hi,



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?

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
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFEzwK0e+7xMGD3itQRAs+tAJ4sl/7AFSwpZdGksIH6aWP868kQmACfWGnL
vevqiI+jgmoJB0iLUvr+jIE=
=AtM2
-----END PGP SIGNATURE-----
 
L

Lars Enderin

AndrewMcDonagh said:
Lars Enderin wrote:


best learn how to do a string equality check then.

S == ""

should be

s.equals("");

It's equivalent if there is only one instance of the empty string "" in
the system.
 
K

kito

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
 
C

Chris Brat

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

Ingo R. Homann

Hi,

Hendrik said:
Yes, from String.java:
...
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
 
M

Morten Alver

kito said:
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)

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.
 
P

Patricia Shanahan

Lars said:
Lars Enderin skrev:

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
 
S

Stefan Ram

Patricia Shanahan said:
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.
 
P

Patricia Shanahan

Stefan said:
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.

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
 
B

Bhanu

Stefan said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top