4 Methods to Print ASCII Value in Java

Printing ASCII values in Java refers to the process of displaying the corresponding ASCII code of a character in the console. This can be achieved using various methods like assigning a variable to an integer variable, using type-casting, and generating byte code.

Methods to Print ASCII Value in Java

Java offers a number of ways to print a character’s ASCII value. In this blog, we will explore some of these methods along with a few sample codes along with examples to help you understand the concept better as follows:

Method 1: Assigning a Variable to the int Variable

In Java, assigning a character to an int variable is one of the simplest ways to print the character’s ASCII value. To accomplish this, we can utilize implicit or automatic typecasting. The code below demonstrates this method for better understanding:

// Print ASCII Value in Java

public class GFG {

	// Main driver method
	public static void main(String[] args)
	{
		// Character whose ASCII is to be computed
		char ch = 'r';

		// Creating a new variable of type int and assigning the character value.
		int ascii = ch;

		/* Java stores the ascii value there itself*/

		// Printing the ASCII value of above character
		System.out.println("The ASCII value of " + ch
						+ " is: " + ascii);
	}
}

The explanation for the code:
The code above demonstrates an easy way to determine the ASCII value of a character in Java. As an example, the program assigns the character “r” to the variable “ch.” Next, the program implicitly typecasts the value of the character variable into its ASCII equivalent by creating the integer data type variable ‘ASCII’. Finally, using the System.out.println() method, the program prints the given character’s ASCII value.

Output:

The ASCII value of r is: 114

Get complete Java Programming Exercises and Solutions here!

Method 2: Using Type-Casting

Another way to find the ASCII value of a character is by explicitly using type-casting. Below is an example of how to do it:

// Print ASCII Value in Java

// Importing java generic libraries
import java.util.*;

public class GFG {

	// Main driver method
	public static void main(String[] args)
	{
		// Character whose ASCII is to be computed
		char ch = 'a';

		// Typecasting the character to int and printing the same
		System.out.println("The ASCII value of " + ch
						+ " is: " + (int)ch);
	}
}

Explanation of the Code:

The above Java code demonstrates one of the methods to print the ASCII value of a character.

First, the code imports the required Java utility libraries. Then, the main method actively defines a character variable ‘ch’ and initializes it with the value ‘a’.


To print the ASCII value of ‘a’, we actively typecast the character ‘ch’ into an integer and print the result to the console using the System.out.println statement.

The output of the code will be “The ASCII value of a is: 97”, as the ASCII value of ‘a’ is 97.

Output:

The ASCII value of a is: 97

Methods 1 and 2 mentioned above are both examples of typecasting. The compiler performs typecasting automatically in method 1. Method 2 typecasts the data manually, making it significantly more efficient than Method 1 because the compiler must exert less effort. The process of automatically converting types is known as implicit typecasting, while the process of converting types at the user end is known as explicit typecasting.

Method 3: Using format specifier 

Printing a character’s ASCII value is another way we can use the format specifier. As an example, look at the following code:

// Print ASCII Value in Java

// Importing format library
import java.util.Formatter;

public class ABC {

	// Main driver method
	public static void main(String[] args)
	{
		// Character whose ASCII is to compute
		char character = 'w';

		// Initializing the format specifier
		Formatter formatSpecifier = new Formatter();

		// Converting the character to integer and ASCII value is stored in the format specifier
		formatSpecifier.format("%d", (int)character);

		// Print the corresponding ASCII value
		System.out.println(
			"The ASCII value of the character ' "
			+ character + " ' is " + formatSpecifier);
	}
}

Explanation of the code:

The code actively imports the Java utility package’s Formatter library and declares a char variable named “character”. Then, the code actively initializes this variable with the character for which the ASCII value needs to be calculated.

Next, a new Formatter object is actively created to store the ASCII value of the character. The “%d” format string, which designates that an integer should be written to the output, is then used to initialize the format specifier using the format() method of the Formatter class.

Following typecasting the character variable to an integer with the (int) operator, the format() method stores the result in the format specifier object.

Finally, The println() method prints the character’s ASCII value along with a message string that provides context. Automatically converted to a string and printed in the output is the format specifier object.

Output:

The ASCII value of the character ' w ' is 119

Check out our blog on Create Objects in Java here!

Method 4: Finding the ASCII value by generating a byte

We can also generate a byte array of the character and then extract the ASCII value from it.

Here’s an example of how to do it:

// Print ASCII Value in Java

// Importing I/O library
import java.io.UnsupportedEncodingException;

public class ABCD {

	// Main driver method
	public static void main(String[] args)
	{
		// Try block to check exception
		try {

			// Character is initiated as a string
			String cha = "o";

			// An array of byte type is created by using getBytes method
			byte[] bytes = sp.getBytes("US-ASCII");

			/*This is the ASCII value of the character / present at the '0'th index of above string.*/

			// Printing the element at '0'th index of array(bytes) using charAt() method
			System.out.println("The ASCII value of "
							+ cha.charAt(0) + " is "
							+ bytes[0]);
		}

		// Catch block to handle exception
		catch (UnsupportedEncodingException e) {

			// Message printed for exception
			System.out.println("OOPs!!!UnsupportedEncodingException occurs.");
		}
	}
}

Explanation of the code:

The sample code shows how to convert a character into a byte array, print the ASCII value from the byte array, and display the ASCII value of a character in Java. The character is encoded in the ASCII encoding as an array of bytes using the getBytes() method. The code actively prints the ASCII value of the character by using the index operator to access the first element of the byte array.


The code actively utilizes a try-catch block to handle the UnsupportedEncodingException that may occur during its execution. If an exception occurs, the code actively prints an error message to handle it. With this technique, we are able to print the ASCII value of any character, whether or not that character is printable.

Output:

The ASCII value of o is 111

Also Learn How to Automorphic Number in Java, Now!

Importance of knowing ASCII value in programming

Knowing ASCII values is essential in programming for a number of reasons are as follows:

  1. Encoding and decoding: Communication protocols frequently use ASCII values to encode and decode data. Being aware of ASCII values actively improves the accuracy of data transmission and reception.
  2. String manipulation: Knowing the ASCII values when working with strings in programming can make string manipulation more effective. You could, for instance, convert a string to its ASCII value and then work with it numerically.
  3. Character analysis: In some programming tasks, you need to examine the characters in a string to determine their characteristics, such as whether they are letters, digits, or punctuation marks. You can ascertain these characteristics by using ASCII values.
  4. Compatibility: Programming languages and computer systems all support ASCII values. The compatibility of various platforms and systems can be improved by knowing the ASCII values.

Programmers should understand ASCII values to improve code effectiveness, accuracy, and compatibility. In conclusion, having the knowledge of printing ASCII values in Java is a vital skill for programmers. It proves valuable in various tasks, including data validation, encryption, and character manipulation.

In conclusion, knowing how to print ASCII values in Java is an important skill for any programmer. It can help with tasks such as data validation, encryption, and character manipulation.


We have actively crafted our blog post on ‘How to Print ASCII Value in Java’ to provide you with valuable guidance and knowledge on Java-related queries. To continue strengthening your coding abilities, browse Newtum’s website and enroll in our online courses on Java, PHP, Python, and other relevant subjects.

About The Author

Leave a Reply