2

Of course I'm a beginner for Java, previously I learned C. Please take a look on the following code segments.

char Character;
int Number = 27;
Character = Number;
System.out.println(Character);

The above code cannot be compiled as an error stated as “Loss of Information”

Whereas the following code...

char Character = ‘F’;
int Number;
Number = Character;
System.out.println(Number);`

The above code can be compiled but the output is “70”... not as “F”

Also take a look on the following code...

char [] arrayCh = new char [3];
arrayCh [0] = 27;
System.out.println(arrayCh[0]);

The above code can be compiled however it also gives an unfamiliar symbol...

I know the issues regarding the ASCII Values and the memory taking as 'char' takes 16 Bits, 'int' takes 32 Bits. Therefore an integer value couldn’t be assigned in to a character variable whereas a character value can be assigned in to an integer variable as "ASCII" value.

My question is... why a 'char' array accepts 'int' values..? Could anyone explain?

3
  • 1
    70 is the ASCII code of the character F Commented Aug 2, 2015 at 19:31
  • 1
    Constant expressions. Commented Aug 2, 2015 at 19:32
  • 1
    you can use casting: Character = (char)Number; Commented Aug 2, 2015 at 19:35

1 Answer 1

5

A char is a 2-bytes long, unsigned integer. 27 is an integer literal that is in the range of a char, so the compiler accepts to let you assign it to a char.

'F' is a character literal that represents the character F, which has the decimal value 70 in the unicode standard. So, assigning 'F' to an integer is the same thing as assigning 70.

Sign up to request clarification or add additional context in comments.

3 Comments

I knew it friend... Take a look on the last code snippet... A 'char' array accepts an integer value as the array element. How it is possible? Or Is this the behavior of Arrays in Java?
It doesn't have anything to do with arrays. Doing char c = 27; would work as well. As my answer explains: 27 is an integer literal that is in the range of a char, so the compiler accepts to let you assign it to a char. A char is an unsigned positive integer on two bytes. 27 is also an positive integer that fits in two bytes, so the compiler accepts the conversion: you're not losing information.
You stated the phrase "range of a char"... This made me clear enough..! I assigned a negative integer to that char then the compiler hasn't accepted..! Nothing coupled with arrays..! Thank You Friend..!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.