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.
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??
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:
true// two variable pointing to same address
true
Different Employee
false //False because new object created and reference pointing two different object.
true
No comments:
Post a Comment