• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java char data type problem

 
Rameshwar Soni
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
Campbell Ritchie
Sheriff
Pie
Posts: 50278
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic