Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

When I calculate byte - 8bits like this 2^7+ 2^6 +2^5 + 2^4 + 2^3 + 2^2 + 2^1 +  2^0. It added up to 255. Then how the byte range is -128 to 127? 

Can anyone tell me how to calculate the range of primitive data types in Java? 

 

1 Answer

0 votes
by (19.7k points)

-2^(n-1) to (2^(n-1)-1) is the formula to calculate the range of data types. 

Where n = no.of.bits of the primitive data type. 

For example: for the byte data type, n = 8 bits

-2^(8-1) to (2^(8-1)-1)

The above calculation will give you -128 to 127. Now, coming to the question of why it’s not 255. The reason is a byte, int, short, double are signed data types meaning it has half the range below 0 (negative) and half the range above 0 (positive). The first bit represents a sign (+ or -). The remaining bits are 7. That’s why 2^(8-1) = 128. We take 0 as a positive sign, so the range is 2^(8-1) - 1 for positive numbers. 

If you want to learn more about Javathen go through this Java tutorial by Intellipaat for more insights.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...