Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Literals

 
Sarath Koiloth Ramath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,

I have a doubt basic regarding the literals,As char is 16 bit.I found in K&B book that char c=(int)700000 is a valid statement.How it is working,and is it storing as a character or as an interger.

I know its a very basic question.


Thank You
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As per i know, char are stored as 16 bit unsigned integer. So int from 0 to 2(raise to power 16) -1, can be assigned to a char as it is. Apart from that you need to cast explicitly.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As a 32-bit int, 70000 is...

0000 0000 0000 1010 1010 1110 0110 0000

When this value is cast to type char, only the rightmost 16 bits are preserved...

1010 1110 0110 0000

In hex, this is AE60. Consulting with Unicode.org, you will find that this value represents a Hangul Syllable.

More than likely, the environment in which you're running Java (for example, a command prompt application) will not know how to display this value as a Unicode character, so you might see something like a question mark displayed instead.
 
Sarath Koiloth Ramath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your valuable replies.
 
venu surampudi
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interesting but i could not get it to run. I get the following exception

Main.java:102: possible loss of precision

and i also think this is kind of understantable as we are trying to stuff a 32 bit thing ( for lack of vocabulary ) into a 16 bit thing

am is missing something? clearly i am
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by venu surampudi:
...am is missing something? clearly i am

I think there was a typo in the original post. The literal 700000 is already an int, so the cast should be to type char instead of int...

char c = (char)700000;
 
Dean Jones
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It prints a question mark since it is outside the range of char.(0-255)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic