Java String comparison

G

grz02

Hi,

Im an experienced developer, but kinda new to Java...
Just want to know how you practically handle this one.

I have this code line (JSP):

String rqstUserid = (String)request.getParameter("userid");

Now I wanna check if this String is a non-empty, not-null string, like:

if (rqstUserid != null) && (rqstUserid.length() > 0)
{ ... }

which looks terribly tedious syntax to me,
since you in some other language would just write something like:

if (rqstUserid<>"")
{ ... }

Is there some smarter way (=shorter syntax) to express the test above in Java,
i.e. when you have to account for null values?
 
D

Dan Hinojosa

grz02 said:
Hi,

Im an experienced developer, but kinda new to Java...
Just want to know how you practically handle this one.

I have this code line (JSP):

String rqstUserid = (String)request.getParameter("userid");

Now I wanna check if this String is a non-empty, not-null string, like:

if (rqstUserid != null) && (rqstUserid.length() > 0)
{ ... }

which looks terribly tedious syntax to me,
since you in some other language would just write something like:

if (rqstUserid<>"")
{ ... }

Is there some smarter way (=shorter syntax) to express the test above in Java,
i.e. when you have to account for null values?


Yes

if (!("".equals(rqstUserid)) {...}

Be warned it doesn't check for null, nor does it evaluate a trim, but
then again I don't think your example of:

if (rqstUserid<>"")

does either.
 
A

Adam Maass

grz02 said:
Hi,

Im an experienced developer, but kinda new to Java...
Just want to know how you practically handle this one.

I have this code line (JSP):

String rqstUserid = (String)request.getParameter("userid");

Now I wanna check if this String is a non-empty, not-null string, like:

if (rqstUserid != null) && (rqstUserid.length() > 0)
{ ... }

which looks terribly tedious syntax to me,
since you in some other language would just write something like:

if (rqstUserid<>"")
{ ... }

Is there some smarter way (=shorter syntax) to express the test above in
Java,
i.e. when you have to account for null values?


No, not really. The syntax you used in your original is a very common idiom
in Java.

You are, by the way, missing a pair of parentheses in your original.

if ((rqstUserid != null) && (rqstUserid.length() > 0))
{ ... }


I would have expressed the second test as !rqstUserId.equals(""), but the
effect is the same.


-- Adam Maass
 
T

Tony Morris

grz02 said:
Hi,

Im an experienced developer, but kinda new to Java...
Just want to know how you practically handle this one.

I have this code line (JSP):

String rqstUserid = (String)request.getParameter("userid");

Now I wanna check if this String is a non-empty, not-null string, like:

if (rqstUserid != null) && (rqstUserid.length() > 0)
{ ... }

which looks terribly tedious syntax to me,
since you in some other language would just write something like:

if (rqstUserid<>"")
{ ... }

Is there some smarter way (=shorter syntax) to express the test above in Java,
i.e. when you have to account for null values?

Some will tell you that calling equals with an empty String is smarter.
Or calling equals on the empty String to avoid the null check.
Or interning the String and performing a reference comparison.
Or calling compareTo and checking for 0.

None of these are smarter, they are all weaker solutions.
You have found the smartest solution.
 
G

grz01

Thanks for replies.
I was hoping it was possible to express this in a shorter way I hadnt
figured out,
but it seems it is not possible to avoid this null-pointer problem
then...

Personally, from a practical viewpoint,
since strings are so frequently used and clutter up syntax
and readability in common cases like this,
it seems to me like a fundamental design-flaw in Java to define String
as objects in the first place.

I'm very sold on OOP in general, but still,
wouldn't String have been better defined as a primitive type?
That would also have avoided a lot of awkward things like
s.equals(t)
instead of the neater
s==t
etc.

Is there any good reason String was defined as object in Java?
 
P

Patricia Shanahan

grz02 said:
Hi,

Im an experienced developer, but kinda new to Java...
Just want to know how you practically handle this one.

I have this code line (JSP):

String rqstUserid = (String)request.getParameter("userid");

Now I wanna check if this String is a non-empty, not-null string, like:

if (rqstUserid != null) && (rqstUserid.length() > 0)
{ ... }

which looks terribly tedious syntax to me,
since you in some other language would just write something like:

if (rqstUserid<>"")
{ ... }

Is there some smarter way (=shorter syntax) to express the test above in Java,
i.e. when you have to account for null values?


The key point to remember here is that every Java variable
or expression has either a primitive type, such as int, or a
pointer type, such as pointer to string (although it is
called "reference" just to confuse the issue). Because there
are no actual struct types, only struct pointer types,
dereferencing is understood for the "." operator.

In terms of e.g. C, rqstUserid is not a string, but a
pointer to string. The test is equivalent to the form:

if( p != null && *p.length() > 0)

Looking at it this way, it is clear that you can skip the
null test if, and only if, you can prove p is not null based
on other information. This is just like C - you would not
write if(*rqstPtr <> "") without knowing that rqstPtr is not
null.

Without knowing the type of "request", I don't know whether
it applies in this case, but many Java methods use a null
pointer return to indicate a different condition from an
empty string. For example, Applet's getParameter call uses a
null return to indicate that the parameter is not set, and
an empty string to indicate it is set but is empty.

Patricia
 
W

willirl

We usually write a little method like this:

public String getParameter(HttpServletRequest req, String param) {
String s = req.getParameter(param);
if (s == null) return "";
return s.toUpperCase();
}

then you can do a little simpler test:

String s = getParameter(req, "paramname");
 
M

Malte

Patricia said:
grz02 wrote:

Without knowing the type of "request", I don't know whether
it applies in this case, but many Java methods use a null
pointer return to indicate a different condition from an
empty string. For example, Applet's getParameter call uses a
null return to indicate that the parameter is not set, and
an empty string to indicate it is set but is empty.

Patricia

From Sun's javadoc for the HttpRequest object:

public java.lang.String getParameter(java.lang.String name)

Returns the value of a request parameter as a String, or null if
the parameter does not exist.

I think it is prudent if not downright necessary to always check for
null when evaluating the result from this call.

Unless of course, one's code is wrapped in a try/catch thingie.
 
J

John C. Bollinger

Followups to comp.lang.java.programmer.

Is there any good reason String was defined as object in Java?

(1) A String is logically _composed_ of primitives (chars).
(2) Java was designed to be object-centric.
(3) If there were a string primitive then a String wrapper class would
be required, and it would probably look virtually identical to the
current String class.
(4) It would be rare to be able to use string primitives for much of
anything without resorting to the string library methods of class
String. It would make for a much worse mess than the minor
inconvenience that got you started on this.

I might be able to come up with a few more if I actually put some
thought into it.
 
A

Anthony Borla

Thanks for replies.
I was hoping it was possible to express this in a shorter way
I hadnt figured out, but it seems it is not possible to avoid
this null-pointer problem then...

Well, it *can* be minimised [or perhaps better hidden] by making use of the
NullObject design pattern [another poster - Andrew McDonagh - already
mentioned this approach].

The approach entails having methods always return an object [thereby
eliminating the need for a 'if (object == null)' test], and where you would
normally return a null, you return an 'empty' or 'default-valued' object
[i.e. all its fields are set to predetermined values] - a NullObject - one
that behaves as an object of its type should, but one that does nothing
consequential.

A Google search will doubtless turn up more information on this topic.

Of course this approach is only useful in classes you implement. If using
API methods that return null you really have no choice but to perform the
'if (object == null)' test since there is no guarantee [unless exception
handling is used] an object [and not a null] will be returned.
Personally, from a practical viewpoint,
since strings are so frequently used and clutter up syntax
and readability in common cases like this,
it seems to me like a fundamental design-flaw in Java to
define String as objects in the first place.

I'm very sold on OOP in general, but still,
wouldn't String have been better defined as a primitive
type? That would also have avoided a lot of awkward
things like s.equals(t) instead of the neater
s==t
etc.

Is there any good reason String was defined as object
in Java?

Actually, I think the question you should be asking is:

Why did Java implement primitive types ? [thus introducing
the complications associated with handling both objects
and primitives]

The reason for asking this question is that a truly 'pure' OOPL would only
support objects [Smalltalk being the classic example]. That Java, and many
other OOPL's make a distinction between primitives and objects is [I
believe] purely for performance reasons. Primitives map directly to hardware
components [i.e. CPU registers] so that many operations can be performed
directly on the hardware, thus bypassing the overhead associated with
object-handling.

