Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using Integer in loop makes any difference?

I've been using int in for-loop. Like below:

for (int i = 0; i < 100 ; i++) {
     //Do something...
}

If I use Integer instead of int, like below, does it makes any difference?

for (Integer i = 0; i < 100 ; i++) {
     //Do something...
}
like image 234
Gokul Nath KP Avatar asked Jan 16 '26 21:01

Gokul Nath KP


1 Answers

Yes, it will require auto-unboxing and auto-boxing for each iteration. It'll work the same way, and you don't need to do anything to make it work, but it's unnecessary and easily avoided.

Also it might slightly slow down the loop for no real advantage.

Basically Integer should only ever be used when you actually need the number to be an Object (for example when you put it into a collection, when null is a valid value, ...). At all other times, you should use the primitive types where possible (int, char, ...).

like image 122
Joachim Sauer Avatar answered Jan 19 '26 17:01

Joachim Sauer



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!