int to Integer Java

In this post, I will be sharing how to convert int to Integer in Java. The main difference between int and Integer is that int is a primitive data type whereas Integer is a wrapper class that wraps a value of the primitive data type int in an object.

There are two ways to convert int to Integer in Java:

1. Using Integer.valueOf() method
2. Using new keyword

Read Also:  How to convert char to Character in Java

1. Using Integer.valueOf() method

You can use Integer's class valueOf() method to convert int to Integer as shown below:

 public class IntToInteger {
    public static void main(String args[]) {
      // Initializing int variable
      int i=100;
      // Convert int to Integer using Integer.valueOf() method
      Integer intObj = Integer.valueOf(i);
      // Printing Integer
      System.out.println("Integer is: " + intObj);
    }
}


Output:
Integer is: 100

2. Using new keyword

You can use new keyword to convert int to Integer in Java as shown below:

 public class IntToInteger2 {
    public static void main(String args[]) {
      // Initializing int variable
      int i = 200;
      // Convert int to Integer using new keyword
      Integer intObj = new Integer(i);
      // Displaying Integer
      System.out.println("Integer is: " + intObj);
    }
}


Output:
Integer is: 200

That's all for today. Please mention in the comments in case you have any questions related to how to convert int to Integer in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry