Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Integer to int?

Tags:

java

integer

People also ask

What is the difference between int and Integer in Java?

In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it. Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.

Which is the correct way of converting an int value to Integer in below Java code?

To convert the Integer to int, we can use the intValue() or the parseInt() method. However, after Java 1.5 version, the Java compiler does this implicitly, and we don't need any explicit conversion. Before Java 1.5, no implicit conversion was available.


As already written elsewhere:

  • For Java 1.5 and later you don't need to do (almost) anything, it's done by the compiler.
  • For Java 1.4 and before, use Integer.intValue() to convert from Integer to int.

BUT as you wrote, an Integer can be null, so it's wise to check that before trying to convert to int (or risk getting a NullPointerException).

pstmt.setInt(1, (tempID != null ? tempID : 0));  // Java 1.5 or later

or

pstmt.setInt(1, (tempID != null ? tempID.intValue() : 0));  // any version, no autoboxing  

*using a default of zero, could also do nothing, show a warning or ...

I mostly prefer not using autoboxing (second sample line) so it's clear what I want to do.


Since you say you're using Java 5, you can use setInt with an Integer due to autounboxing: pstmt.setInt(1, tempID) should work just fine. In earlier versions of Java, you would have had to call .intValue() yourself.

The opposite works as well... assigning an int to an Integer will automatically cause the int to be autoboxed using Integer.valueOf(int).


Java converts Integer to int and back automatically (unless you are still with Java 1.4).


Another simple way would be:

Integer i = new Integer("10");

if (i != null)
    int ip = Integer.parseInt(i.toString());