Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char to Int Conversion Java

public static void main (String[] args)
{
    char x = 'x';
    char w = x-1;
    System.out.println(w);
}

Whenever I try to run the following code, I got a loss of precision. The compiler tells me that the line char w = x-1 doesn't seem to work. How can I make the char value equal w?

like image 968
idude Avatar asked Jul 11 '26 14:07

idude


1 Answers

You need to re-cast to char as you converted to int

char x = 'x';
char w = (char)(x - 1);
System.out.println(w);

That will output w.

like image 125
Jean-François Savard Avatar answered Jul 14 '26 03:07

Jean-François Savard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!