开发者

Why two same strings not matched under if condition....?

Can you tell me where i have done mistake in this program .

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code="kk" height=400 width=400></apple开发者_StackOverflow中文版t>*/
public class kk extends Applet implements ActionListener
{
    Button b;
    TextField t;
    String str1,str2;
    public void init()
    {
        b=new Button("submit");
        t=new TextField(20);
        add(t);
        add(b);
        b.addActionListener(this);
    }
    public void actionPerformed(ActionEvent ae)
    {
        try
        {
            str2="mohit";
            str1=t.getText();
            if(str1==str2)
            {
                System.out.println("matched");
            }
            else
            {
                System.out.println("not matched");
            }
        }
        catch(Exception e)
        {
            System.out.println("Exception caught ");
        }
    }
}

Don't know why str1 and str2 are not matched.


Yes - you're comparing whether str1 and str2 refer to the exact same string objects, when you want to compare whether the strings are equal:

if (str1.equals(str2))

The == operator will always compare references rather than perform any type-specific equality checking, when applied to variables of reference types.


Your checking for identity (==) but you actually want to check for equality (.equals()).

This is necessary, because, like in real world, two things may look equal.

If you need to now whether two variables reference the same object, use ==. Otherwise, if you only want to know, if two variables reference objects, that have the same state (aka "content"), use the equals method.


I'm not really sure what you're trying to do there and what you enter in TextField t, but you should test for String equality using the equals()-Method


== operator compares object references whereas .equals is used to compare strings !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