7

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
jww
  • 97,681
  • 90
  • 411
  • 885
cc.
  • 5,533
  • 14
  • 37
  • 46
  • What is not working? Is "hey" printed only once, and did you expect it to be printed twice? Did "hey" not appear on your console? – Bart Kiers Oct 07 '09 at 10:52
  • He is pretty specific: // I put 2 ifs to be sure, but not even one is working. – dpq Oct 07 '09 at 10:57
  • 8
    Please don't call it "JAVA" - it's "Java". The name is not an acronym, so you don't need to write it with all caps. – Jesper Oct 07 '09 at 10:57
  • Ok. I will not called it "JAVA" anymore. :) 1. The first if( action.equals) is working in the first place, but in another function, I evaluate the variable and the if in not working, and I know for sure the value is the same. Anw, my problem, I will try to find out alone what is the problem. 2. Thanx for all the answers, I will not use "==" for this kind of evalutions anymore, and secondly, I will not use compareTo(), like I did 5 minutes ago (still for the same evaluation type). Problems resolved. (kinda of :)) – cc. Oct 07 '09 at 11:32
  • I edited the title: JAVA -> Java :) – cc. Oct 07 '09 at 11:49
  • The programming language in title is actually entirely irrelevant since there's the tag "Java" in this question already. Why repeat yourself when people do see the context from the tags? :) – Esko Oct 09 '09 at 07:40
  • @Esko - also see [Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles) Tags should ***not*** normally be in the title. Its a site policy that few enforce. – jww Sep 27 '14 at 02:53

8 Answers8

37

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.

Community
  • 1
  • 1
Daniel Rikowski
  • 71,375
  • 57
  • 251
  • 329
9

Your second condition is unlikely ever to be true - you're testing whether the string object created by trimming action is the same object as the string literal "something". This will only be true if action is set to that same literal value elsewhere. Use "something".equals( action.trim() ) instead.

Your first condition would be true the characters in the action string are the characters "something". If it's not true, then it doesn't. Assert it in a test, log it, print it or look at it in a debugger.

If you print a string for debugging, use something like System.out.println ( "String = >" + string + "<" ); so that it's obvious if there are any trailing spaces.

Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171
  • Your answer should be preferred, it's more correct and even avoids NPE:s (in theory, not in this exact case tho'). Oh well, here's to hoping loads of other peoples notice that too. – Esko Oct 08 '09 at 11:40
  • +1 for printing strings inside ">", this just highlighted a trailing newline that was messing with my string.matches()! – shearn89 Aug 12 '14 at 13:43
4

String comparison in Java cannot be done by ==.

You have to use String.equals() or String.compareTo()-

By the way, String.compareTo() returns 0 whereas String.equals() returns true when two strings are equal.

See: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#equals(java.lang.Object)

lifebalance
  • 1,846
  • 3
  • 25
  • 57
JCasso
  • 5,423
  • 2
  • 28
  • 42
  • 1
    What you say is true, but it would be more helpful if you explained _why_ it is true. (I.e., `a.equals(b)` tests whether the contents of the two strings are the same, but `a == b` only returns true when a and b both refer to the same String object.) – Solomon Slow Sep 27 '14 at 02:13
1

My guess is that you've got trailing or leading spaces which don't show in the println.

Combine this with the fact that you're using action.trim() == 'something' means this test won't work either.

Switch this to .equals("something") as suggested by others and it might work.

Chris R
  • 2,464
  • 3
  • 25
  • 31
  • 1
    I often do `System.out.println("Action: [" + action + ']');` for debugs as then you can see the trailing spaces. – Chris R Oct 07 '09 at 11:07
  • Sorry that should be `System.out.println("Action: [" + action + "]");`. I've been writing JavaScript this morning :) – Chris R Oct 07 '09 at 11:08
1

You can better protect against nulls by switching the if clauses around to have the string literal first.

But since you also seem to want to protect against whitespace on the parameter value, you could also do a null safe trim of the parameter value using StringUtils.trimToEmpty from Apache Commons Lang:

String action = StringUtils.trimToEmpty(request.getParameter("action"));

System.out.println("Action: " + action);

if("something".equals(action)) {
   System.out.println("hey");            
}
A_M
  • 7,693
  • 6
  • 33
  • 37
0

Just a wild guess: could be that one of these "somethings" contains e.g. a Cyrillic character that looks identical to its Latin counterpart. In this case, it could be the "o".

dpq
  • 9,028
  • 10
  • 49
  • 69
0

try this :

String action = request.getParameter("action");
System.out.println("Action: " + action);

if(action.trim().equals("something"))
{
    System.out.println("hey");            
}
krock
  • 28,904
  • 13
  • 79
  • 85
-7

The equals method compares the strings for object identity and compares not the content. To compare the content of two strings, use the compareTo method.

Frank
  • 1
  • 10
    This is plain wrong. `String.equals()` compares the strings and returns `true` if they are equal—just as one would expect. – Bombe Oct 07 '09 at 11:06