Comparing Strings | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Comparing Strings

Hi! I was testing the new acquired knowledge and stumbled upon a problem. The code is as follows: Scanner scan = new Scanner(System.in); System.out.println("Please, enter your password: "); String pass = scan.nextLine(); System.out.println(pass); //Used this line to test this error out, to be sure it was capturing the right word (and it apparently is) if(pass == "password"){ System.out.println("Correct!"); }else{ System.out.println("Wrong password! Get out!"); Why does this run the else statement even if I put in the right word (pass value = "password") ? thanks in advance :)

4th Jan 2017, 12:21 PM
Lloyd
Lloyd - avatar
2 Answers
+ 4
It's because when you create the string object and assign it to the variable "pass" and you compare it to another string object called "password" what you are essentially doing is asking the compiler if they have the same address in memory, But they don't. They are 2 separate String objects with the same contents but different memory addresses. A String is considered an object unlike primitive values (int, double, boolean, ect). So when you set two different string objects equal to each other you are asking if they have the same memory address. To compare 2 Strings use the equals() method or the compareTo() method. equals(String s1) => returns true if this string is equal to s1 ex) if(pass.equals("password"){ ........... } equalsIgnoreCase(String s1) => it Is the same as equals but is case insensitive. Also, you can get a numeric result by using compareTo() compareTo(String s1) => returns and integers greater than zero, equal to zero, for less than zero to indicate whether this string is greater than, Equal to, Or less then s1. for example String s1 = "hello"; String s2 = "goodbye"; System.out.println(s1.compareTo(s2)); returns the result of 1 because g comes before h...... I'm kind of trying to keep this short but if you want to further understand the compareTo() method you should read up on how Strings are stored in memory as integers
3rd Jan 2017, 10:36 PM
Pat Gekoski
Pat Gekoski - avatar
+ 2
Thanks for the answer! helped me a lot =)
4th Jan 2017, 10:57 AM
Lloyd
Lloyd - avatar