Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do chars have intrinsic int values in Java?

Tags:

java

char

int

Why does this code print 97? I have not previously assigned 97 to 'a' anywhere else in my code.

public static void permutations(int n) {
    System.out.print('a' + 0);
}
like image 861
Rachel Avatar asked Dec 30 '14 00:12

Rachel


People also ask

Can a char hold an int in Java?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

Do chars have int values?

In Java, char can be converted to int value using the following methods: Implicit type casting ( getting ASCII values ) Character. getNumericValue()

Can a char hold an int?

char cant hold what integers can. Not everything. At least not in the way you assign a value to a char .

Is char an integer type in Java?

char in java is defined to be a UTF-16 character, which means it is a 2 byte value somewhere between 0 and 65535. This can be easily interpreted as an integer (the math concept, not int ). char in c is defined to be a 1 byte character somewhere between 0 and 255.


1 Answers

a is of type char and chars can be implicitly converted to int. a is represented by 97 as this is the codepoint of small latin letter a.

System.out.println('a'); // this will print out "a"

// If we cast it explicitly:
System.out.println((int)'a'); // this will print out "97"

// Here the cast is implicit:
System.out.println('a' + 0); // this will print out "97"

The first call calls println(char), and the other calls are to println(int).

Related: In what encoding is a Java char stored in?

like image 59
Sebi Avatar answered Sep 19 '22 01:09

Sebi