Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn’t == work on String? [duplicate]

Tags:

java

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?

like image 692
user2545642 Avatar asked Jul 03 '13 08:07

user2545642


2 Answers

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

like image 53
Suresh Atta Avatar answered Sep 19 '22 12:09

Suresh Atta


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"))
like image 33
Kevin Bowersox Avatar answered Sep 19 '22 12:09

Kevin Bowersox