Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte/short Vs int as for loop counter variable

Tags:

java

for-loop

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++)
like image 640
MaheshVarma Avatar asked Dec 04 '13 08:12

MaheshVarma


People also ask

What are counter variables in for loop?

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.

Is it necessary that loop counter only of integer data type?

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.

What is the difference between Byte and integer?

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.

What is the difference in size between an INT A short a byte and a long integral data type?

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.


2 Answers

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.

like image 149
Martijn Courteaux Avatar answered Sep 19 '22 17:09

Martijn Courteaux


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.

like image 23
Nishant Lakhara Avatar answered Sep 20 '22 17:09

Nishant Lakhara