• Post Reply Bookmark Topic Watch Topic
  • New Topic

Bit operators

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gravity is a harsh mistress. But this tiny ad is pretty easy to deal with:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!