Type casting:
- Conversion of data from one data type to another data type.
- Type casting classified into
- Implicit cast: Auto conversion of data from one type to another type.
- Explicit cast: Manual conversion of data from one type to another type.
Convert Character to Integer: this conversion happens implicitly when we assign character to integer type.
class Code { public static void main(String[] args) { char ch = ‘A’ ; int x = ch ; System.out.println(“x value : ” + x); } } |
Convert Integer to Character: this conversion must be done manually
class Code { public static void main(String[] args) { int x = 97 ; char ch = (char)x ; System.out.println(“ch value : “+ch); } } |
Convert Upper case to Lower case Character:
Lower Case to Upper Case | Upper Case to Lower Case |
A(65) + 32 -> a(97) B(66) + 32 -> b(98) … … Z(90) + 32 -> z(122) | a(97) – 32 -> A(65) b(98) – 32 -> B(66) … … z(122) – 32 -> Z(90) |
Conversion Code:
class Code { public static void main(String[] args) { char up = ‘A’; char lw = (char)(up+32); System.out.println(“Result : ” + lw); } } |
Convert Digit to Number: We can convert character type digit into number as follows
Digit to Number: |
‘0’ – 48 -> 48-48 -> 0 ‘1’ – 48 -> 49-48 -> 1 .. .. ‘9’ – 48 -> 57-9 -> 9 |
Conversion Code:
class Code { public static void main(String[] args) { char d = ‘5’; int n = d-48; System.out.println(“Result : ” + n); } } |