Strings do not map to any hardware component, thus the performance benefit
from implementing them as primitives [even if this were easy to do] doesn't
exist. Besides, you'd still need to make method calls on the string [sounds
like a utility class might be needed], so I don't see that making it a
primitive gains anything in the usage stakes.

Finally, the awkwardness you mention [between s == t and s.equals(t)] could
perhaps be addressed via the introduction of a new operator, one that can be
mapped to a class' 'equals' method ? Thus, instead of dong this:

s.equals(t);

you might do something like this:

s <=> t

You certainly couldn't use the '==' operator because [as another poster -
Patricia Shanahan - mentions] Java variables that refer to objects are
really pointers, so that this:

s == t

is a test for pointer equality; this operator would need to remain as is to
maintain current language semantics.

I hope this helps.

Anthony Borla
 
S

Steve Wampler

since you in some other language would just write something like:

if (rqstUserid<>"")
{ ... }

Out of idle curiousity. What is the language that lets you
write the above?
 
G

grz01

Hi Steve,

Well, most languages I guess where strings can be empty (""), but not
null...
like Pascal (even in Borland's Object Pascal), Visual Basic (if they
havent changed it lately), etc.

Actually works fine in PL/SQL, too, because NULL and "" are equivalent
as strings :)
 
G

grz01

