Home > Java > javaTutorial > body text

Why Does My Java Code Convert an Integer to an Unprintable Character?

Susan Sarandon
Release: 2024-11-10 03:07:02
Original
976 people have browsed it

Why Does My Java Code Convert an Integer to an Unprintable Character?

Converting Integer to Character in Java: A Comparison

Understanding character and integer conversions in Java can be tricky. Let's examine the following code snippets:

int a = 1;
char b = (char) a;
System.out.println(b);
Copy after login

Expectedly, this code should print the character '1'. However, it produces an empty output. To understand this, we need to delve deeper into the type conversion process.

The assignment char b = (char) a converts the integer a (which is the number 1) to a character. This conversion actually stores the character with the Unicode code point corresponding to the integer value. For example, the Unicode code point for '1' is 49, whereas the Unicode code point for the start-of-heading character is 1. Since the integer a is 1, it gets converted to the start-of-heading character, which is not printable.

In contrast, the following code snippet:

int a = '1';
char b = (char) a;
System.out.println(b);
Copy after login

Produces the expected output '1'. This is because the assignment int a = '1' initializes a with the ASCII value of '1' (which is 49) rather than the integer value 1.

To convert an integer to a character as intended in the first snippet, you can use the following approaches:

  • Use the Character.forDigit() method: This converts a digit between 0 and 9 to its corresponding character.

    int a = 1;
    char b = Character.forDigit(a, 10);
    System.out.println(b); // Prints '1'
    Copy after login
  • Add 48 to the integer and cast: This approach relies on the fact that the Unicode code points for digits are 48 higher than the digit values.

    int a = 1;
    char b = (char) (a + 48);
    System.out.println(b); // Prints '1'
    Copy after login
  • Use the Character.toChars() method: This converts a Unicode code point to its corresponding character array.

    int a = 1;
    char[] b = Character.toChars(a);
    System.out.println(b[0]); // Prints '1'
    Copy after login

The above is the detailed content of Why Does My Java Code Convert an Integer to an Unprintable Character?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!