Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set greater than 127 int byte variable in java

Tags:

java

casting

byte

I write the following sample code:

public static void main(String[] args) throws Exception
{
      byte number_1 =  127;
      byte number_2 =  (byte) 128;
      System.out.println("number_1 = " + number_1);
      System.out.println("number_2 = " + number_2);
}

I get the following result in output:

number_1 = 127
number_2 = -128

I know range of a byte data type( -128 to 127). Is my sample is correct? What happened? Is there a two's complement operation? I don't understand this behavior.

like image 744
Sam Avatar asked May 18 '26 07:05

Sam


2 Answers

Because one byte can hold upto -128 to 127 only, This is expected behavior of overflow

Check with this loop

for(int index = 0 ; index < 258 ; index ++ ){
  System.out.println((byte)index);
}

number line

Also See

  • Endless for loop
  • Nice comic illustration
like image 109
jmj Avatar answered May 19 '26 20:05

jmj


This is because of byte range . A byte can store values from -128 to 127 only.

like image 20
Pramod Kumar Avatar answered May 19 '26 20:05

Pramod Kumar