[Java] If-else involving strings

  • Java
  • Thread starter Deathfish
  • Start date
  • #1
86
0
I have an if-else piece of code involving strings

String color = sc.nextLine();
if (color == "R" || color == "r"){
System.out.println("red");
}
else if (color == "G" || color == "g"){
System.out.println("green");
}
else if (color == "B" || color == "b"){
System.out.println("blue");
}
else{
System.out.println("Invalid input.");
}

Why is it that no matter what input I put in, it always returns invalid input?
 

Answers and Replies

  • #3
34,687
6,394
I'm not sure how string literals are stored in Java, but in C and C++, string literals evaluate to the address of their first byte in memory. IOW, a string literal such as "R" would evaluate to the location of the 'R' character.
 
  • #4
DavidSnider
Gold Member
500
141
if (color == "R" || color == "r")

is better written as:

if(color.toUpperCase.Equals("R"))
 
  • #5
34,687
6,394
On the other hand, if color is of type char, you CAN do this:
Code:
if (color == 'R' || color == 'r')
{
   ...
}
else if ((color == 'G' || color == 'g')
{
   ...
}
...
Note that character literals are delimited by single quotes, not double quotes.
 
  • #6
29
3
This will work.

if (color.equals("R")|| color.equals("r"))
{
System.out.println("red");
}
else if (color.equals("G") || color.equals("g"))
{
System.out.println("green");
}
else if (color.equals("B") || color.equals("b"))
{
System.out.println("blue");
}
else
{
System.out.println("Invalid input.");
}
 

Related Threads on [Java] If-else involving strings

  • Last Post
Replies
15
Views
4K
  • Last Post
Replies
3
Views
6K
Replies
2
Views
1K
  • Last Post
Replies
2
Views
39K
Replies
2
Views
2K
  • Last Post
Replies
16
Views
2K
Replies
7
Views
6K
  • Last Post
Replies
20
Views
1K
Replies
9
Views
1K
  • Last Post
Replies
2
Views
594
Top