Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use int or Integer

Tags:

java

integer

int

In my code there are a lot of final values, like 10000. They never change, i do nothing with them, just sometimes checks like if(number1 == number2).

Is it better to use int or Integer for such numbers?

like image 699
user1451415 Avatar asked Nov 29 '22 02:11

user1451415


1 Answers

In your case, use int.

In a general case, if you're in the situation where you could feasibly use either the primitive value is almost always preferred:

  • They're potentially more memory efficient
  • You can always use == reliably, which isn't the case with the class Integer type - you'd have to use .equals() to ensure you were getting what you wanted. See here for more details.

Memory requirements are a lot less of an issue these days, but the big gotcha is the second one, which can cause the potential for a lot of bugs if you're not aware of it (especially since there's cases where == will work as you expect, and others where it won't - it's not a "reliable" bug in that sense.)

like image 143
Michael Berry Avatar answered Dec 22 '22 08:12

Michael Berry