Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

java - Why doesn't my string comparison work?

Ok, this is stupid, but wtf is going on?

I have a String variable in a servlet, which takes the value of a parameter and based on that value I make a test to do something, but the if is not working. What is the problem?

 String action = request.getParameter("action");
    System.out.println("Action: " + action);
// I put 2 ifs to be sure, but not even one is working
    if(action.equals("something"))
            {
                System.out.println("hey");            
            }
    if(action.trim() == "something")
            {
                System.out.println("hey");
            }

On the console, the System.out.println shows me that the value of action is "something"

Action: something
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your second comparison is wrong. You should also use equals instead of ==, like this:

if (action.trim().equals("something"))

The == operator compares references of (String) objects and under normal circumstances equal strings don't automatically have the same reference, i.e. they are different objects. (Unless both are internalized, but normally you shouldn't consider it)

Other than that your example works fine and the first comparison is valid. Try fixing the second comparison. If it works, you found your problem. If not, try using a debugger and double-check everything.

PS: When comparing literal strings with dynamic string objects, it's good practice to call the equals method on the literal string:

"something".equals(action)

That way you can avoid NullPointerExceptions when the string object is null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...