| Author |
Questions about string comparison
|
Azuritul Wu
Greenhorn
Joined: Apr 21, 2004
Posts: 8
|
|
Hello everyone: While I was reading other people's code...I found the following two coding styles...And I am a little bit curious that whether they differ only in style or some other areas?
|
Preparing...
|
 |
Mani Ram
Ranch Hand
Joined: Mar 11, 2002
Posts: 1140
|
|
In the first case, if the variable operation is null, you will get a NullPointerException, when the String is compared. But that won't be the case with the second style. Additionaly, it is easy to change "doModify" to "doUpdate", if they are defined at a single place as given in the second approach.
|
Mani
Quaerendo Invenietis
|
 |
David Harkness
Ranch Hand
Joined: Aug 07, 2003
Posts: 1646
|
|
|
The first method will get a null pointer exception if the request attribute isn't present. Other than that, the second is generally preferred as it's clearer and easier to change later.
|
 |
Azuritul Wu
Greenhorn
Joined: Apr 21, 2004
Posts: 8
|
|
Thanks for the help. Now i know how to use it. Thank you.
|
 |
Ko Ko Naing
Ranch Hand
Joined: Jun 08, 2002
Posts: 3178
|
|
|
The usage of Constants are pretty good, where there might be a need to change the actual value. As for the null value checking, I prefer checking the null value before doing actual operation on the variable. Otherwise, the unforgivable NullPointerException will occur.
|
Co-author of SCMAD Exam Guide, Author of JMADPlus
SCJP1.2, CCNA, SCWCD1.4, SCBCD1.3, SCMAD1.0, SCJA1.0, SCJP6.0
|
 |
James Carman
Ranch Hand
Joined: Feb 20, 2001
Posts: 580
|
|
Originally posted by Ko Ko Naing: The usage of Constants are pretty good, where there might be a need to change the actual value. As for the null value checking, I prefer checking the null value before doing actual operation on the variable. Otherwise, the unforgivable NullPointerException will occur.
The point is that with the constant.equals() trick, you don't have to worry about the NullPointerException, because it won't happen. You know the constant String is non-null and the String class can compare itself to a null value and return false.
|
James Carman, President<br />Carman Consulting, Inc.
|
 |
 |
|
|
subject: Questions about string comparison
|
|
|