Thanks John,
I see what you mean...
After some pondering, I think its actually your point (4) that is the
crucial one.
Just realized it's the absence of ordinary standalone functions
(like e.g: string2 = substring(string, offset, length))
that makes primitive types quite impotent in Java.

ps. isnt it amazing, that classy compiler doesnt even know what
x = sin(y)
means, anymore :)
 
T

Thomas G. Marshall

Anthony Borla coughed up:
grz02 said:
Hi,

Im an experienced developer, but kinda new to Java...
Just want to know how you practically handle this one.

I have this code line (JSP):

String rqstUserid = (String)request.getParameter("userid");

Now I wanna check if this String is a non-empty, not-null
string, like:

if (rqstUserid != null) && (rqstUserid.length() > 0)
{ ... }

which looks terribly tedious syntax to me,
since you in some other language would just write something
like:

if (rqstUserid<>"")
{ ... }

Is there some smarter way (=shorter syntax) to express the
test above in Java, i.e. when you have to account for null
values?

[General answer only - not necessarily addressing JSP issues]

This:

if (rqstUserid != null)

is testing to see whether an object reference was actually returned.
On the other hand, this:

if (rqstUserid.length() > 0)

assumes the existence of an object reference [presumably to a
'String'], and calls its 'length' method to ascertain whether it is
non-empty i.e. contains one or more characters.

The two tests are necessary as they are for quite separate things
[no-object vs. object-with-no-content]

As an aside, other languages such as C or C++ also require both tests
to be performed where an 'object pointer' [loosely-speaking] is
returned, and it is not known whether:

* A valid 'object pointer' or a NULL has been returned
* The 'object' [presumably a 'String' or equivalent] has a
'length' of zero or not

I hope this helps.

Anthony Borla


What on earth made you think that the OP didn't already know all of this?
He stated as much clearly in his post.

What he's asking is if there is a short cut of some kind that he can employ.
Something like

if (! String.NullOrEmpty(str)) {.....}

would be fairly nifty in some circumstances.
 
T

Thomas G. Marshall

Tony Morris coughed up:
Some will tell you that calling equals with an empty String is
smarter. Or calling equals on the empty String to avoid the null
check.
Or interning the String and performing a reference comparison.
Or calling compareTo and checking for 0.

None of these are smarter, they are all weaker solutions.
You have found the smartest solution.


You're not going far enough by calling those "weaker".

Here are some points as to why "no one" should have claimed these as smarter
solutions to the OP's post. They aren't "weaker", they are simply wrong. A
small "however" is at the bottom.

1. calling equals with an empty String.

