-3

import java.util.Scanner; public class RandomTest {

public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
    String[] alphabets={"a","b"};
    String [] cipher={"b","c"};
    System.out.println("Please enter a letter.");
                String word=input.nextLine();

    for (int i=0;i<2;i++){
        if (word.equals(alphabets[i])){
            System.out.println("Preparing a cipher");
            System.out.println("Here is the cipher: "+cipher[i]);

            }
    }
}
}

This code above works perfectly fine, but instead of saying (word.equals(alphabets[i])), if i put word==alphabets[i] it wouldn't work at all. While using the later, the program does not check if the input is equal to a value in the array. Why does this happen?

  • Also, see [this question](http://stackoverflow.com/questions/7520432/java-vs-equals-confusion) – augray Aug 02 '15 at 00:05
  • 2
    This may be better duplicate: [whats the difference between “.equals" and "==”](http://stackoverflow.com/questions/1643067/whats-the-difference-between-equals-and) – Pshemo Aug 02 '15 at 00:25

1 Answers1

0

== is an operator which compares the objects' locations in memory. equals() is a method defined in Object meant for comparing the actual content/values. By default, these two options behave similarly, but Java's String class overrides equals() when comparing strings.

In the future, please do research before asking questions. There is plenty of information to be found on the Internet.

deezy
  • 1,480
  • 1
  • 11
  • 22
  • 1
    "There is plenty of information to be found on the Internet"--my facepalm when I realize how many people don't know this – D. Ben Knoble Aug 02 '15 at 03:10