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
Integer
class is part of thejava.lang
package, which is automatically imported in Java. The explicitimport
statement here is optional. Integer
is a wrapper class that provides an object representation for primitiveint
values.
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);
Integer
Constructor:- Creates an object of the
Integer
wrapper class that stores the value100
. - This object is an instance of the
Integer
class, which wraps the primitiveint
value100
.
- 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
Integer
object. - The
toString()
method of theInteger
class 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,
Integer
is 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