Convert Decimal to hexadecimal Using toHexString() method
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
Scanner scanner = new Scanner( System.in );
System.out.print("Enter the decimal number you want to convert in Hexadecimal : ");
int number =scanner.nextInt();
String hexstr = Integer.toHexString(number);
System.out.println("Afer conversion from Decimal to hexadecimal is: "+hexstr);
}
}
Output:-
Enter the decimal number you want to convert in Hexadecimal : 1234 Afer conversion from Decimal to hexadecimal is: 4D2
Convert Decimal to hexadecimal without using predefined method in Java
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
Scanner scanner = new Scanner( System.in );
System.out.print("Enter the decimal number you want to convert in Hexadecimal : ");
int number =scanner.nextInt();
int remainder;
String hexstr="";
char hexarr[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(number>0)
{
remainder=number%16;
hexstr=hexarr[remainder]+hexstr;
number=number/16;
}
System.out.println("Afer conversion from Decimal to hexadecimal is: "+hexstr);
}
}
Output:-
Enter the decimal number you want to convert in Hexadecimal : 1234 Afer conversion from Decimal to hexadecimal is: 4D2