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);
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.
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.
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.
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.
I assume you want the letter A
to be printed.
Instead of print
use printf
.
int hex=0xA;
System.out.printf("%X%n", hex);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With