English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, we will learn how to convert an integer (int) variable to a character (char) in Java.
To understand this example, you should understand the followingJava programmingTopic:
class Main { public static void main(String[] args) { //Creare variabile di tipo int int num1 = 80; int num2 = 81; //Convertire int in char //Explicit type conversion char a = (char)num1; char b = (char)num2; //Stampare il valore System.out.println(a); // P System.out.println(b); // Q } }
In the above example, we have int type variables num1 and num2. Note this line,
char a = (char)num1;
Here, we use type conversion to convert an int type variable to a char type variable. For more information, please visitConversione di tipo Java。
Please note that these int values are considered ASCII values. Therefore, we getPhas an int value80and Q has an int value of 81. This is because P and Q have the ASCII values of 80 and 81。
We can also use the forDigit() method of the Character class to convert an int type variable to a char type.
class Main { public static void main(String[] args) { //Creare variabile di tipo int int num1 = 1; int num2 = 13; //Convertire int in char //For values between 0-9 char a = Character.forDigit(num1, 10); //For values between 0-9 char b = Character.forDigit(num2, 16); //Stampare il valore System.out.println(a); // 1 System.out.println(b); // d } }
Note the expression
char a = Character.forDigit(num1, 10);
We have already used the forDigit() method, which is a method to convert a specified int value to a char value.
Here, 10 and 16 are the base values of decimal and hexadecimal numbers, respectively. That is, if the int value is between 0 and 9, we use 10 as the base value; if the int value is between 0 and 15, we use 16, and so on.
In Java, we can also convert an integer by" 0"Aggiungi a un intero per convertirlo in un carattere. Ad esempio,
class Main { public static void main(String[] args) { //Creare variabile di tipo int int num1 = 1; int num2 = 9; //Convertire int in char char a = (char)(num1 + '0'); char b = (char)(num2 + '0'); //Stampare il valore System.out.println(a); // 1 System.out.println(b); // 9 } }
Nell'esempio sopra, notate le seguenti righe:
char a = (char)(num1 + '0');
Qui, il carattere" 0"in valore ASCII 48。Convertiamo il valore 48 Sommando con num1 (ovvero 1). Il risultato è 49 Il suo valore ASCII è1。Di conseguenza, utilizzeremo il carattere '1' come output.
Attenzione:Questo si applica solo ai valori int0 a 9。