Assignment of beyond range value

Learn what happen when out of range assigned to variable

Each data type in java has a specific memory to store data. When a large value assigned to variable of less size then some information will be lost. In this tutorial we will see how values are converted into in range value.

Range calculation for a Variable

Let's assume we have a variable of byte data type in java. Byte data type can be used to store integer value in range [-128 to 127]. Data size of byte is 1 Byte.


0 0 1 1 0 1 0 1

Now every bit space can have either 0 or 1. Only two values are possible. So one bit can store maximum two values 1 or 0.
For byte data type number of bits are 8. So total number of values will be 2*2*2*2*2*2*2*2



Total number of values = 28
Total number of values = 256
		

Range of byte data type then will be 0 to 255.

[0,1,2,3,4, ......254,255]

Above given range is for unsigned byte(Only positive numbers)
To calculate signed range same process has to be executed. For signed number one digit is taken for storing sign of the number. byte data type having total 8 bits. one bit reserved for sign , seven bit left for storing number.


+/- 0 1 1 0 1 0 1

number of bits for storing number are 7. So total number of values will be 2*2*2*2*2*2*2


Total number of values = 27
Total number of values = 128

Range of byte data type then will be 128 positive values and 128 negative values.



[-128,-127,-126,......-2,-1,0,1,2,3,..,126,127]



This is general question what happen when we assign a value out of range to a variable. for example what will happen when we assign 257 to a byte variable.


// file : one.java 
// www.jgyan.com   
class one 
{	
  public static void main(String arg[])
   { 
    unsigned byte b=(byte)257;
    System.out.println(b);
   }
}
// Output 
// 1


Binary representation of 257 is 100000001. There are 9 bits, but space allocated to byte variable is only 8 bits. byte variable can accommodate only 8 bits. So one bit is discarded(left most bit)


After discarding the binary is 00000001



0 0 0 0 0 0 0 1

It is 1.


// one.java 
// www.jgyan.com	   
class one
{ 
	public static void main(String arg[])
	{   
	   byte b=129;
          System.out.println(b);
	}
}
// Output 
// -127