11
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?

5
  • Are you sure cord is actually just the letter and no whitespace? Commented Aug 20, 2011 at 0:43
  • could also be upper vs lowercase Commented Aug 20, 2011 at 0:44
  • Yes, I am sure 100%. No, they both uppercase. Commented Aug 20, 2011 at 0:44
  • 1
    possible duplicate of What is the difference between .Equals and == Commented Aug 20, 2011 at 0:50
  • you should use compareTo instead of == Commented Aug 20, 2011 at 3:26

2 Answers 2

24

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!");
    
Sign up to request clarification or add additional context in comments.

5 Comments

holy cow you have a lot of badges
@Code: It's nothing when compared to Jon Skeet.
well congrats either way :) I bow to you Sir
@BalusC - does the # notation in String#equals() mean its an instance method?
@Kublai: Nothing special. I tend much to use javadoc style to refer the classname/methodname in written text (as one would normally do in javadocs).
11

To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them). Use the .equals() method to compare strings for equality. Similarly, use the .compareTo() method to test for unequal comparisons. For example,

String s = "something", t = "maybe something else";
if (s == t)      // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t)    // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.