wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Java char data type problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java char data type problem" Watch "Java char data type problem" New topic
Author

Java char data type problem

Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19719
    
  20

Welcome to the Ranch!

A char can store exactly one character. "12" is not one but two characters - '1' and '2'. That means it cannot fit into a char. It does fit into a String, which uses double quotes: "12".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Welcome again

I have added code tags to your post and you can see how much better it looks

People think that a char stores a character, but it doesn't really. It stores an (unsigned) integer between 0 and 0xffff (=65335, I think). As Rob has already told you, you can't store "12", but you can store 12.Note you need to cast the int 12 to a char, otherwise it won't fit into the available memory. You have already seen you can dispense with the cast if you declare and initialise the char on the same line.
I am not sure what you get when you print 12 out; the character is called 000c (c in hex = 12 in decimal), and you can find out what it is from this Unicode chart.
Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
Rob Spoor wrote:Welcome to the Ranch!

A char can store exactly one character. "12" is not one but two characters - '1' and '2'. That means it cannot fit into a char. It does fit into a String, which uses double quotes: "12".


Thanks for the reply.....Now i understood my mistake
Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
Campbell Ritchie wrote:Welcome again

I have added code tags to your post and you can see how much better it looks

People think that a char stores a character, but it doesn't really. It stores an (unsigned) integer between 0 and 0xffff (=65335, I think). As Rob has already told you, you can't store "12", but you can store 12.Note you need to cast the int 12 to a char, otherwise it won't fit into the available memory. You have already seen you can dispense with the cast if you declare and initialise the char on the same line.
I am not sure what you get when you print 12 out; the character is called 000c (c in hex = 12 in decimal), and you can find out what it is from this Unicode chart.


Thanks for the reply.....Now i understood my mistake.Thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java char data type problem