Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a hexadecimal Integer into a character using explicit type conversion?

I coded the following, But the o/p is not the expected ? Someone Guide me?

Question: Write a sample program to declare a hexadecimal integer and covert it into a character using explicit type Conversion?

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

please tell me : Why there is a difference in output

/*code 1*/
int hex = (char)0xA; 
System.out.println(hex); 
/*code 2*/
int hex = 0xA; 
System.out.println((char)hex);
like image 223
Rand Mate Avatar asked Oct 07 '12 08:10

Rand Mate


People also ask

What is explicit type conversion?

Explicit type conversion, also called type casting, is a type conversion which is explicitly defined within a program (instead of being done automatically according to the rules of the language for implicit type conversion). It is defined by the user in the program.

Which method converts an integer to a hexadecimal string?

toHexString() method in Java converts Integer to hex string. Let's say the following are our integer values. int val1 = 5; int val2 = 7; int val3 = 13; Convert the above int values to hex string.

What is an implicit conversion?

An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.


2 Answers

int hex = 0xA; 
System.out.println( (char)hex );

The hex value 0xA (or decimal 10) is "\n" (new line feed char) in ASCII.
Hence the output.

EDIT (thanks to halex for providing the correction in 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.
like image 108
Zaki Avatar answered Oct 12 '22 23:10

Zaki


I assume you want the letter A to be printed. Instead of print use printf.

int hex=0xA;
System.out.printf("%X%n", hex);
like image 28
halex Avatar answered Oct 13 '22 01:10

halex