Java Forum / General / March 2006
when using equals method with a null string...
minjie@excite.com - 10 Mar 2006 15:22 GMT If I have declared 2 strings as follows: private String myStr1 = ""; private String myStr2 = ""; and somewhere in the application they may or may not get assigned values. When I do if (myStr1.equals(myStr2)) .... I will get an exception if myStr1 is null. How do I test it without using if (myStr1 != null) if (myStr1.equals(myStr2)) .... ? I have a lot of string comparisons like the above, and if I have to test one by one like that, it's a lot of code! Thanks.
Tony Burrows - 10 Mar 2006 15:38 GMT On Fri, 10 Mar 2006 07:22:03 -0800, minjie wrote:
> If I have declared 2 strings as follows: > private String myStr1 = ""; [quoted text clipped - 12 lines] > test one by one like that, it's a lot of code! > Thanks. You're relying on an optimising String creation. Java sees there is no content, so doesn't actually bother to create a String object. Using thi approach, if two strings have the same content, then Java stores just one.
String myStr1 = "one"; String myStr2 = "one"; will create just one String, with two references to it, for the sake of efficiency. This means equals and == will both report true.
On the other hand, you can force Java to create one string object per variable, by using new.
myStr1 = new String(""); creates a real String object, and then you can call equals on it.
Tony
mike - 10 Mar 2006 15:42 GMT The first thing that comes to my head is to write your own method that will do the above. For example:
boolean equals(String a, String b) { if (a != null) return a.equals(b); else return false; }
that would save you on the typing. Other than that, I don't see a better way.
Mike
Ed Kirwan - 10 Mar 2006 15:45 GMT > If I have declared 2 strings as follows: > private String myStr1 = ""; [quoted text clipped - 12 lines] > test one by one like that, it's a lot of code! > Thanks. You could use a library, for example:
class Library { boolean isEqual(String a, String b) { if (a == null) { return false; } else { return a.equals(b); } } }
(Adjust to suit to case a and b both are null.)
At least then your code would only peppered with: if (Library.getInstance().isEqual(a, b)) { .... }
 Signature www.EdmundKirwan.com - Home of The Fractal Class Composition.
Download Fractality, free Java code analyzer: www.EdmundKirwan.com/servlet/fractal/frac-page130.html
Tony Burrows - 10 Mar 2006 16:04 GMT On Fri, 10 Mar 2006 07:22:03 -0800, minjie wrote:
> If I have declared 2 strings as follows: > private String myStr1 = ""; [quoted text clipped - 12 lines] > test one by one like that, it's a lot of code! > Thanks. I've just tried this code in Java 1.4 and 1.5 public class testCode{ public static void main (String[] args){ String s = ""; String y = new String(""); System.out.println("Tony equals string y"+ y.equals("Tony")); System.out.println("Tony equals string s"+ s.equals("Tony")); } } and it compiles and runs with no problems. I don't get a null pointer at all. I can't get one with an if statement either.
Tony
njzy333@gmail.com - 10 Mar 2006 16:29 GMT Hello Tony, That is strange. The difference between your code and my code is that I declared both strings to be private, and neither are NEWed. I changed my code according to your example, and I'm still getting an exception. I guess there is a slight difference in our environment or libraries? I'm using NetBeans with Java 1.5. Thanks.
Oliver Wong - 10 Mar 2006 16:39 GMT > Hello Tony, > That is strange. The difference between your code and my code is that I [quoted text clipped - 3 lines] > I'm using NetBeans with Java 1.5. > Thanks. Try running Tony's code exactly as is. If you're getting NPEs, then your Java is broken, and you should uninstall it, redownload it, and reinstall it.
- Oliver
Hendrik Maryns - 10 Mar 2006 16:54 GMT -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 NotDashEscaped: You need GnuPG to verify this message
njzy333@gmail.com schreef:
> Hello Tony, > That is strange. The difference between your code and my code is that I > declared both strings to be private, and neither are NEWed. I changed > my code according to your example, and I'm still getting an exception. > I guess there is a slight difference in our environment or libraries? > I'm using NetBeans with Java 1.5. Learn the difference between null and "". "" will not throw an NPE if you invoke methods on it. See http://mindprod.com/jgloss/string.html, the part about comparison and gotchas.
H.
 Signature Hendrik Maryns
