Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Input Problems - how to compare strings [duplicate]

This seems to be pretty simple, but I have been stucked here for a couple of hours.

I have a doubt when you have to compare two Strings in Java.

if I just do something like this:

String var1 = "hello";
String var2 = "hello";

and then compare these two words in another function, the result will clearly be true.

But the problem is when I have to compare two words that come from an input. Here is my code:

import java.util.Scanner;

public class Compare{

public static void main(String[] args){
    Scanner Scanner = new Scanner (System.in);

    System.out.println("Enter first word: ");
    String var1 = Scanner.nextLine();

    System.out.println("Enter second word: ");
    String var2 = Scanner.nextLine();

    if (same (var1, var2))
        System.out.println("Yes");
    else
        System.out.println("No");
}

public static boolean same (String var1, String var2){
    if (var1 == var2)
        return true;        
    else
        return false;
}


}

I have tried several times (clearly entering the same word) and the result is always False.

I don't know why this happens. What am I missing?

This is my first time in Java. I will appreciate any kind of help. Thanks

like image 463
stbamb Avatar asked Jul 29 '26 02:07

stbamb


1 Answers

You should change

if (var1 == var2)
{
    return true;        
}
else
{
    return false;
}

to

if (var1.equals(var2))
{
    return true;        
}
else
{
    return false;
}

See this answer for the difference between the two

like image 96
su- Avatar answered Jul 31 '26 16:07

su-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!