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..

Recommended Answers

All 2 Replies

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.