================== www.lieverleven.be http://aouw.org
Boobay - 10 Mar 2006 18:39 GMT Please read the documentation over NullPointer exceptions. You should be able to use a try catch block and eliminate/track down the problem you're having with your code.
Thomas Hawtin - 10 Mar 2006 19:05 GMT > if (myStr1.equals(myStr2)) > .... [quoted text clipped - 3 lines] > if (myStr1.equals(myStr2)) > .... It is normal to use -
if (myStr1 != null && myStr1.equals(myStr2)) {
If you know that myStr2 will never be null, you can just turn it around (often used with literals) -
if (myStr2.equals(myStr1)) {
You can wrap the null and equals checking up in a small method -
package com....;
public class ObjectUtils { public static boolean eq(Object a, Object b) { return a==b || (a != null && a.equals(b)); } } .... import static com.....ObjectUtils.eq; ... if (eq(myStr1, myStr2)) {
Tom Hawtin
 Signature Unemployed English Java programmer http://jroller.com/page/tackline/
minjie@excite.com - 13 Mar 2006 15:02 GMT steve - 15 Mar 2006 00:26 GMT > If I have declared 2 strings as follows: > private String myStr1 = ""; [quoted text clipped - 12 lines] > test one by one like that, it's a lot of code! > Thanks. code it like this
if ( myStr1 !=null && myStr1.equals(myStr2)){}
java normally evaluates if statements from left to right , therefore if the first action fails the rest of the if statement is NOT evaluated.
Jean-Marie Gaillourdet - 15 Mar 2006 10:21 GMT Hi,
steve schrieb:
> code it like this > > if ( myStr1 !=null && myStr1.equals(myStr2)){} > > java normally evaluates if statements from left to right , therefore if the > first action fails the rest of the if statement is NOT evaluated. Your observation is right, but your explanation not exactly right. If statement conditions have the same evalution order than any other expression. But && is defined to do short circuit evalution, which means that it first checks the left subexpression and only if it is still possible to evaluate the whole expression to true, the right subexpression is evaluated. The same applies to ||. Just to be clear in my point: I want to remark, that this is not a property of the if but a property of the &&.
Regards, Jean-Marie
tom fredriksen - 15 Mar 2006 11:12 GMT > steve schrieb: >> code it like this [quoted text clipped - 12 lines] > my point: I want to remark, that this is not a property of the if but a > property of the &&. The difference being that a || expression will short circuit if it meets a true value expression while a && expression will short circuit if it meets a false value expression.
/tom
steve - 18 Mar 2006 11:49 GMT > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 [quoted text clipped - 30 lines] > =EwBd > -----END PGP SIGNATURE----- sorry i was sloppy.
I should have said:
Evaluations are run from left to right and once the evaluation reaches a definitive condition that cannot be altered by any other evaluation in the if statement, the remaining evaluations are skipped.
It IS a function of the if statement. it is not actually strictly a property of &&, I can think of some bitwise operations (&)
Steve
 Signature http://NewsGuy.com/overview.htm 30Gb $9.95 Carry Forward and On Demand Bandwidth
Chris Uppal - 18 Mar 2006 12:53 GMT > I should have said: > [quoted text clipped - 5 lines] > it is not actually strictly a property of &&, I can think of some > bitwise operations (&) No, this is not true. The "if" is completely irrelevant. E.g in:
boolean b = aTest() && anotherTest();
anotherTest() will only be executed if aTest() returns true. That is a defined property of the && operator. Similarly the || and ?: operators are defined to do short-circuited evaluation.
In contrast the bitwise/logical operations, & and |, do /not/ do short-circuited evaluation, not even when applied to boolean arguments, and not even in the condition of an "if" statement.
See the JLS sections 15.23, 15.24, and 15.25, for the spec for &&, ||, and :? respectively. See section 15.22 for the spec for & and |.
-- chris
Stefan Ram - 18 Mar 2006 16:05 GMT >>It IS a function of the if statement. >No, this is not true. To avoid this misinterpretation (which is well-known to me), in my classes, I teach »&&« strictly separated from »if« and from »?:«. (In fact, I do not use »if« at all in my course as of now.)
It is regrettable that courses often show »&&« only in the context of »if«, so that beginners are lead to assume that »&&« can only occur in this context.
Chris Uppal - 19 Mar 2006 13:55 GMT > It is regrettable that courses often show »&&« only in the > context of »if«, so that beginners are lead to assume that > »&&« can only occur in this context. Arguably teachers should also go out of their way to show comparison operators like == and < outside the condition part of "if" and "while" statements.
I've seen code like: if (a < b) doSomething(true); else doSomething(false); which (IMO) clearly indicates a flawed understanding.
-- chris
Oliver Wong - 20 Mar 2006 17:00 GMT > Arguably teachers should also go out of their way to show comparison > operators [quoted text clipped - 6 lines] > doSomething(false); > which (IMO) clearly indicates a flawed understanding. Sometimes the code used to say something else (i.e. the "then" branch and the "else" branch were both complex, and very different), then someone used an automated refactoring tool, and eventually the changes were such that the code ended up looking like the above. Since the programmer was using a tool, rather than refactoring by hand, (s)he (and the tool) might have not noticed that the above could be further simplified, especially if several thousands of other refactorings were done in the same session.
I've done this for example; leaving behind "stupid" code after a massive refactoring session, I mean.
- Oliver
Chris Uppal - 20 Mar 2006 17:44 GMT [me:]
> > I've seen code like: > > if (a < b) [quoted text clipped - 7 lines] > used an automated refactoring tool, and eventually the changes were such > that the code ended up looking like the above. I suppose that is a plausible sequence.
I wouldn't be any too happy if it actually occurred, though. Not in code that /I/ had to work with...
> Since the programmer was > using a tool, rather than refactoring by hand, (s)he (and the tool) might > have not noticed that the above could be further simplified, especially if > several thousands of other refactorings were done in the same session. FWIW, I have very little time for automated refactoring tools.
-- chris
Roedy Green - 20 Mar 2006 20:28 GMT On Mon, 20 Mar 2006 16:44:50 -0000, "Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org> wrote, quoted or indirectly quoted someone who said :
>FWIW, I have very little time for automated refactoring tools. I think the key is to see them as tools you invoke when you want a certain refactoring rapidly and accurately done, rather than mindlessly accepting whatever "recommendations" the tool makes.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Roedy Green - 18 Mar 2006 17:06 GMT >Evaluations are run from left to right Java inherits a complex set of precedence rules from C++ where most evaluations work left to right but some right to left e.g. casts.
See http://mindprod.com/jgloss/precedence.html for the full story.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Lasse Reichstein Nielsen - 19 Mar 2006 12:24 GMT > Java inherits a complex set of precedence rules from C++ where most > evaluations work left to right but some right to left e.g. casts. Casts aren't really binary operations on expressions, since only one operand can be an expression. The other must be a type literal. Associativity only makes sense for infix (and therefore binary or higher-ary) operators of the same arity. Unary operators are either prefix or postfix, but they have no associativity (only precendence).
Associativity is a disambiguation device for making parsing of expressions unambiguous. The expression 4-3-2 could be ambiguously parsed as either (4-3)-2 or 4-(3-2), so Java specifies that associativity is left-to-right for infox operators with that precendence (i.e., "+" and "-").
In Java, the only ternary infix operator (?:) has a syntax that makes associativity irrelevant, since parsing is always unambiguous. This can be compared to the if/else statement where the "else" can be omitted, so a statement like if (a) if (b) x=2; else x=4; needs disambiguation in the syntax to decide which "if" the "else" belongs to (it's the inner if).
A better example of right-to-left evaluation order would be assignments.
(I can see your table have two rows with precedence 1. I think it would be just as correct to move the postfix operators to the top and give them precedence 0.) /L
 Signature Lasse Reichstein Nielsen - lrn@hotpop.com DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html> 'Faith without judgement merely degrades the spirit divine.'
Jaakko Kangasharju - 19 Mar 2006 13:04 GMT >>Evaluations are run from left to right > > Java inherits a complex set of precedence rules from C++ where most > evaluations work left to right but some right to left e.g. casts. No, Java order of evaluation is always left to right (JLS 15.7). Order of evaluation has nothing to do with precedence and associativity.
 Signature Jaakko Kangasharju, Helsinki Institute for Information Technology Kokoo kokoon koko kokko! Koko kokkoko? Koko kokko!
Roedy Green - 19 Mar 2006 19:08 GMT On Sun, 19 Mar 2006 14:04:51 +0200, Jaakko Kangasharju <jkangash@hiit.fi> wrote, quoted or indirectly quoted someone who said
>No, Java order of evaluation is always left to right (JLS 15.7). >Order of evaluation has nothing to do with precedence and >associativity. In what order are these casts applied:
byte b = (byte) (int) 343.3D;
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Lasse Reichstein Nielsen - 20 Mar 2006 21:24 GMT > On Sun, 19 Mar 2006 14:04:51 +0200, Jaakko Kangasharju > <jkangash@hiit.fi> wrote, quoted or indirectly quoted someone who said [quoted text clipped - 6 lines] > > byte b = (byte) (int) 343.3D; Inside out! :)
An expression is evaluated by evaluating each sub-expression, from left to right, and then combining the results. Since casts are unary prefix operators, there is only one sub-expression, so this holds trivially.
Precedence and associativity does not affect order of evaluation, but structure of the parse tree (i.e., which sub-expressions exist).
/L
 Signature Lasse Reichstein Nielsen - lrn@hotpop.com DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html> 'Faith without judgement merely degrades the spirit divine.'
Roedy Green - 20 Mar 2006 22:34 GMT >> byte b = (byte) (int) 343.3D; > >Inside out! :) the (int) is evaluated before the (byte). If you ask a 5 year old, they will tell you that is right to left.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Lasse Reichstein Nielsen - 21 Mar 2006 02:08 GMT >>> byte b = (byte) (int) 343.3D; >> >>Inside out! :) > > the (int) is evaluated before the (byte). If you ask a 5 year old, > they will tell you that is right to left. More precisely: "(int) 343.3D" is evaluated (to the value 343) before "(byte) 343" is evaluated.
Or, the order of evaluation is:
byte b = (byte) (int) 343.3D; ------------ first ------------------- second ----------------------------- last The part that is evaluated grows towards the left, but it's not "right before left". Compare that to an expression like:
foo() - bar() - baz() ----- first ----- second ------------- third ----- fourth --------------------- fifth In all cases, sub-expressions of the same expressions are evaluated left before right. I.e., evaluating as a post-order left-to-right depth-first traversal of the syntax tree.
/L
 Signature Lasse Reichstein Nielsen - lrn@hotpop.com DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html> 'Faith without judgement merely degrades the spirit divine.'
nospam_googlegroups@scovetta.com - 21 Mar 2006 05:13 GMT Also note that when you want to compare a String with a constant string, instead of doing: if (input != null && input.equals("secret")) doSomething(); you can do: if ("secret".equals(input)) doSomething();
Mike
> > If I have declared 2 strings as follows: > > private String myStr1 = ""; [quoted text clipped - 19 lines] > java normally evaluates if statements from left to right , therefore if the > first action fails the rest of the if statement is NOT evaluated.
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 ...
|
|
|