Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int or Integer in java [duplicate]

I have seen many times in code that people use int or Integer to declare variable in beans. I know int is datatype and Integer is wrapper class. My question is, in which condition int or Integer should be used and is there any advantage of either of them over another?


1 Answers

My question is, in which condition int or Integer should be used and is there any advantage of either of them over another?

Well, you should use the reference type Integer whenever you have to. Integer is nothing more than a boxed int. An Object with a single field containing the specified int value.

Consider this example

public class Ex {
    int field1;
    Integer field2;

    public Ex(){}
}

In this case field1 will be initialized with the value 0 while field2 will be initialized with null. Depending on what the fields represent, both approaches might be advantageous. If field1 represents some kind of UUID, would you want it to be initialized with a zero value?

I wouldn't worry too much about the performance implications of Autoboxing. You can still optimize after you get your code running.

For more information take a look at the documentation

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Integer.html

like image 59
Tmrd993 Avatar answered May 24 '26 02:05

Tmrd993



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!