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 the java.lang package, which is automatically imported in Java. The explicit import statement here is optional.
  • Integer is a wrapper class that provides an object representation for primitive int 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 value 100.
    • This object is an instance of the Integer class, which wraps the primitive int value 100.
  • Note:
    • The constructor new Integer(int value) is deprecated in modern Java versions. You should use Integer.valueOf(100) or simply 100 (autoboxing) instead.

5. Print the Value

System.out.println ("Value of Integer object : " + iObj);
  • Prints the value stored in the Integer object.
  • The toString() method of the Integer class is implicitly called to convert the object to a string for display.

Key Concepts

  1. Wrapper Classes:

    • A wrapper class provides an object representation for primitive data types. In this case, Integer is the wrapper class for the primitive type int.
  2. 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.
  3. 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
      

Output

Value of Integer object : 100