Java Program to Store Unicode Characters Using Character Literals
The Unicode-characters are universal characters encoding standard. It represents way different characters can be represented in different documents like text file, web pages etc. The Unicode supports 4 bytes for the characters. UTF-8 has become standard character encoding it supports 4 bytes for each character. There are other different Unicode encodings like UTF-16, UTF-8. Character literals in java are constant characters in java. They are expressed in single quotes ‘a’,’A, ‘1’,’!’, ‘π’, ‘$’,’©’. The data type that can store char literals is char. By using three approaches given below:
Method 1: Assigning Unicode to the char data types.
Example:
Input : a = '$' Output: $ Input : a = '~' Output: ~
Approach:
- Create a char variable.
- Store Unicode character in a variable using a single quote.
- Print variable
Below is the implementation of the above approach:
Java
// Assigning Unicode to the char data typesimport java.io.*;class GFG { public static void main(String[] args) { char c1 = 'a'; System.out.println(c1); char c2 = 'A'; System.out.println(c2); char c3 = '1'; System.out.println(c3); char c4 = '~'; System.out.println(c4); char c5 = '$'; System.out.println(c5); char c6 = '/'; System.out.println(c6); char c7 = 'π'; System.out.println(c7); }} |
a A 1 ~ $ / ?
Method 2: Assigning Unicode values to char data types
Example:
Input : a = '\u0061' Output: a Input : a = '\u002F' Output: /
Approach:
- Create a char variable.
- Store Unicode value in a variable using a single quote.
- Print variable
Below is the implementation of the above approach:
Java
// Assigning Unicode values to char data typesimport java.io.*;class GFG { public static void main(String[] args) { char c1 = '\u0061'; System.out.println(c1); char c2 = '\u0041'; System.out.println(c2); char c3 = '\u0031'; System.out.println(c3); char c4 = '\u007E'; System.out.println(c4); char c5 = '\u0024'; System.out.println(c5); char c6 = '\u002F'; System.out.println(c6); char c7 = '\u03C0'; System.out.println(c7); }} |
a A 1 ~ $ / ?
Method 3: Assigning ASCII values to char data types
Example:
Input : a = 97 Output: a Input : a = 49 Output: 1
Approach:
- Create a char variable.
- Store ASCII value in a variable using a single quote.
- Print variable
Below is the implementation of the above approach:
Java
// Assigning ASCII values to char data typesimport java.io.*;class GFG { public static void main(String[] args) { char c1 = 97; System.out.println(c1); char c2 = 65; System.out.println(c2); char c3 = 49; System.out.println(c3); char c4 = 126; System.out.println(c4); char c5 = 36; System.out.println(c5); char c6 = 47; System.out.println(c6); }} |
a A 1 ~ $ /



