Java Program to demonstrate Integer wrapper class
Program
import java.lang.Integer;
public class javaLangIntegerDemo
{
public static void main (String[]args)
{
Integer iObj = new Integer(100);
System.out.println ("Value of Integer object : " + iObj);
}
}
This Java program demonstrates the use of the Integer wrapper class to create an object that represents an integer value and how to use it.
1. Import Statement
import java.lang.Integer;
- The
Integerclass is part of thejava.langpackage, which is automatically imported in Java. The explicitimportstatement here is optional. Integeris a wrapper class that provides an object representation for primitiveintvalues.
2. Class Definition
public class javaLangIntegerDemo
- Defines the class
javaLangIntegerDemo.
3. Main Method
public static void main (String[] args)
- Entry point for the program.
4. Create an Integer Object
Integer iObj = new Integer(100);
IntegerConstructor:- Creates an object of the
Integerwrapper class that stores the value100. - This object is an instance of the
Integerclass, which wraps the primitiveintvalue100.
- Creates an object of the
- Note:
- The constructor
new Integer(int value)is deprecated in modern Java versions. You should useInteger.valueOf(100)or simply100(autoboxing) instead.
- The constructor
5. Print the Value
System.out.println ("Value of Integer object : " + iObj);
- Prints the value stored in the
Integerobject. - The
toString()method of theIntegerclass is implicitly called to convert the object to a string for display.
Key Concepts
-
Wrapper Classes:
- A wrapper class provides an object representation for primitive data types. In this case,
Integeris the wrapper class for the primitive typeint.
- A wrapper class provides an object representation for primitive data types. In this case,
-
Why Use Wrapper Classes?
- To treat primitive data types as objects.
- Useful in collections like
ArrayList, which only work with objects. - Provide utility methods for conversion, parsing, and handling numbers.
-
Autoboxing and Unboxing:
- Autoboxing: Automatically converts a primitive type to its wrapper class.
Example:
Integer iObj = 100; // Autoboxing - Unboxing: Automatically converts a wrapper class object to its primitive type.
Example:
int primitiveValue = iObj; // Unboxing
- Autoboxing: Automatically converts a primitive type to its wrapper class.
Example:
Output
Value of Integer object : 100