top

Search

Java Tutorial

.

UpGrad

Java Tutorial

int to char in Java

Introduction

int is a primitive data type in Java. It is used to store whole numbers. It can be both positive and negative within a specific range. It typically occupies 32 bits of memory.

On the other hand, char is another primitive data type in Java that represents a single character. It uses the Unicode character set and occupies 16 bits of memory.

Converting an int to char in Java is to obtain the corresponding character based on the ASCII or Unicode value. This conversion allows for character manipulation and processing, such as performing character-based operations or converting numerical representations to their character equivalents. It provides flexibility in dealing with textual data and enables developers to work with individual characters within a string or other data structures.

Overview

We will deal with several aspects in this tutorial. Concepts such as Java typecasting, what a string is in Java, why a string is used, and several examples of converting int to char in Java have been thoroughly discussed. Read on to learn more.

Example: Java Program To Convert int to char Using Typecasting

public class upGradTutorials {
    public static void main(String[] args) {
        int num = 65;
        char ch = (char) num;

        System.out.println("Integer: " + num);
        System.out.println("Character: " + ch);
    }
}

In this example, an integer variable num is assigned with the value 65. We want to convert this integer to its corresponding character value. To perform the typecasting, we use the syntax (char) num, where (char) is the typecast operator. It tells the compiler to convert the integer value to a character.

We assign the result of the typecasting to the char variable ch. Now, ch will hold the character value corresponding to the integer value 65. We then print the original integer and character values using the System.out.println() statement.

Using Typecasting in Java

Typecasting in Java is the process of converting a value of one data type to another data type. It allows us to use a value of one type as if it were another. However, it is also essential to remember that typecasting may result in a loss of precision or information if the conversion involves incompatible types or a narrowing conversion. Therefore, it should be used carefully, ensuring that the casted value is within the valid range for the target data type.

There are two types of typecasting in Java, they are:

  • Explicit Typecasting: Explicit typecasting (downcasting) converts a larger data type into a smaller one. It is done by manually specifying the target type in parentheses before the value is cast.

Syntax:

double num1 = 3.14;
int num2 = (int) num1;

In the above example, we have a double value, num1, and want to convert it to an integer. By using explicit typecasting (int), we can assign the truncated value of num1 to the integer variable num2.

  • Implicit Typecasting: Implicit typecasting (upcasting) converts a smaller data type to a larger one. It is done automatically by the Java compiler without the need for any explicit typecast operator.

Syntax:

int num1 = 5;
double num2 = num1;

In the above example, we have an integer value num1 and want to assign it to a double variable num2. Since double is a larger data type than int, the compiler performs the implicit typecasting, converting the int value to a double.

Example: int to char by Using toString() 

public class upGradTutorials {
    public static void main(String[] args) {
        int number = 42;
        String numberString = Integer.toString(number);
        System.out.println("Number as String: " + numberString);

        double value = 3.14;
        String valueString = Double.toString(value);
        System.out.println("Value as String: " + valueString);

        boolean flag = true;
        String flagString = Boolean.toString(flag);
        System.out.println("Flag as String: " + flagString);
    }
}

We start by declaring an int variable number with a value of 42. To convert this int to a String, we use the Integer.toString() method and assign the result to the numberString variable. Finally, we print the converted String using the System.out.println() statement.

Similarly, we declare a double variable value with a value of 3.14. To convert this double to a String, we use the Double.toString() method and assign the result to the valueString variable. We then print the converted String using the System.out.println() statement.

Finally, we declare a boolean variable flag with a value of true. To convert this boolean to a String, we use the Boolean.toString() method and assign the result to the flagString variable. We again print the converted String using the System.out.println() statement.

Using the toString() Method in Java

The toString() method in Java converts an object to its string representation. It is defined in the Object class, which is the root class for all classes in Java. All classes inherit the toString() method from the Object class by default.

When applied to primitive data types, such as inttoString() converts the value to a string representation.

Example: int to char by Using forDigit()

public class upGradTutorials {
    public static void main(String[] args) {
        int number = 12;
        int radix = 16; // Hexadecimal

        char digit = Character.forDigit(number, radix);
        System.out.println("Digit as char: " + digit);
    }
}

In this example, we have an integer variable number with a value of 12, and we want to convert it to its corresponding character representation using a hexadecimal radix.

We use the Character.forDigit() method to convert the integer to a character. The first argument is the integer value we want to convert, which is number. The second argument is the radix, which represents the number system used. We use 16 as the radix to represent hexadecimal numbers in our example.

The forDigit() method returns the character representation of the given digit. In our case, since the radix is 16, the value of number is within the range of valid hexadecimal digits (0-15), so it will return the corresponding character. In this example, the output will be 'C', the character representation of 12 in hexadecimal.

Finally, we print the converted character using the System.out.println() statement.

Using forDigit() Method in Java: Another Example

