Convert Integer To Char in Java

Convert Integer To Char in Java | In Java, primitive int and char data types are compatible with each other. We can easily convert int to char and char to int value through type casting.

The Integer is a wrapper class that wraps the primitive int value into the Object. The char primitive and Integer object is incompatible with each other and we can’t directly convert the Integer object to a char primitive value. But since int primitive and char primitive are compatible with each other therefore we have to convert Integer to int primitive value.

With the help of autoboxing, we can easily convert an int primitive to an Integer object, and with the help of auto unboxing, we can easily convert an Integer object to an int primitive value.

Let us see how to convert Integer to char in Java.

public class Main {
    public static void main(String args[]) {
        Integer num = 65;
        System.out.println("Num: " + num);
        System.out.println("Class: " + num.getClass().getName());

        // autounboxing
        int val = num;
        // convert int to char
        char ch = (char) val;

        System.out.println("Char value: " + ch);
    }
}

Output:-

Num: 65
Class: java.lang.Integer
Char value: A

public class Main {
    public static void main(String args[]) {
        Integer num = 100;
        System.out.println("Num: " + num);
        System.out.println("Class: " + num.getClass().getName());

        // autounboxing
        int val = num;
        // convert int to char
        char ch = (char) val;

        System.out.println("Char value: " + ch);
    }
}

Output:-

Num: 100
Class: java.lang.Integer
Char value: d

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *