How to Convert a Number to a Letter in Java

Save

In the Java programming language, both numbers and letters are considered primitive data types, which are the basic data types built into the language itself. Whole numbers can be represented as one of these numeric types: byte, short or int. The choice of which numeric type is suitable is determined by the expected minimum and maximum range of values to be stored. In contrast, letters are typically represented as only the char type, which can hold a single Unicode character. Java programmers often need to convert a number to a letter for further processing in the application.

  • Declare the appropriate variable to hold the number value. Typically Java programmers would often use the int primitive type because it has the largest range of values. The following example shows the declaration and initialization of an integer variable called a with value 65:

    int a = 65;

  • Declare the appropriate variable to hold the letter value. Java programmers often use the char primitive type for this purpose. The following example shows the declaration and initialization of a character variable called myChar with an empty value:

    char myChar = ''

  • Convert the number into a letter. This is accomplished through an operation called casting, which converts one primitive type into another. The following example shows how the integer variable a is converted into the corresponding ASCII letter A in the myChar variable:

    myChar = (char) a; // cast from int to char

    Letters which are represented as the ASCII character set can include 128 possible upper and lower case letters and other numeric and punctuation symbols.

  • Verify that the number has been successfully converted to a letter. The following command is used to display the value of the letter variable into the console for manual verification by the Java programmer.

    "System.out.println ("Char - " + myChar);"

    Ensure that the words "Char - A" is printed on the console as proof of successful conversion from number to letter.

References

  • Photo Credit Ryan McVay/Photodisc/Getty Images
Promoted By Zergnet

Comments

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!