Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are we allowed to assign char to a int in java? [duplicate]

Tags:

java

Possible Duplicate:
char and int in Java

AsicII table :http://www.asciitable.com

The code below print out the Dec value of the corresponding char, for example "123" -> 49 50 51

 public void foo(String str)
        {
            for(int x = 0; x < str.length(); x++)
            {
                int temp = str.charAt(x);
                System.out.println(temp);
            }
        }

But I notice java is a strong type language, which mean every thing has to be cast in compile time, but how come the code knows how and when to convert char into the correct Dec value in AsicII table? Did I mess up any of the java/programming fundamental?

like image 301
user1701840 Avatar asked Jan 15 '13 17:01

user1701840


People also ask

Can we assign char to 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.

Is it legal to assign an int to a char variable?

The character is only a representation of an integer value. For example, '0' can be written as 0x30 or 48 , 'a' is an alternative for 0x61 or 97 , etc. So the assignment is perfectly valid.

Why do we use char in Java?

The char keyword is a data type that is used to store a single character.

Can char be assigned a number?

You can assign a single Char in a Text or Code variable to a Char variable, as shown in the second line of the following code example. You can assign a numeric value to a Char variable, as shown in the third line of the following code example.

What happens when we add char and int in Java?

If we direct assign char variable to int, it will return ASCII value of given character. If char variable contains int value, we can get the int value by calling Character. getNumericValue(char) method. Alternatively, we can use String.


1 Answers

A char is simply an unsigned 16-bit number, so since it's basically a subset of the int type, the JVM can cast it without any ambiguity.

like image 137
mprivat Avatar answered Nov 14 '22 23:11

mprivat