Wrapper Example in Java
On this page (10sections)
Introduction
Wrapper is a classic Java console program that demonstrates the concept with complete source code and sample output. The Collections Framework provides ArrayList, HashMap, HashSet and related data structures.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
A wrapper class is a class that encapsulates types so that those types can be used to create object instances and methods in another class that need those types.
Syntax
Integer variable-name = new Integer(10);
Wrapper Example Program
public class WrapperExample {
public static void main(String[] args) {
int primitiveInteger = 500;
System.out.println("Primitive Integer : " + primitiveInteger);
Integer wrapperInteger = Integer.valueOf(primitiveInteger);
System.out.println("After assigning this value in Wrapper Integer : " + wrapperInteger);
primitiveInteger = wrapperInteger.intValue();
System.out.println("Again assigning this value in Primitive Integer : " + primitiveInteger);
String integerString = "1000";
System.out.println("String to be converted to integer : " + integerString);
System.out.println("Converting String to integer : " + Integer.parseInt(integerString));
}
}
Sample Output
Primitive Integer : 500
After assigning this value in Wrapper Integer : 500
Again assigning this value in Primitive Integer : 500
String to be converted to integer : 1000
Converting String to integer : 1000
When to use
Use this wrapper example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
int primitiveInteger = 500;updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
Integer wrapperInteger = Integer.valueOf(primitiveInteger);updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
primitiveInteger = wrapperInteger.intValue();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.