Type conversion in Java

John Doe ·

1194 Views

Converting int to string

String myString = Integer.toString(my int value)

or 

String str = "" + i

 

Converting String to int

int i = Integer.parseInt(str);

or 

int i = Integer.valueOf(str).intValue();

 

Double to String :

String str = Double.toString(i);

 

Long to String :

String str = Long.toString(l);

 

Float to String :

String str = Float.toString(f);

 

String to double :

double d = Double.valueOf(str).doubleValue();

 

String to long :

long l = Long.valueOf(str).longValue();

or

long l = Long.parseLong(str);

 

String to float :

float f = Float.valueOf(str).floatValue();


Decimal to binary :

int i = 42;
String binstr = Integer.toBinaryString(i);


Decimal to hexadecimal :

int i = 42;
String hexstr = Integer.toString(i, 16);

or

String hexstr = Integer.toHexString(i);

or (with leading zeroes and uppercase)

public class Hex {
     public static void main(String args[]){
       int i = 42;
       System.out.print
       (Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
      }
}

 

Hexadecimal (String) to integer :

int i = Integer.valueOf("B8DA3", 16).intValue();

or

int i = Integer.parseInt("B8DA3", 16);    


ASCII code to String

int asciiVal = 87;
String str = new Character((char) asciiVal).toString();

 

Float to integer (Round off the decimal place)

float a = 1.1f;
float b = 2.1f;
int i = ((int)(100-a/b*100));
System.out.println(i);
// 47