How To Convert Character To Integer In Java

A character can be termed as a single letter, digit, or symbol that can be represented by a single byte of data. Characters are commonly used to represent text in a program.

While an integer is a whole number without a decimal point which in programming languages can be represented by multiple bytes of data. Integers are used for numeric operations in a program.

Why do we need to convert character to integer in java

Here are several scenarios in which we could need to convert characters to numbers in Java:

  • Program Requirement: Some programming tasks necessitate the usage of numerical values as opposed to character representations.
  • Encryption: In Java, characters are represented as numeric values using the ASCII or Unicode encoding techniques. Converting characters to integers allows us to access their underlying numeric values for a variety of applications.
  • Readability: Converting characters to integers might be beneficial when processing input data using character-based representations of numeric values.

How to convert character to integer in java

There are several approaches you can use to convert characters to integers in Java. Here are some common ones:

  • Using the (int) type cast operator
  • Using the Character.getNumericValue() method
  • Using the Integer.parseInt() method

Approaches

Approach 1: Using the (int) type cast operator

In Java, you can convert a character to an integer using the (int) type cast operator. This conversion is possible because characters are represented as numeric values in the Unicode character set. The (int) operator converts the Unicode value of the character to its corresponding integer value.

class CharToIntExample {
    public static void main(String[] args) {
        char c = '5';  // define a character variable 'c' with value '5'
        int i = (int) c;  // cast the character to an integer using (int)
        System.out.println("Character '" + c + "' converted to integer: " + i);
    }
}

Output:

Character '5' converted to integer: 53

Explanation:

  • We define a char variable ‘c’ and initialize it to the character ‘5’.
  • We use the (int) type cast operator to convert the character ‘5’ to its corresponding integer value, which is 53 according to the ASCII encoding scheme.
  • We store the resulting integer value in an int variable ‘i’.
  • We print out the original character value and the converted integer value to the console using System.out.println().
  • The output shows that the character ‘5’ was successfully converted to the integer value 53.

Approach 2: Using the Character.getNumericValue() method

Another approach for converting characters to integers is to use the Character.getNumericValue() method. This method returns the numeric value of a character, which can be useful in various scenarios, such as converting a digit character to its integer value. Unlike type casting, this method also handles non-digit characters gracefully, returning -1 for invalid inputs.

class CharToIntExample {
    public static void main(String[] args) {
        char c = '7';  // define a character variable 'c' with value '7'
        int i = Character.getNumericValue(c);  // use getNumericValue() method to convert character to integer
        System.out.println("Character '" + c + "' converted to integer: " + i);
    }
}

Output:

Character '7' converted to integer: 7

Explanation:

  • We define a char variable ‘c’ and initialize it to the character ‘7’.
  • We use the Character.getNumericValue() method to convert the character ‘7’ to its corresponding integer value, which is also 7.
  • We store the resulting integer value in an int variable ‘i’.
  • We print out the original character value and the converted integer value to the console using System.out.println().
  • The output shows that the character ‘7’ was successfully converted to the integer value 7.

Approach 3: Using the Integer.parseInt() method

We can also use the Integer.parseInt() method to convert a character to an integer in certain cases where user input needs to be converted from a character to an integer data type. This method takes a string representation of the character as an argument and returns the corresponding integer value.

class CharToIntExample {
    public static void main(String[] args) {
        char c = '9';  // define a character variable 'c' with value '9'
        int i = Integer.parseInt(Character.toString(c));  // use parseInt() method to convert character to integer
        System.out.println("Character '" + c + "' converted to integer: " + i);
    }
}

Output:

Character '9' converted to integer: 9

Explanation:

  • We define a char variable ‘c’ and initialize it to the character ‘9’.
  • We convert the character ‘9’ to a string using the Character.toString() method.
  • We use the Integer.parseInt() method to convert the string representation of the character ‘9’ to an integer value, which is also 9.
  • We store the resulting integer value in an int variable ‘i’.
  • We print out the original character value and the converted integer value to the console using System.out.println().
  • The output shows that the character ‘9’ was successfully converted to the integer value 9.

Best Approach

The (int) type cast operator is the best method to convert characters to integers in Java when we know for certain that the character represents a valid integer value. Here are some reasons why:

  • Simplicity: This approach is the simplest and can be said as the most straightforward way to convert a character to an integer. It involves using one operator and doesn’t require any additional methods or objects.
  • Efficiency: This approach is efficient since it involves only a simple conversion operation. It doesn’t require any additional object creation or method calls.
  • Reliability: This approach is reliable because it directly converts a character to an integer value without any intermediate steps. As long as we know that the character represents a valid integer value, the conversion will be accurate and error-free.

