I just started Java programming. I love it so far, but I have been stuck on this problem for a while.
When I run this code, whenever I type in “boy” it will just respond with GIRL
:
import java.util.Scanner;
public class ifstatementgirlorboy {
public static void main(String args[]) {
System.out.println("Are you a boy or a girl?");
Scanner input = new Scanner(System.in);
String gender = input.nextLine();
if(gender=="boy") {
System.out.println("BOY");
}
else {
System.out.println("GIRL");
}
}
}
Why?
Use the String.equals(String otherString)
function to compare strings, not the ==
operator.
This is because the ==
operator only compares object references, while
the String.equals()
method compares both String
's values i.e. the sequence of characters that make up each String
.
equals() method from Source code of String:
public boolean equals(Object anObject) {
1013 if (this == anObject) {
1014 return true;
1015 }
1016 if (anObject instanceof String) {
1017 String anotherString = (String)anObject;
1018 int n = count;
1019 if (n == anotherString.count) {
1020 char v1[] = value;
1021 char v2[] = anotherString.value;
1022 int i = offset;
1023 int j = anotherString.offset;
1024 while (n-- != 0) {
1025 if (v1[i++] != v2[j++])
1026 return false;
1027 }
1028 return true;
1029 }
1030 }
1031 return false;
1032 }
So you should write
if(gender.equals("boy")){
}
or to comapre with regardless of case
if(gender.equalsIgnoreCase("boy")){
}
and for null safety
if("boy".equals(gender)){
}
Future reference:
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object
Here s1 == s2 == s3 but s4 != s5
Where as
anyOfAbove.equals(anyOtherOfAbove); //true
When comparing objects of type String
, you should use the equals
method instead of operator ==
. equals
will compare the values of String
objects while ==
checks to see if they are the same object in memory.
So instead of:
if(gender=="boy")
use
if(gender.equals("boy"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With