Hi,have a look at the code: Which of the following will compile without error?
1) char c='1'; System.out.println(c>>1); 2) Integer i=Integer("1"); System.out.println(i>>1); 3) int i=1; System.out.println(i<<<1); 4) int i=1; System.out.println(i<<1); the Ans;1,4.i cant understand why it is 1 since 1 is treated as Character. Thanks!
Carl Trusiak
Sheriff
Joined: Jun 13, 2000
Posts: 3340
posted
0
Originally posted by avn: Hi,have a look at the code: Which of the following will compile without error?
1) char c='1'; System.out.println(c>>1); 2) Integer i=Integer("1"); System.out.println(i>>1); 3) int i=1; System.out.println(i<<<1); 4) int i=1; System.out.println(i<<1); the Ans;1,4.i cant understand why it is 1 since 1 is treated as Character. Thanks!
The char data type is a numeric data type. By assigning '1' to a char data type, you actually assign the unicode value that represents '1' on the platform you are on. Java allows and does implicate casting of char data type to an int data type when necessary. In the above, the char value of '1' is \u0031 or 49 so this gets auto promted to an int with the value of 49.