Type Conversions

 

conversion

Converting something means using a value or a substitute value as a different type.

Converting values is done by “casting.”

 

Casting

(type) value-to-convert

For primitives, this returns a new value of type that represents value-to-convert.

For objects, this allows a variable to be set to a value that has been assigned to another variable declared as a different type. Example:

//object conversion.
Object object = new Integer(1);
Integer integer = (Integer) object;

/primitive conversion.
int i = 1;
double d = (double) i;
System.out.println(d); //1.0

Rounding errors occur when an exact conversion between numbers is not possible. Example:

double d = 1.2;
int i = (int) d;
System.out.println(i) //1; discarded .2

 

Wrapping

Wrapping is creating something representing another. Wrappers are objects representing primitives where objects are required (example: ArrayList elements, which can only be objects).

List of primitives and their corresponding wrappers, along with what needs to be passed to the wrapper class constructor to create a wrapper:

Primitive type Wrapper class Constructor Argument type
byte Byte byte or String
short Short short or String
int Integer int or String
long Long long or String
float Float floatdouble or String
double Double double or String
char Character char
boolean Boolean boolean or String

Example:

Integer i = new Integer(1);

Wrapper objects can also be obtained by casting. Example:

int i = 1;
Integer wrapper = (Integer) i;

 

Autowrapping

Automatically wrapping occurs when ArrayLists, which can only take primitives as elements, are added of primitives.

Example:

ArrayList list = new ArrayList();
list.add(1); //create wrapper representing 1, then add the wrapper

(The above is actually equivalent to the steps of:)

ArrayList list = new ArrayList();
list.add(new Integer(1));

 

Converting String to other types

Wrapper classes often have a method beginning with parse, to convert a string into a certain primitive. Example:

int i = Integer.parseInt("100"); //i is now set to 100

 

READ  Static

Converting other types to String

Both object and primitive types have their own way to be converted to a String:

Objects have a method called toString(), which gives a String representation of the object. Example:

Object object = new Object();
String s = object.toString();

Primitives need to be converted to wrapper objects to do it. Example:

int I = 10;
Integer I = new Integer(i); //wrapping I so we can call toString()
String s = i.toString();

You can define your own way to convert an object to a string. Just define a method called toString in your class definition. Example:

public String toString()
{
     return “test”;
}
Please like & share: