8

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?

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
user2545642
  • 345
  • 1
  • 4
  • 14
  • use equals instead of == for string in java. Check other questions on this site for more precisions about this. – benzonico Jul 03 '13 at 08:31
  • This has been asked a lot of time in SO. Please take a while to explore before posting http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – sanbhat Jul 03 '13 at 08:34
  • 3
    whenever someone compares Java `String`s with `==` a Developer cries... – Marco Forberg Jul 03 '13 at 09:27
  • Oh god... you know you haven’t done Java in a while when you’re suddenly get flashbacks to pointer exam questions the second == is brought up – jscul Oct 24 '18 at 02:14
  • "Why doesn't == work on String`? It _does_ work! It just **doesn't do what you normally want** when you're asking if one string is "equal to" another. – Kevin Anderson Oct 24 '18 at 02:27
  • None of these answers explains the deeper "why can't you compare strings using ==?" As in the foundation of the decision in the language specification. For someone who has no experience of C, it's entirely counterintuitive. – jarmod Nov 22 '20 at 17:16
  • This is the answer you were looking for: https://stackoverflow.com/a/14123474/912829 – ACV Jan 13 '21 at 22:36

7 Answers7

30

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

shmosel
  • 49,289
  • 6
  • 73
  • 138
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 7
    Or, even better, `"boy".equals(gender)` because this works even if `gender == null`. –  Jul 03 '13 at 08:32
  • and `equalsIgnoreCase()` would be even better :D – WarrenFaith Jul 03 '13 at 08:32
  • 5
    @Tichodroma Sometimes if something is `null`, you should take care of it.. So you actually want to see the NPE in order to prevent this.. However, if you **can** set some String to `null` in purpose.. then this attitude is very good. – Maroun Jul 03 '13 at 09:04
  • @MarounMaroun: If null is expected and to be treated differently then checking for `null` would be better to catch the NPE – Marco Forberg Jul 03 '13 at 09:29
  • 2
    Java is the weirdest language ever – Jesse de gans Nov 11 '18 at 14:07
7

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"))
Jimmy Pelton
  • 11
  • 3
  • 16
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

Use equals instead of ==

if("boy".equals(gender)){

}

use equals To compare the value. while == is compare object reference.

bNd
  • 7,512
  • 7
  • 39
  • 72
1
String a,b;

a==b;

here references(addresses) of both string objects are compared

a.equals(b);

here contents of both strings are compared

RAS
  • 8,100
  • 16
  • 64
  • 86
claw
  • 11
  • 1
1

In Java, strings are objects (String). Variables which contain objects are references. If you compare two objects with == operator, true is returned only if they are the same objects (in memory). But in your code they aren't ("boys" is an instantialized String on the fly).

There is, however, a method String.equals(), which compares two strings and returns true if they have the same characters in the same order, not if they are the same objects.

Correct code here:

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.equals("boy")) {
            System.out.println("BOY");
        } 

        else {
            System.out.println("GIRL");
        }
    }
}

You can also swap the two strings (the advantage is that it prevents NullPointerException from being thrown if gender == null):

"boy".equals(gender)

To ignore the case of letters in comparison, use equalsIgnoreCase() instead.

wassup
  • 2,333
  • 2
  • 21
  • 30
0

you cant compare strings like that in java, You need to use

if (gender.equals("boy"))

for it to work. Your way is comparing the object rather than the content

exussum
  • 18,275
  • 8
  • 32
  • 65
0

You're using reference equality there. The == is literally comparing the 2 references. i.e. are they the same object.

You need to use the equals() method, which (in this case) will compare the contents of the two strings. See here for more info.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • correct, but should his code not work, too? strings are internalized, so when reading "boy" the ref should both point to the same "boy" string object? – AlexWien Jul 03 '13 at 08:36