Java Program to Convert Char to Byte
Last Updated :
02 Feb, 2022
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
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.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
char ch = 'G' ;
byte by = ( byte ) ch ;
System.out.println(by);
}
}
|
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.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
char [] ch = { 'G' , 'e' , 'e' , 'k' , 's' , 'f' , 'o' , 'r' , 'G' , 'e' , 'e' , 'k' , 's' };
byte [] by = new byte [ch.length];
for ( int i = 0 ; i < ch.length; i++) {
by[i] = ( byte )ch[i];
}
for ( int i = 0 ; i < by.length ; i++)
{
System.out.println(by[i]);
}
}
}
|
Output
71
101
101
107
115
102
111
114
71
101
101
107
115
Share your thoughts in the comments
Please Login to comment...