6

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?

Community
  • 1
  • 1
user1701840
  • 1,062
  • 3
  • 19
  • 27

3 Answers3

8

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.

mprivat
  • 21,582
  • 4
  • 54
  • 64
  • Hmm, that logic would make you think you could perform the cast without changing the representation value... thus '1' would cast to '1' not 49 or whatever it does. – BlackVegetable Jan 15 '13 at 17:14
  • Representation and value aren't the same thing. Two things can have the same value (i.e. 49), but a different representation '1' for char, and 49 for int. Dunno if I'm confusing you even more... sorry.. – mprivat Jan 15 '13 at 17:20
  • Nah, you are correct. I used the wrong terms. I suppose it could either cast it as it does, or it would have to disallow all int->char casts as only 0->9 would make sense. – BlackVegetable Jan 15 '13 at 17:22
3

Java was made based in C, and thats a feature of C: chars represent a number as well

As Scalar Types, though, there's a catch: - printing a char will yield the ascii char - printing an int will yield the number

there are also some details about upcast and downcast (the int to be converted into a char, needs to be done explictly, as there is some truncation involved)

Example:

long a = 1L; // a real long
long n = 5; // int, cast to long
int x = n;  // (will raise an error)
int z = (int) n; // works fine
aldrinleal
  • 3,559
  • 26
  • 33
2

char has a dual personality.

It is a 16 bit unsigned integer numeric type, which makes assignment to int a very natural operation, involving widening primitive conversion, one of the conversions that the compiler will insert if needed without requiring an explicit cast.

It is also the way characters are represented for I/O and String operations.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75