0

I've been trying to compare a string which is stored in two diffrent variables(but the content is same). I get the two same inputs from user..

package switchcasepgm;
import java.util.Scanner;

public class stringcomp {
    public static void main(String[] args)
    {
        Scanner getinp=new Scanner(System.in);
        System.out.println();
        String sdr = getinp.nextLine();
        System.out.println();
        String rds = getinp.nextLine();
if(sdr==rds)
{
    System.out.println("succ");
}
else
{
    System.out.println("fail");
}

}
}

But the output always returns the else statement.. here's the output..

yes

yes
fail

even i tried for if(sdr=="yes"), it to returns only the else statement.. I've tried for many possibilites, but not get it..

Edited by krnaveen14

2
Contributors
2
Replies
12
Views
2 Years
Discussion Span
Last Post by krnaveen14
1

You compare srtings with the method equals() in the String class
sdr.equals(rds). Equals would check whether the objects are the same, while == checks their references

0

thank you.. and from this, i tried out the sdr.equals("yes"), and it works too.. thanks for the reply..

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.