In Java, int is a primitive data type used to store whole numbers, while Integer is a wrapper class that encapsulates an int value as an object. This distinction is crucial:
intis a primitive type that stores values directly in memory (typically 32 bits). It is faster and uses less memory but cannot be used in collections or with generics.Integeris a class that wraps anintvalue. It enables the use of integers in collections (likeList<Integer>), supports null values, and provides utility methods (e.g.,parseInt(),toString(),compareTo()).
Since Java 5, autoboxing and unboxing automatically convert between int and Integer:
int a = 10;
Integer b = a; // Autoboxing
int c = b; // UnboxingKey Constants in Integer Class:
Integer.MAX_VALUE: 2,147,483,647 (maximum value forint)Integer.MIN_VALUE: -2,147,483,648 (minimum value forint)Integer.SIZE: 32 bitsInteger.BYTES: 4 bytes
When to Use Which?
Use
intfor performance-critical code, loops, arithmetic, and when null is not needed.Use
Integerwhen you need nullability, generics, or object behavior (e.g., in collections, databases, or APIs expecting objects).
⚠️ Memory Note:
Integerobjects use more memory (~16 bytes) thanint(4 bytes). UsingIntegerin large collections can significantly increase memory usage.
Common Operations:
Convert
Stringtoint:Integer.parseInt("123")Convert
inttoString:Integer.toString(123)orString.valueOf(123)Convert
inttoInteger:Integer.valueOf(123)(preferred overnew Integer(123))
Use Integer only when necessary—otherwise, stick with int for better performance.
the Integer class is provided so that values can be boxed/unboxed in a pure OO manner. use int where appropriate unless you specifically need to use it in an OO way; in which case Integer is appropriate.
Java Int vs Integer
However, very different things are going on under the covers here. An int is a number; an > Integer is a pointer that can reference an object that contains a number.
...
An int is not an object and cannot passed to any method that requires objects. A common case is in using the provided collection classes ( List , Map , Set ) - though it is possible to write versions of these classes that provide similar capabilities to the object versions. The wrapper classes ( Integer , Double , etc) are frequently required whenever introspection is used (such as in the reflection API).
A better description of when to use one vs. the other:
Choosing between int and Integer
Answer from Mike McMahon on Stack OverflowI'll start with how these types should be used before going into detail on why.
- Prefer
intfor performance reasons- Methods that take objects (including generic types like
List<T>) will implicitly require the use ofInteger- Use of
Integeris relatively cheap for low values (-128 to
- because of interning - use
Integer.valueOf(int)and not new Integer(int)
- Do not use
==or!=with Integer types- Consider using
Integerwhen you need to represent the absence of a value (null)- Beware unboxing Integer values to int with null values
the Integer class is provided so that values can be boxed/unboxed in a pure OO manner. use int where appropriate unless you specifically need to use it in an OO way; in which case Integer is appropriate.
Java Int vs Integer
However, very different things are going on under the covers here. An int is a number; an > Integer is a pointer that can reference an object that contains a number.
...
An int is not an object and cannot passed to any method that requires objects. A common case is in using the provided collection classes ( List , Map , Set ) - though it is possible to write versions of these classes that provide similar capabilities to the object versions. The wrapper classes ( Integer , Double , etc) are frequently required whenever introspection is used (such as in the reflection API).
A better description of when to use one vs. the other:
Choosing between int and Integer
I'll start with how these types should be used before going into detail on why.
- Prefer
intfor performance reasons- Methods that take objects (including generic types like
List<T>) will implicitly require the use ofInteger- Use of
Integeris relatively cheap for low values (-128 to
- because of interning - use
Integer.valueOf(int)and not new Integer(int)
- Do not use
==or!=with Integer types- Consider using
Integerwhen you need to represent the absence of a value (null)- Beware unboxing Integer values to int with null values
If you can use int do so. If the value can be null or is used as an Object e.g. Generics, use Integer
Usually it doesn't matter which one you use but often int performs slightly better.
Force / hint of Int to java.lang.Integer? - Support - Kotlin Discussions
java - Which one to use, int or Integer - Stack Overflow
utilities - Checking if a number is an Integer in Java - Stack Overflow
spring - int or Integer in java - Stack Overflow
Videos
Integer is a better option, as it can handle null; for int, null would become 0, silently, if resultSet.getInt(..) is used. Otherwise, it might throw some exception, something like, "Unable to set null to a primitive property".
Performance is of little concern here.
- if you choose
int, you will end-up adding extra handling code; and that wouldn't benefit you much. Your code will not be clean and straight-forward, lot of boiler-plate code, and you wouldn't even gain performance. - let me make it clear, for databases, null is not same as zero. Sometimes you end-up entering
0, wherenullwas intended. Imagine the case where user submitted a form, and doesn't supply any value forint. You will end up getting0by default. It makes sense, or does that really, when that field isnot nullin the database.
You should really make your decision based on- what you need your object to do, rather than the performance costs. Deciding based on performance should be done, once a speed issue has been identified with a profiler - the root of all evil and all that.
Look at some of the features of both and use that for your decision, e.g.
Integercan benull,intcannot. So is theintin the DB aNullablefield?- Do you need access to the
Integerclass methods? - Are you doing arithmetic?
Personally, I always opt for the primitive over the wrapper. But that's just a preference thing, rather than based on any technical merit.
Quick and dirty...
if (x == (int)x)
{
...
}
edit: This is assuming x is already in some other numeric form. If you're dealing with strings, look into Integer.parseInt.
One example more :)
double a = 1.00
if(floor(a) == a) {
// a is an integer
} else {
//a is not an integer.
}
In this example, ceil can be used and have the exact same effect.
My question is, in which condition int or Integer should be used and is there any advantage of either of them over another?
Well, you should use the reference type Integer whenever you have to. Integer is nothing more than a boxed int. An Object with a single field containing the specified int value.
Consider this example
public class Ex {
int field1;
Integer field2;
public Ex(){}
}
In this case field1 will be initialized with the value 0 while field2 will be initialized with null. Depending on what the fields represent, both approaches might be advantageous. If field1 represents some kind of UUID, would you want it to be initialized with a zero value?
I wouldn't worry too much about the performance implications of Autoboxing. You can still optimize after you get your code running.
For more information take a look at the documentation
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Integer.html
You always use int, pretty much.
Integer should rarely be used; it is an intermediate type that the compiler takes care of for you. The one place where Integer is likely to appear is in generics, as int is simply not legal there. Here is an example:
List<Integer> indices = new ArrayList<Integer>();
int v = 10;
indices.add(v);
The above works: It compiles with no errors and does what you think it would (it adds '10' to a list of integer values).
Note that v is of type int, not Integer. That's the correct usage; you could write Integer here and the code works as well, but it wouldn't be particularly idiomatic java. Integer has no advantages over int, only disadvantages; the only time you'd use it, is if int is straight up illegal. Which is why I wrote List<Integer> and not List<int> as the latter is not legal java code (yet - give it a few versions and it may well be legal then, see Project Valhalla).
Note also that the compiler is silently converting your v here; if you look at the compiled code it is as if javac compiled indices.add(Integer.valueOf(v)) here. But that's fine, let the compiler do its thing. As a rule what the compiler emits and what hotspot optimizes are aligned; trust that what javac emits will be relatively efficient given the situation.
Integer objects are immutable, so you cannot modify the value once they have been created. You will need to create a new Integer and replace the existing one.
playerID = new Integer(playerID.intValue() + 1);
As Grodriguez says, Integer objects are immutable. The problem here is that you're trying to increment the int value of the player ID rather than the ID itself. In Java 5+, you can just write playerID++.
As a side note, never ever call Integer's constructor. Take advantage of autoboxing by just assigning ints to Integers directly, like Integer foo = 5. This will use Integer.valueOf(int) transparently, which is superior to the constructor because it doesn't always have to create a new object.
int is a primitive type. Variables of type int store the actual binary value for the integer you want to represent. int.parseInt("1") doesn't make sense because int is not a class and therefore doesn't have any methods.
Integer is a class, no different from any other in the Java language. Variables of type Integer store references to Integer objects, just as with any other reference (object) type. Integer.parseInt("1") is a call to the static method parseInt from class Integer (note that this method actually returns an int and not an Integer).
To be more specific, Integer is a class with a single field of type int. This class is used where you need an int to be treated like any other object, such as in generic types or situations where you need nullability.
Note that every primitive type in Java has an equivalent wrapper class:
bytehasByteshorthasShortinthasIntegerlonghasLongbooleanhasBooleancharhasCharacterfloathasFloatdoublehasDouble
Wrapper classes inherit from Object class, and primitive don't. So it can be used in collections with Object reference or with Generics.
Since java 5 we have autoboxing, and the conversion between primitive and wrapper class is done automatically. Beware, however, as this can introduce subtle bugs and performance problems; being explicit about conversions never hurts.
An Integer is pretty much just a wrapper for the primitive type int. It allows you to use all the functions of the Integer class to make life a bit easier for you.
If you're new to Java, something you should learn to appreciate is the Java documentation. For example, anything you want to know about the Integer Class is documented in detail.
This is straight out of the documentation for the Integer class:
The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.