devxlogo

How do I get Java to return the ASCII value of a character?

How do I get Java to return the ASCII value of a character?

Question:
How do I get Java to return the ASCII value of a character?

Answer:
Java characters are encoded using Unicodes, two-byte codes that enable coding of non-Roman characters. Fortunately, Unicodes for Roman characters have the form 0x00yz where yz is the usual ASCII code.

Second, due to Java’s stricter typing discipline, the char typeis distinct from the numeric types, hence an explicit cast is requiredto convert a char to an int.

Here’s a sample program that allows users to inspect the ASCIIcodes of characters contained in a command line argument:

public class CharTest {   public static void main(String[] args) {      int len = args[0].length();      for(int i = 0; i < len; i++) {         char next = args[0].charAt(i);         System.out.println("Unicode for " + next + " = " + (short)next);      }   }}

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist