Open In App

Java Program to Convert Char to Byte

Last Updated : 02 Feb, 2022
Comments
Improve
Suggest changes
1 Like
Like
Report

Given a char in Java, the task is to write a Java program that converts this char into Byte.

Examples:

Input: ch = 'A'
Output: 65

Input: ch = 'B'
Output 66

In Java, char is a primitive data type and it is used to declare characters. It has the capability to hold 16-bit unsigned Unicode characters. The range of a char can lie between 0 to 65,535 (inclusive). It holds a default value that is equal to '\u0000'. Also, the default size is 2. The syntax to declare and initialize a char variable is given below,

Syntax:

char ch1;  // Declaration 
char ch2 = 'G';  // Initialization

In Java, a byte is also a primitive data type and it is used for declaring variables. It contains the capacity to hold an 8-bit signed integer. A byte can range from -128 to 127 (inclusive). It is used to optimize memory in our systems.

This article focuses on converting a char value into an equivalent byte value.

byte by; // Declaration 
byte by = 12; // Initialization

Method 1: Explicit type-casting

We can typecast the char variable into its equivalent Byte value by using explicit type-casting. The syntax is quite simple and given below:

Syntax:

byte by = (byte) ch;

Here, ch is the char variable to be converted into Byte. It tells the compiler to convert the char into its byte equivalent value.

Example: In this program, we have typecasted the char variable ch to a byte. 


Output
71

Method 2:

Steps:

  • Declare a byte array.
  • Iterate over the values of the char array.
  • During each step of the iteration, convert the current value in the char array using explicit typecasting and then insert it into the byte array.

Example: In this program, we have typecasted the char array ch to the equivalent byte array. 


Output
71
101
101
107
115
102
111
114
71
101
101
107
115

Next Article
Practice Tags :

Similar Reads