-2
import java.util.Scanner;

public class First{
  public static void main(String[] args) {

    byte a = (byte)257;
    System.out.println(a); // output : 1
  }
}

I am new to Java and I do not know how am I getting an output of 1 here, can anyone explain it ?

  • 1
    `257&0xff` is 1. `0xff` is the pattern of bits supported by a single byte. What did you expect the result to be? – khelwood May 20 '22 at 03:53
  • For more information, this question has already been answered here: https://stackoverflow.com/questions/19808612/converting-integer-variable-to-byte-variable – r Blue May 20 '22 at 04:04

1 Answers1

1

Here, binary system plays it's role. Binary code for 257 is 100000001. Now as you already know that byte occupies 1 byte memory (8 bits). This means that a byte variable can only store 8 zeroes and ones. Since in the binary code of 257 (100000001), we have 9 bits (zeroes and ones), compiler will automatically try to convert into 8 bits. For truncating, it will take 8 bits from the right and finally what will be stored in the byte variable stored will be 00000001 (the leftmost 1 is truncated). Now 00000001 is the binary code of 1 so 1 is stored in your variable a. Thus, a is displayed.

I hope you got what I want to say.

Utkarsh Sahu
  • 409
  • 3
  • 16