Sample Problem

Sample Problem 1:

Write a java program that converts the score gained by striking a dart to the board from a character to an integer data type. Use the (int) type cast operator method for the same.

Solution:

  • We start by importing the java.util.Scanner class, which allows us to read user input from the console.
  • We then create a Scanner object to read user input.
  • We prompt the user to enter the section hit using the System.out.print() method.
  • We read the user input as a character using the scanner.next().charAt(0) method. This reads the next token entered by the user and returns the first character of that token.
  • We convert the character sectionHit to its corresponding integer value using the (int) type cast operator. Since the ASCII value of ‘0’ is 48, we subtract this value from the ASCII value of the character to get the actual integer value.
  • We display the corresponding score using the System.out.println() method.
import java.util.Scanner;

class DartScore {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Ask the user to enter the section hit
        System.out.print("Enter the section hit: ");
        char sectionHit = scanner.next().charAt(0);
        
        // Convert the section hit to its corresponding integer value using the (int) type cast operator
        int score = (int) sectionHit - 48; // Subtract the ASCII value of '0' to get the actual integer value
        
        // Display the corresponding score
        System.out.println("Score: " + score);
    }
}

Output:

Enter the section hit: 10 14 18 17 19 23 20 22
Score: 1

Sample Problem 2:

Write a java code that converts the given letter tile in the game of scramble to its associate point value.

Solution:

  • We create a character variable letterTile and assign it the value of the letter tile whose point value we want to find.
  • We use the Character.getNumericValue() method to get the numeric value of the character. The getNumericValue() method returns the numeric value of the character in the specified radix, which in this case is 10 (decimal). For letters A through Z, the numeric values returned by this method are 10 through 35 respectively.
  • We subtract 9 from the numeric value obtained in the previous step to get the point value of the letter tile. This is because in the game of Scrabble, the point values for letters A through Z are 1 through 26 respectively.
  • We display the point value of the letter tile using the System.out.println() method.
class Scrabble {
    public static void main(String[] args) {
        char letterTile = 'A'; // replace 'A' with the actual letter tile
        
        int pointValue = Character.getNumericValue(letterTile) - 9;
        
        System.out.println("The point value of the letter tile '" + letterTile + "' is " + pointValue);
    }
}

Output:

The point value of the letter tile 'A' is 1

Sample Problem 3:

Write a java code that takes a player’s timing to finish the race and convert it into integers. Use Integer.parseInt() function method.

Solution:

  • We start by importing the java.util.Scanner class, which allows us to read user input from the console.
  • We then create a Scanner object to read user input.
  • We prompt the user to enter the time taken to complete the race using the System.out.print() method.
  • We read the user input as a string using the scanner.nextLine() method.
  • We split the string timeTakenStr into hours, minutes, and seconds using the String.split() method. This returns an array of strings, which we convert to integers using the Integer.parseInt() method.
  • We calculate the total time taken in seconds by multiplying the number of hours by 3600, the number of minutes by 60, and adding the number of seconds.
  • We display the total time taken in seconds using the System.out.println() method.
import java.util.Scanner;

class RaceTime {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Ask the user to enter the time taken to complete the race
        System.out.print("Enter the time taken to complete the race (hh:mm:ss): ");
        String timeTakenStr = scanner.nextLine();
        
        // Split the time taken into hours, minutes, and seconds
        String[] timeArr = timeTakenStr.split(":");
        int hours = Integer.parseInt(timeArr[0]);
        int minutes = Integer.parseInt(timeArr[1]);
        int seconds = Integer.parseInt(timeArr[2]);
        
        // Calculate the total time taken in seconds
        int totalTime = (hours * 3600) + (minutes * 60) + seconds;
        
        // Display the total time taken in seconds
        System.out.println("Total time taken: " + totalTime + " seconds");
    }
}

Output:

Enter the time taken to complete the race (hh:mm:ss): 18:20:59
Total time taken: 66059 seconds

Conclusion

Converting a character data type to integer in java may ease the understanding of the data in many programming applications. This operation may be accomplished by a variety of methods such as type casting, the getNumericValue() function, and the parseInt() method.

While each of these ways have their own advantages, the (int) type cast operator is the simplest and most efficient option to apply when we are certain that the character represents a valid integer value. Depending on the scenario we can use other approaches in our programs.