public class upGradTutorials {
    public static void main(String[] args) {
        int number = 9;

        char binaryDigit = Character.forDigit(number, 2);
        System.out.println("Binary Digit: " + binaryDigit);

        char octalDigit = Character.forDigit(number, 8);
        System.out.println("Octal Digit: " + octalDigit);

        char decimalDigit = Character.forDigit(number, 10);
        System.out.println("Decimal Digit: " + decimalDigit);

        char hexadecimalDigit = Character.forDigit(number, 16);
        System.out.println("Hexadecimal Digit: " + hexadecimalDigit);
    }
}

In this example, we have an integer variable number with a value of 9, and we want to convert it to its corresponding character representation using different radix values.

We use the Character.forDigit() method to perform the conversion. The first argument is the number we want to convert (number), and the second is the radix, which determines the number system for the conversion.

For binary representation, we use a radix of 2. The forDigit() method will convert the number 9 to its binary representation, '1001'. The output will be '1'.

For octal representation, we use a radix of 8. The forDigit() method will convert 9 to its octal representation, '11'. The output will be '1'.

For decimal representation, we use a radix of 10. Since the radix is the same as the number system we commonly use, the forDigit() method will return the corresponding character for the given number. In this case, the output will be '9'.

For hexadecimal representation, we use a radix of 16. The forDigit() method will convert 9 to its hexadecimal representation, '9'. The output will be '9'.

Example: int to char by Adding ‘0’

public class upGradTutorials {
    public static void main(String[] args) {
        int number = 5;

        char convertedChar = (char) (number + '0');
        System.out.println("Converted Character: " + convertedChar);
    }
}

In this example, we have an integer variable number with a value of 5, and we want to convert it to its corresponding character representation.

We use typecasting and add the character '0' to the integer value to achieve this. In Java, characters are internally represented using Unicode values, and the character '0' has a Unicode value of 48. By adding '0' to the integer, we get the Unicode value of the corresponding digit character.

In the code, (char) (number + '0') adds the integer number with the Unicode value of '0'. The result is then cast to a char type representing the corresponding character.

In this case, the integer 5 is added to the Unicode value of '0' (48), resulting in 53. The character with the Unicode value 53 represents the digit '5'.

Java Programs for int to char Conversion 

Method 1: Using Switch Case

public class upGradTutorials {
    public static void main(String[] args) {
        int number = 5;
        char convertedChar = '\0';

        switch (number) {
            case 0:
                convertedChar = '0';
                break;
            case 1:
                convertedChar = '1';
                break;
            case 2:
                convertedChar = '2';
                break;
            // Add more cases for remaining digits 3 to 9 if needed

            default:
                System.out.println("Invalid number!");
        }

        if (convertedChar != '\0') {
            System.out.println("Converted Character: " + convertedChar);
        }
    }
}

In this example, we use a switch statement to map each digit int value to its corresponding character representation. We provide cases for each digit from 0 to 9 and assign the appropriate character to the convertedChar variable.

Method 2: Using Concept of Type-Casting

public class upGradTutorials {
    public static void main(String[] args) {
        int number = 5;
        char convertedChar = (char) (number + '0');
        System.out.println("Converted Character: " + convertedChar);
    }
}

This method uses type-casting to convert the int value to a char. By adding the integer number to the Unicode value of '0', we obtain the Unicode value of the corresponding digit character. The resulting value is then cast to a char type.

Method 3: Using Modulo Operator

public class IntToCharModuloExample {
    public static void main(String[] args) {
        int number = 5;
        char convertedChar = (char) ('0' + number % 10);
        System.out.println("Converted Character: " + convertedChar);
    }
}

This method uses the modulo operator % to extract the least significant digit from the number. We obtain the corresponding digit character by adding this digit to the Unicode value of '0'.

Method 4: Using String Array and Indexing

public class upGradTutorials {
    public static void main(String[] args) {
        int number = 5;
        String[] digits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        char convertedChar = digits[number].charAt(0);
        System.out.println("Converted Character: " + convertedChar);
    }
}

This method uses a String array to store the character representations of the digits from 0 to 9. We access the corresponding String value using the number as the index and then retrieve the first character of that String using the charAt(0) method.

Conclusion 

There are many ways to convert int to char in Java. You can consider enrolling in a professional Java course if you want to learn Java. Several learning platforms help students gain in-depth insight into Java. upGrad, for instance, has several well-curated courses for professionals and freshers to excel in their respective fields. 

FAQs

1. Can you assign a char to an int in Java?

Yes, you can assign a char value to an int variable in Java because char is implicitly convertible to int. The int variable will store the Unicode value of the corresponding character.

2. How to take char as input after an integer in Java?

You can use a combination of Scanner class methods to take a char as input after an int in Java. First, read the int using nextInt(), then read the char using next().charAt(0) to capture the first character entered by the user.

3. Can we convert a char array to String in Java?

Yes, we can convert a char array to a String in Java. We can do this using the constructor of the String class. We need to pass the char array as an argument to the constructor. It will create a String object with the characters from the array.

Leave a Reply

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