Wednesday, November 5, 2014

Java data type conversion

Java auto boxing is a nice feature but it can sometimes cause a lot of problems, especially when going from Object to primitive. A NullPointerException can be very hard to spot, because it can be throw in strange places where you normally would not expect it. See this for some auto boxing errors.
This blog will list some nice data type conversion between different data type and from primitive and Object type and vise versa.

Integer/int conversion
See examples here. 

Data type from, to Use Comment
int to Integer int i = 10; 
Integer intObj = Integer.valueOf(i);

int to Long int i = 10;
Long longObj= Long.valueOf(i);

int to long int i = 10;
long l = (long) i;

int to String int i = 10;
String s = Integer.toString(i);

Integer to int Integer intObj = new Integer(10);
int i = intObj.intValue();
NumberFormatException will be thrown if the intObj is a null Integer.
Integer to String Integer intObj = new Integer(10);
String s = intObj.toString();
NumberFormatException will be thrown if the intObj is a null Integer.
Integer to long Integer intObj = new Integer(10);
long l = intObj.longValue();
NumberFormatException will be thrown if the intObj is a null Integer.
Integer to Long Integer intObj = new Integer(10);
Long longObj = Long.valueOf(intObj.longValue());
NumberFormatException will be thrown if the intObj is a null Integer.

Long/long conversion
Careful when converting from Long/long to Integer/int. No exception is thrown if the Long value is bigger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE. It will simple do an int overflow and the output will be unexpected.
See examples here
long to Long long l = 10L;
Long longObj = Long.valueOf(l);

long to Integer long l = 10L;
Integer intObj = Integer.valueOf(Long.valueOf(l).intValue());
No really good way of doing this. Overflow may occur.
long to String long l = 10L;
String s = Long.toString(l);

long to int long l = 10L;
int i = (int) l;
Use simple cast.
Overflow may occur.
Long to long Long longObj = new Long(10L);
long l = longObj.longValue();
NumberFormatException will be thrown if the longObj is a null Long.
Long to String Long longObj = new Long(10L);
String s = longObj.toString();

Long to Integer Long longObj = new Long(10L);
Integer intObj = Integer.valueOf(longObj.intValue());
No really good way of doing this. Overflow may occur.
Long to int Long longObj = new Long(10L);
int i = longObj.intValue();
Overflow may occur.