Below is a program to demonstrate simple Java Type conversions with examples. You will notice the following converstions;
- Java String to Primitive Data Type
- Java Primitive Data Type to String
- Use of Wrapper classes to support the conversion
[sourcecode language='java']
public class JavaTypeConversions {
public static void main(String args[]) {
// ASCII code to String Conversion
int i = 74;
String iStr = new Character((char) i).toString();
System.out.println(”Ascii Code : ” + i + “\t”
+ “Converted to String : ” + iStr);
// decimal to binary Conversion
// Similarly you can convert it into a HexString using
// Integer.toHexString
int j = 74;
String bStr = Integer.toBinaryString(j);
System.out.println(”Decimal Value : ” + j + “\t” + “Binary String : ”
+ bStr);
// double to String Conversion
// Similarly you can convert from float to String using Float.toString
// Similarly you can convert from Integer to String using
// Integer.toString
double k = 74.50;
String dStr = Double.toString(k);
System.out.println(”Double Value : ” + k + “\t”
+ “Converted to String : ” + dStr);
// Char to Ascii Conversion
char l = ‘J’;
int m = (int) l;
System.out.println(”Char Code : ” + l + “\t” + “Converted to Ascii : ”
+ m);
// HexaDecimal to Integer
int n = Integer.valueOf(”A8DA3″, 16).intValue();
System.out.println(”Hexadecimal Code : A8DA3\t”
+ “Converted to Ascii : ” + n);
// String to double
// You can also do Double.parseDouble(”str”)
String oStr = “128″;
double p = Double.valueOf(oStr).doubleValue();
System.out.println(”String :” + oStr + “\t” + “Converted to double : ”
+ p);
// int to hexadecimal
int q = 17;
System.out.println(”int : “+q+”\t Converted to Hex is : ” + Integer.toHexString(i) );
}
}
[/sourcecode]











Leave a Reply