byte to char Java


After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast byte to char as an example.

The byte takes 1 byte of memory and char takes 2 bytes of memory. Here, casting rules do not work like 1 byte value can be assigned to 2 bytes implicitly, as byte can take negative values where as char does not. The explicit conversion takes care of this.

Either byte to char or char to byte requires explicit casting.

Following program example on byte to char explains the explicit casting procedure. Observe, the Java syntax of doing so.
public class Conversions
{
  public static void main(String args[])
  {
    byte b1 = 65;
    // char ch = b1;  
          
    char ch = (char) b1;

    System.out.println("byte value: " + b1);             // prints 65
    System.out.println("Converted char value: " + ch);   // prints A (ASCII is 65 for A)
  }
}


byte to char
Output screenshot of byte to char Java

char ch = b1;

The above statement raises a compilation error "possible loss of precision".

char ch = (char) b1;

The byte b1 is explicitly type casted to char ch. Observe, the syntax of explicit casting. On both sides, it should be char.

View all for 65 types of Conversions

2 thoughts on “byte to char Java”

Leave a Comment

Your email address will not be published.