0

I know that Strings in Java should be compared using .equals() and not using == operator.

But in the given below code there is a primaryObserverId which has a value of ""

The given below if condition runs fine on Java 6 but fails on Java 7

 String primaryObserverId = request.getParameter("primary_observer_id");
        if(primaryObserverId == null || primaryObserverId=="")
            primaryObserverId = RoleMap.getUserIdForThisSession(session.getId());

Need to know why this code was working on Java 6 and not on Java 7.

I know how the concept of String Pool works for string literals in java , just want to know the reason this abrupt behavior.

Can using different version of GlassFish may cause any issue as I am using GlassFish-2.1 with Java 6 and GlassFish-4.1 with Java 7

Abhishek
  • 878
  • 12
  • 28
  • 1
    Something else. NO change with version. – Suresh Atta Dec 18 '15 at 11:49
  • Are you sure that you are getting "" in both Java 6 and 7? – Joker Dec 18 '15 at 11:53
  • 2
    On Java 6 it was just luck: Literals are "cached" and ""=="" works but new String("")=="" does not. – Mikey Dec 18 '15 at 11:55
  • 4
    Most likely `request.getParameter("primary_observer_id")` was changed to return a empty string that was constructed rather than the literal `""`. see http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java . Also in this case `String.isEmpty` should work too. – fabian Dec 18 '15 at 11:56
  • @suresh atta Could the use of two different GlassFish versions cause this discrepancy. Please see my update. – Abhishek Dec 18 '15 at 12:17

2 Answers2

0

All string literals in java are placed in a special area of the heap as they are required. So if you have a variable that is initialised to an empty string, this string is added to the heap. If you have another variable that is initialised to an empty string then it will contain a reference to the empty string already on the heap rather than creating a new one. So it seems your problem is that when you run your application in java 6 for some reason an empty string is on the heap at that point so you can check that the two strings are exactly the same object. However when run in java 7 there is no empty string on the heap so the two string must be completely different objects.

See this article for a more complete explanation.

ewanc
  • 1,284
  • 1
  • 12
  • 23
0

== compares the address in memory while equals() compares if 2 objects are meaningfully equivalent, so in your case it makes more sense to user the equals() method as the Servlet creates the String not using the pool, so they are not == but they are meaningfully equivalent, therefore equals.

String primaryObserverId = request.getParameter("primary_observer_id");

if(primaryObserverId == null || "".equals(primaryObserverId)){
            primaryObserverId = RoleMap.getUserIdForThisSession(session.getId());
}
petre
  • 508
  • 7
  • 9