[JAVA] To equalize or not to equalize

Being used to the magic of PHP, it can be quite hard to get used to a more strict language. Variable comparison can only be done if both types are the same. String "5" is definately not the same as Integer 5. But what happens if you compare two strings? That should be easy right? Well, not allways.

Create a small form wich has one textfield. Create a small bean that checks if that value matches a pre-defined value. Enter that value in the textfield. Click submit. And tadaa... it won't match. Let's say our pre-defined value is "foo". If you enter "foo" in the textfield (all without the double quotes) it won't be the same as the pre-defined value. Your code will probably look like:

String param = request.getParameter("param1"); //holds "foo"
if (param == "foo") { //match }

Whatever you will try, it will never match. It probably has to do with something like magic quotes (or at least the java variant of it), or something like that, but it just won't match. There is however a 'trick' to get it working:

String param = request.getParameter("param1"); //holds "foo"
if (param.equals("foo")) { //match }

Looks like it should do the same, but this time, it simply does work. If you look up the javaDoc entry for String.equals it says "To compare the characters of two strings". Hey! Wait a minute! Isn't that what == should do too? In my opinion: yes, in Sun's: guess not. It turns out that == tests if the two strings have the same reference. But, when do strings share the same reference then? Read this:

  • if String objects having the same data are created using a constant expression, a string literal, a reference to an existing string, or by explicitly using the intern() method, their references will be the same
  • if String objects having the same data are created explicitly with the new operator or their values are computed at runtime, their references will be different

So basicly put: use String.equals() to compare the value of two strings. Hmm, I just might to get used to that one day...

R.W.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <img> <center> <table> <tr> <th> <td>
  • Lines and paragraphs break automatically.

More information about formatting options

Powered by Drupal - Design by artinet