Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String is not equal to string?

Tags:

java

string

String[] letters  = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "L"};

Scanner inp = new Scanner(System.in);
String input = (inp.nextLine());
String[] cord = input.split("");

for(int x = 0; x < 10; x++)
    if(letters[x] == cord[1])
        System.out.println("Fk yeah!");

Why the Fk yeah! never happens if I input one of A-L letters?

like image 718
good_evening Avatar asked Aug 20 '11 00:08

good_evening


People also ask

How do you check if a string is not equal to another string?

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.

Can we use != For string?

Note: When comparing two strings in java, we should not use the == or != operators. These operators actually test references, and since multiple String objects can represent the same String, this is liable to give the wrong answer.

Do you use == or .equals for string?

Unfortunately, it's easy to accidentally use == to compare strings, but it will not work reliably. Remember: use equals() to compare strings. There is a variant of equals() called equalsIgnoreCase() that compares two strings, ignoring uppercase/lowercase differences.

Is == and .equals the same?

The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.


1 Answers

Strings are objects. The == compares objects by reference, not by their internal value.

There are 2 solutions:

  1. Use String#equals() method instead to compare the value of two String objects.

    if (letters[x].equals(cord[1]))
    
  2. Use char instead of String. It's a primitive, so == will work.

    char[] letters  = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L'};
    
    Scanner inp = new Scanner(System.in);
    String input = (inp.nextLine());
    char[] cord = input.toCharArray();
    
    for (int x = 0; x < 10; x++)
        if (letters[x] == cord[1])
            System.out.println("Fk yeah!");
    
like image 117
BalusC Avatar answered Nov 08 '22 08:11

BalusC