• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

using String/char in boolean statment

 
gaine chung
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
simple question from a simple mind: How do you use a String/char in a boolean statment? ie: if (userInput == 'N') {do something};
[This message has been edited by gaine chung (edited October 24, 2001).]
 
Junilu Lacar
Bartender
Pie
Posts: 7306
45
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use == for char comparison:
<pre>
char userInput = ...
if (userInput == 'N') { // do something }
</pre>
but use equals() when comparing String:
<pre>
String userInput = ...
if ("N".equals(userInput)) { // do something }
</pre>
The above form is safer than writing
<pre>userInput.equals("N")</pre>
because the latter will produce a NullPointerException if userInput is null.

------------------
Junilu Lacar
Sun Certified Programmer for the Java� 2 Platform
 
gaine chung
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That was exactly what I was looking for. Thanks junilu!
- Gaine
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic