Videos
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.
import java.util.*;
class Main {
public static void main(String args[]) {
Integer[] a = {1,2};
int[] b = {1,2};
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
}
}Hi all, trying to learn Java from python background and run into some trouble.
So I have read that Integer is the object class and int is the binary primitive, and that Java compiler is now able to convert between them when nesessary.
But when should I use the primitive vs the object ? Generally speaking, all I can think of right now is that we should always use the primitives unless we may need to cast to another type in the future so then use object ones.