Bhavesh
Bhavesh

Reputation: 4677

The char type in Java behaves somewhat in a strange way?

Let's consider the following simple expressions in Java.

char c='A';
int i=c+1;

System.out.println("i = "+i);

This is perfectly valid in Java and returns 66, the corresponding value of the character (Unicode) of c+1.


String temp="";
temp+=c;
System.out.println("temp = "+temp);

This is too valid in Java and the String type variable temp automatically accepts c of type char and produces temp=A on the console.


All the following statements are also surprisingly valid in Java!

Integer intType=new Integer(c);
System.out.println("temp = "+intType);

Double  doubleType=new Double(c);
System.out.println("temp = "+doubleType);

Float floatType=new Float(c);
System.out.println("temp = "+floatType);

BigDecimal decimalType=new BigDecimal(c);
System.out.println("temp = "+decimalType);

Although c is a type of char, it can be supplied with no error in the respective constructors and all of the above statements are treated as valid statements. They produce the following outputs respectively.

temp = 65
temp = 65.0
temp = 65.0
temp = 65

In such a scenario, what is the internal behavior of the char type available in Java?

Upvotes: 3

Views: 248

Answers (3)

Crollster
Crollster

Reputation: 2771

The primitives char and byte are interchangeable (which refers to the Unicode table values) - so yes, char variables can be treated as numerics, just as byte can.

Edit: Further to Henery's comment below, you are right of course, Java does use unicode to represent character content (original text updated to reflect this) - but as we know, the first 127 ASCII and Unicode chars more or less match, and so any manipulation performed within the character range 0..127 would be the same for both ASCII and Unicode, meaning that converting between the two are trivial.

The old-timers amongst us were probably taught and remember most of the ASCII table, rather than the Unicode table, and indeed I still keep a ASCII crib sheet in my desk for quick referal. Oh, and +1 for Henery's comment, for making me actually clarify what I wrote.

Upvotes: 0

Norman
Norman

Reputation: 453

char is sort of like a 16-bit int. You can concatenate integers other things onto Strings. It's a shortcut for Character.toString(c).

You can use the Character object if you wish to avoid such confusion.

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Char is a primitive numeric integral type and as such is subject to all the rules of these beasts including conversions and promotions. You'll want to read up on this, and the JLS is one of the best sources for this: Conversions and Promotions. In particular, read the short bit on "5.1.2 Widening Primitive Conversion".

Upvotes: 8

Related Questions