Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Calculating the ASCII Value of a Character in Java

Last Updated on May 17, 2023 by Prepbytes

ASCII is an acronym that stands for American Standard Code for Information Interchange. In ASCII, different characters and symbols are assigned a specific numerical value for computers to store and manipulate. While storing and manipulating, the electronic device always works with the binary value of the ASCII number assigned. Because it is impossible to do so in its original form. ASCII assigns letters, numbers, characters, and symbols to one of the 256 available slots in the 8-bit code.

For Example

Character ASCII Value
a 97
b 98
A 65
B 66

Methods to Calculate the ASCII Value of a Character in Java

There are four ways to print the ASCII value or code of a specific character, which are detailed below, followed by a Java example for implementation.

  1. Method of brute force
  2. Method of type-casting
  3. Method of using the format specifier
  4. Method for Using the Byte Class

Calculating the ASCII Value of a Character using Brute Force Method

  1. Create a class called "Prep."
  2. Define the main method, which accepts an array of strings called ‘args’ as input.
  3. Declare a variable ‘ch’ of type ‘char’ and assign it the character ”.
  4. Declare an ‘ascii’ variable of type ‘int’.
  5. Use the implicit conversion from ‘char’ to ‘int’ to assign the ASCII value of the character ‘ch’ to the variable ‘ascii’.
  6. Display the message "The ASCII value of [character] is: [ascii]," where [character] is the value of ‘ch’ and [ascii] is the value of ‘ascii’.
  7. Complete the main method.
  8. Complete the class definition.

Code Implementation

class Prep {
    public static void main(String[] args)
    {
        char ch = '}';
        int ascii = ch;
        System.out.println("The ASCII value of " + ch + " is: " + ascii);
    }
}

Output

The ASCII value of } is: 125

Calculating the ASCII Value of a Character using Type Casting Method

  1. Add the ‘java.util’ package to your project.
  2. Create a class called "Prep."
  3. Create the main method, which accepts an array of strings ‘args’ as input.
  4. Declare a variable ‘ch’ of type ‘char’ and assign it the character ”.
  5. Make a copy of the message. "[character]’s ASCII value is: [ASCII value]," where [character] is the value of ‘ch’ and [ASCII value] is the casted value of ‘ch’ to an integer using ‘(int)ch’.
  6. Close the main method.
  7. Put an end to the class definition.

Code Implementation

import java.util.*;
class Prep {
    public static void main(String[] args)
    {
        char ch = '}';
        System.out.println("The ASCII value of " + ch + " is: " + (int)ch);
    }
}

Output

The ASCII value of } is: 125

Calculating the ASCII Value of a Character using Format Specifier

  1. Import the java.util.Formatter package.
  2. Define a class named "Prep".
  3. Define the main method that takes an array of strings args as input.
  4. Declare a variable character of type char and assign it a character, in this case, }.
  5. Create a new instance of the Formatter class named formatSpecifier.
  6. Use the format method of the Formatter class to format the ASCII value of the character as a decimal integer. Pass the format specifier %d and the casted value (int)character as arguments.
  7. Print the message "The ASCII value of the character [character] is [formatted value]" where [character] represents the value of character and [formatted value] represents the result of the formatting obtained from the formatSpecifier.
  8. End the main method.
  9. End the class definition.

Code Implementation

import java.util.Formatter;
class Prep {
    public static void main(String[] args)
    {
        char character = '}';
        Formatter formatSpecifier = new Formatter();
        formatSpecifier.format("%d", (int)character);
        System.out.println("The ASCII value of the character"+ character + " is " + formatSpecifier);
    }
}

Output

The ASCII value of the character } is: 125

Calculating the ASCII Value of a Character using Byte Class

  1. Import the java.io.UnsupportedEncodingException package.
  2. Define a class named "Prep".
  3. Define the main method that takes an array of strings args as input.
  4. Begin a try-catch block to handle the UnsupportedEncodingException.
  5. Inside the try block:
    • Declare a variable sp of type String and assign it a single character, in this case, }.
    • Declare a byte array bytes to store the ASCII value of the character.
    • Use the getBytes method of the String class to convert the sp string to a byte array using the "US-ASCII" encoding.
    • Print the message "The ASCII value of [character] is [ASCII value]" where [character] represents the character obtained from sp.charAt(0) and [ASCII value] represents the value of the first element of the bytes array.
  6. In the catch block, handle the UnsupportedEncodingException by printing the message "OOPs!!! UnsupportedEncodingException occurs."
  7. End the main method.
  8. End the class definition.

Code Implementation

import java.io.UnsupportedEncodingException;
public class Prep {

    public static void main(String[] args)
    {
        try {
            String sp = "}";
            byte[] bytes = sp.getBytes("US-ASCII");
            System.out.println("The ASCII value of "+ sp.charAt(0) + " is "+ bytes[0]);
        }
        catch (UnsupportedEncodingException e) {
            System.out.println("OOPs!!!UnsupportedEncodingException occurs.");
        }
    }
}

Output

The ASCII value of } is: 125 

Conclusion
In summary, ASCII is a standard for character encoding that assigns numerical values to characters and symbols. There are several methods available in Java to determine the ASCII value of a character, including brute force, type casting, format specifier, and the Byte class method. These methods provide various approaches to obtaining the ASCII value based on the program’s specific requirements.

Frequently Asked Questions (FAQs)

Q1. What is the ASCII value of A to Z in Java?
Ans. In Java, the char variable stores the ASCII value of a character (a number between 0 and 127) rather than the character itself. ASCII values for lowercase alphabets range from 97 to 122. Uppercase alphabets have ASCII values ranging from 65 to 90. That is, the letter a is represented by 97, while the letter z is represented by 122.

Q2. In Java, how do you convert an ASCII value to a character in a string?
Ans. Use the toString() method to convert ASCII to string. This method returns the associated character.

Q3. In JavaScript, how do you find the ASCII value of a character in a string?
Ans. Using the charCodeAt() Method to Determine the ASCII Value of a Character: The charCodeAt() method in JavaScript returns the Unicode value of a character at the specified index in a string.

Q4. In Java, how do you check if a string contains ASCII characters?
Ans. isAsciiPrintable() is a static method of the StringUtils class that determines whether a given string contains only printable ASCII characters. If the input string is null, the method returns false.

Leave a Reply

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