Tuesday, January 25, 2022

Java Long variable not equals on == check , why?

 Today we faced a issue in dev environment, the same code works perfectly in local. We have no clue what happens in prod, we thought of data is problem in dev environment. While comparing data between environment we find the empId (Long Type is problem), which mean the type is not a problem, the way compare the Long variable makes the problem in different environment.

Here code snippet of problematic code. 

Boolean isEmployee = employee.getEmpId() == emp.getEmpId();

Since in local we have limited data might be around 50 data max, so empId is might max 50.

Let see what happen in dev environment.

    Dev environment we have lot of data for this particular table. approximately 10000+ records.

Is count of employee table makes that problem??. Partially Yes. How??
Let me explain what is the problem with above code??
In java Long variable will have [-128 to 127] range. If the value is greater than -128 and
less than 127 above condition will return true. else false. why??


Let see how internally Long works, literal values auto boxing using Long.valueOf(String),
this will works on Long [-128 to 127] range and it will find the value from LongCache.
If number greater than 127, then new Long object will create, so while using "==" return false.


What is the fix for our problem??

    We need to use .equals instead of ==. Fix is employee.getEmpId().equals(emp.getEmpId()) or employee.getEmpId().longValue() == emp.getEmpId().longValue().


Here is two example of < 127 and > 127.

public static void main(String[] args) {
Employee employee = new Employee("B", 1, 128L);
Employee emp = new Employee("B", 1, 128L);
Boolean isEmployee = employee.getEmpId() == emp.getEmpId();
if(isEmployee){
//Logic here.
System.out.println("Same Employee");
}else{
System.out.println("Different Employee");
}
System.out.println(employee.getEmpId() == emp.getEmpId());
System.out.println(employee.getEmpId().equals(emp.getEmpId()));
}

Output:

Same Employee
true// two variable pointing to same address
true


If we change empId to 128 and the output below is,
Different Employee
false //False because new object created and reference pointing two different object.
true

Integer also works same way. Here the link for Integer on == 

No comments:

Post a Comment