You're right---this doesn't do it, because str.equals("") doesn't work if
str is null. To the side, IMO, the null type should really have not been a
type but a "special object", a singleton assignable to any object type, with
a few methods of its own, like equals().

2. Or calling equals on the empty String to avoid the null check.

Nope. "".equals(null) is always false, but "".equals("") is always true,
which means two separate checks again. See at the bottom.

3. interning the String and performing a reference comparison.

Doesn't solve the null case either.

4. compareTo

Surprisingly, the String.compareTo(String) method does not check for null.
Here are the first few lines of java 1.5.0's String's compareTo(String):

public int compareTo(String anotherString) {
int len1 = count;
int len2 = anotherString.count;

No check. So there is not much help here. Just a note too, btw, as of JDK
1.5.0, there is no longer a String.compareTo(Object).

*OK, HOWEVER*, and this is to the side of the OP's issue

If checking for comparison to a string literal, the following can
/sometimes/ be useful:

"hello".equals(myString)

Because this expression will yield false when myString is *any of* null,
empty, or different, where as

myString.equals("hello")

Gaks outright if myString is null.
 
T

Thomas G. Marshall

(e-mail address removed) coughed up:
Thanks John,
I see what you mean...
After some pondering, I think its actually your point (4) that is the
crucial one.
Just realized it's the absence of ordinary standalone functions
(like e.g: string2 = substring(string, offset, length))
that makes primitive types quite impotent in Java.

ps. isnt it amazing, that classy compiler doesnt even know what
x = sin(y)
means, anymore :)

:) And thank /GOD/ for that too, by the way.

I am absolutely horrified that I might one day have to design something big
in a procedural language, or even in a language where methods are alowed to
float free from objects. Like that hybrid language, {cough} C++.
 
A

Anthony Borla

Thomas G. Marshall said:
Anthony Borla coughed up:
What on earth made you think that the OP didn't already
know all of this?

He stated as much clearly in his post.

What he's asking is if there is a short cut of some kind that
he can employ. Something like

if (! String.NullOrEmpty(str)) {.....}

would be fairly nifty in some circumstances.

Then you should have posted what you thought was an appropriate answer, just
as I did earlier, addressing it to the OP [rather than another respondent]
to maximise its usefulness.

Cheers,

Anthony Borla
 
C

Chris Uppal

Thomas said:
Just a note too, btw, as of JDK
1.5.0, there is no longer a String.compareTo(Object).

And just a small correction: String.compareTo)Object) does still exist. Its
implementation, translated back into Java would read:

public int
compareTo(Object o)
{
return compareTo((String)o);
}

It's that damnable covariant hack again...

-- chris
 
C

Chris Uppal

Thomas said:
:) And thank /GOD/ for that too, by the way.

I am absolutely horrified that I might one day have to design something
big in a procedural language, or even in a language where methods are
alowed to float free from objects. Like that hybrid language, {cough}
C++.

Or indeed, like that clumsy collection of inelegant hacks, kludged together by
committee, and popularly known (in its marketing dept anyway) as Java 5.

import static java.lang.Math.*;

public class Sin
{
public static void
main(String[] args)
{
double x = PI / 4;
double y = sin(x);
System.out.printf("sin(%f) -> %f", x, y);
System.out.println();
}
}

-- chris
 
A

Andrew McDonagh

Chris said:
Thomas G. Marshall wrote:

:) And thank /GOD/ for that too, by the way.

I am absolutely horrified that I might one day have to design something
big in a procedural language, or even in a language where methods are
alowed to float free from objects. Like that hybrid language, {cough}
C++.


Or indeed, like that clumsy collection of inelegant hacks, kludged together by
committee, and popularly known (in its marketing dept anyway) as Java 5.

import static java.lang.Math.*;

public class Sin
{
public static void
main(String[] args)
{
double x = PI / 4;
double y = sin(x);
System.out.printf("sin(%f) -> %f", x, y);
System.out.println();
}
}

-- chris

:)

Yes its funny that to aid reduce one anti-pattern, they introduce
another one.

http://java.sun.com/j2se/1.5.0/docs/guide/language/static-import.html

Quote from site...

"So when should you use static import? Very sparingly! Only use it when
you'd otherwise be tempted to d...."
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top