Convert hex integer to character using explicit type conversion?

I encoded the following, but o / p is not expected? Will someone tell me?

Question: Write an example program to declare a hex integer and hide it in a character using explicit type conversion?

class hexa { public static void main(String ar[]) { int hex=0xA; System.out.println(((char)hex)); } } 

tell me: why is there a difference in output

 /*code 1*/ int hex = (char)0xA; System.out.println(hex); /*code 2*/ int hex = 0xA; System.out.println((char)hex); 
+4
source share
2 answers
 int hex = 0xA; System.out.println( (char)hex ); 

The hexadecimal value 0xA (or decimal 10) is equal to "\ n" (new char string) in ASCII.
Hence the way out.

EDIT (thanks halex for correcting the comments:

 int hex = (char) 0xA; System.out.println(hex); //here value of hex is '10', type of hex is 'int', the overloaded println(int x) is invoked. int hex = 0xA; System.out.println((char) hex); //this is equivalent to System.out.println( '\n' ); since the int is cast to a char, which produces '\n', the overloaded println(char x) is invoked. 
+8
source

I assume you want to print the letter A Use printf instead of print .

 int hex=0xA; System.out.printf("%X%n", hex); 
+1
source

Source: https://habr.com/ru/post/1438239/


All Articles