Java: Wrapper Classes

This tech recipe describes going to and from the Java Object wrapper classes.


Wrapper classes do exactly what the name implies: they wrap primitive types (e.g., int, double, etc.) in Objects which can be placed into Vectors, and many other uses.

*Notice that an Object starts with a capital letter, while the primitives all start with a lowercase. Also, notice that Strings are Objects.

These Wrapper classes can be created in many ways, so I will start slowly by simply returning Objects with a String.

Integer from String:
Integer i = Integer.valueOf(“125”);

Double from String:
Double d = Double.valueOf(“5.829754097”);

Float from String:
Float f = Float.valueOf(“8.43543”);

Boolean from String:
Boolen b = Boolean.valueOf(“true”);
//This will represent true

Character from String:
Character c = Character.valueOf(“G”);

The more common use is given the primitive in a variable. This next section shows how to convert a variable to these wrapper classes and back to a primitive.

Integer:
int i = 5;
Integer I = Integer.valueOf(i); //Wrapper
int i2 = I.intValue(); //back to primitive

Float:
float f = 5.5f;
Float F = Float.valueOf(f); //Wrapper
float f2 = F.floatValue(); //back to primitive

Double:
double d = 5.55555;
Double D = Double.valueOf(d); //Wrapper
double d2 = D.doubleValue(); //back to primitive

Boolean:
boolean b = true;
Boolean B = Boolean.valueOf(b); //Wrapper
boolean b2 = B.booleanValue(); //back to primitive

*When dealing with strings, you may also wish to use the following to get primitives from the Object String:

Integer:
int i = Integer.parseInt(“234”);

Double
double d = Double.parseDouble(“234.6576533254”);

Float:
float f = Float.parseFloat(“234.78”);

Long:
long l = Long.parseLong(“23454654”);

*Note: You may wish to add the ().trim feature to these last ones in the case of extra white space around your String, which may cause exceptions.
Example of trim:
String s = ” William “; // displays as ‘ William ‘
String s2 = (s).trim(); //displays ‘William’

Questions/Comments: [email protected]
-William. § (marvin_gohan)

RELATED ARTICLES

5 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments

Cleveland Furia on How to Clear Google Activity
Sid Wohlfarth on How to Clear Google Activity
Riley Magsayo on How to Clear Google Activity
สมัครรับเครดิตฟรี ทันที on How to improve Remote Desktop Protocol Performance
Neal Wangstad on How to Clear Google Activity
Slavcho Andov on How to install Ubuntu
Slavcho Andov on How to fix bad sectors
Sheraz Ali on How to Backup Android