A primitive data type such as int
holds values directly into the variable that is using it, meanwhile a variable that was declared using Integer
holds a reference to the value.
According to java API: "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."
By default, int
is a 32-bit signed integer. It can store a minimum value of -231, and a maximum value of 231 - 1.
int example = -42;
int myInt = 284;
int anotherInt = 73;
int addedInts = myInt + anotherInt; // 284 + 73 = 357
int subtractedInts = myInt - anotherInt; // 284 - 73 = 211
If you need to store a number outside of this range, long
should be used instead. Exceeding the value range of int
leads to an integer overflow, causing the value exceeding the range to be added to the opposite site of the range (positive becomes negative and vise versa). The value is ((value - MIN_VALUE) % RANGE) + MIN_VALUE
, or ((value + 2147483648) % 4294967296) - 2147483648
int demo = 2147483647; //maximum positive integer
System.out.println(demo); //prints 2147483647
demo = demo + 1; //leads to an integer overflow
System.out.println(demo); // prints -2147483648
The maximum and minimum values of int
can be found at:
int high = Integer.MAX_VALUE; // high == 2147483647
int low = Integer.MIN_VALUE; // low == -2147483648
The default value of an int
is 0
int defaultInt; // defaultInt == 0