Java – why not = = work on a string?

See English answers > How do I compare strings in Java? 23

When I run this code, whenever I type "boy", it will only respond to Ctrl:

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?

Solution

Use string The equals (string otherstring) function is used to compare strings instead of the = = operator

This is because the = = operator only compares object references to string The equals () method compares the values of two strings, 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")){

}

Anyway, or with comapre

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

}

And for safety

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

}

Future references:

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

anyOfAbove. equals(anyOtherOfAbove); // real

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>