I am solving SonarQube issues , in that issues i face an bellow error but can not understant what kind of error is this ,
Here is my entity class
@Entity @Cacheable @DynamicUpdate @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @Table(name = Vendor.TABLE_NAME) public class Vendor { @Column(name = VENDOR_MODIFIED_BY_FOREIGN_KEY, nullable = true) private Integer modifiedBy; public Integer getModifiedBy() { return modifiedBy == null ? 0 : modifiedBy; //Boxed value is unboxed and then immediately reboxed in com.bostonbyte.thelift.entities.vendors.Vendor.getModifiedBy() } public void setModifiedBy(Integer modifiedBy) { this.modifiedBy = modifiedBy; } I get an error at
public Integer getModifiedBy() { return modifiedBy == null ? 0 : modifiedBy; Could you please let me know what kind of error is this?
4 Answers
That means, that modifiedBy will be unboxed, to compare it with the primitive type and than boxed, because the return value is an object.
Use:
return modifiedBy == null ? Integer.valueOf(0) : modifiedBy; and the error should go away.
0Well, modifiedBy is an Integer, but the type of the ternary conditional expression modifiedBy == null ? 0 : modifiedBy is int (that's the type of the conditional expression when the 2nd operand is an int and the 3rd operand is an Integer, as you can see in table 15.25-C. of the JLS).
Therefore modifiedBy is unboxed to an int in order to evaluate that expression.
Then it is boxed again to Integer, since that's the return type of the getModifiedBy() method.
You could change the return type of that method to int to avoid the boxing (it seems to make sense, since getModifiedBy() can never return null):
public int getModifiedBy() { return modifiedBy == null ? 0 : modifiedBy; } It means that, the automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. In your code modifiedby gets unboxed, for comparing with int value(0) i.e. primitive data type, after values get compared it will again boxed because its return type is Wrapper class, i think you should go with the first answer that is by @jens.
Had the same similar issue with Boolean.
return isModified == null? false : defValue changed to:
return isModified == null? Boolean.valueOf(false) : defValue 0