Yogesh Verma
Yogesh Verma

Reputation: 59

during cast of a char value in java question mark is printed on console

In the following program, can't char primitive neglect the _ve sign during casting of the int value...

public class CharConsole {

    public static void main(String[] er) {
        char a = (char) 65;
        char b = (char) -65;
        char c = (char) 98;
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}

Upvotes: 1

Views: 2428

Answers (3)

Nirbhay Mishra
Nirbhay Mishra

Reputation: 1648

It depends on what "convert an int to char".

If you simply want to cast the value in the int, you can cast it using Java's typecast notation:

int i = 97; // 97 is 'a' in ASCII
char c = (char) i; // c is now 'a'

but -ve is not any ASCII char value and does not represent any char

we can cast back

char b=(char)-65;
int i = (int)b;

print I it will be 65471

Upvotes: 0

Filip
Filip

Reputation: 877

What do expect here? The character int values map to character encoding table. There is no negative table mapping. It will always display a question mark as the requested character code is out of the encoding table range...

Upvotes: 0

assylias
assylias

Reputation: 328873

A char can't be negative, so when you write:

char b = (char) -65;

you have an overflow and the actual value is 65,536 - 65. You can verify it with

System.out.println((int) b);

which prints: 65471

That character is probably not handled by your console and could appear as a blank or a square for example.

Upvotes: 4

Related Questions