0

I am within my first year of CS and near the end of my first Java themed course so I'm not quite sure how to find the answer to my question myself.

While writing some code for a project I created my input scanner as:

Scanner scanner = new Scanner(System.in);

I am taking user inputs as strings via a variable assignment:

String userInput = scanner.nextLine();

the user should only be entering strings of char "1" - "6" and "q" (to quit app)

What I'm using that works currently is as follows:

 userInput = scanner.nextLine();
    while (!appQuit) { //So long as user doesn't quit application
        if (userInput.equals("q")) {
            appQuit = true;
        }
        
        else if (userInput.equals("1")) { //Menu selection for intake a new dog
            intakeNewDog(scanner);
            displayMenu();
            userInput = scanner.nextLine();

        }
        //removed "2" - "6" for brevity
        else {
            System.out.println("Not a valid input");
            displayMenu();
            userInput = scanner.nextLine();
        }


    }

The only way I found to check equality was the userInput.equals() function. When I originally wrote it I tried using:

if (userInput == "1") { code }

but it would never successfully compare values as I thought it would.

Any insight into why one method works over the other? Or where I should be looking for these answers?

-Jonesy

2 Answers2

1

The == equal operator compares the object references where the equals function compares the value.

For primitive types and enums the == equal operator compares the value.

An exception happens for comparing strings in a switch case statement since it internal uses the equals method.

As a rule of thumb, always use equals comparison for String. There maybe is, but i have not seen a case where reference comparison was important.

https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html

Also interesting:

What makes reference comparison (==) work for some strings in Java?

djmj
  • 5,579
  • 5
  • 54
  • 92
0

In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects. You can override the equals method to do more specific things, but that's the just of it.

This is literally the first thing that appears if you search java == vs equals in google.

While you might be trying to compare two strings, the operator == does not behave in java as it does in other languages.