Is it a good practice to use byte/short as counter variable when we know the exact number of loops? for example
for (byte i = 1; i <= 26; i++)
vs
for (short i = 1; i <= 26; i++)
vs
for (int i = 1; i <=26; i++)
A counter variable in Java is a special type of variable which is used in the loop to count the repetitions or to know about in which repetition we are in. In simple words, a counter variable is a variable that keeps track of the number of times a specific piece of code is executed.
So, integers are not always necessary for loops, and the best optimisation is always to not do something that not necessary. If, however, the loop explicitly needs the integer then the int type would generally provide the best result.
Only difference is with the range of values it can hold. Byte variable can hold values from -127 to +128. Bytes consists of 8 bits. In C# integer is of 4 bytes.. so has more range.
short datatype is the variable range is more than byte but less than int and it also requires more memory than byte but less memory in comparison to int. The compiler automatically promotes the short variables to type int, if they are used in an expression and the value exceeds their range.
Short answer: No.
Long answer: No, because CPU's are optimized for integer operations. If you work with bytes or shorts, the CPU constantly has to convert it to integers and back, generally by applying bitmasks.
When you perform some operations on short or byte variable you have to explicitly typecast it back to the required type in java. So it is preferred to use int in place of byte and short. Example :
short s = 0;
s= (short) (s+10);
If you do not typecast it to int it will throw compile time error : Type mismatch: cannot convert from int to short
So it is preferred to use int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With