Java - Integer

About

integer in Java.

int (or Integer) is the 32 bit implementation of an integer.

Java can also store an integer on 64 bit with a long.

An integer in java is a sub-class of number

Immutable

They are immutable which means that they are not passed by reference. ie

Integer i = 4;
Integer j = i; // a copy is made
j = j - 1;
System.out.println("i="+i);
System.out.println("j="+j);
i=4
j=3

Primitive Integer implementation class

Primitive Type Primitive Wrapper Stored in a word of min max
int Integer 32 bits <math>-2^{31}</math>
-2,147,483,648
<math>+2^{31}-1</math>
-2,147,483,647
long Long 64 bits <math>-2^{63}</math>
-9,223,372,036,854,775,807
<math>+2^{63-1}</math>
‭4.611.686.018.427.387.904‬

See also BigInteger - 64 bit signed integer (from to -9223372036854775808 to 9223372036854775807)

Management

Initialization

int var = 5;
Integer var = 5;

Operation

Number - (Arithmetical | Numerical | Mathematical) Operators on integer

The operations are done in the largest data type required to handle all of the current values.

For the below mathematics Operations The operation is a
int (operator) int integer operation
int (operator) long long operation

Example:

  • a long operation
long i = (int)1 * (long)2
  • a int operation
long i = (int)1 * (int)2

To Long

  • from an integer
Long i = theinteger.longValue()
/**
   * 1.2.3.4 = 4 + (3 * 256) + (2 * 256 * 256) + (1 * 256 * 256 * 256)
   * is 4 + 768 + 13,1072 + 16,777,216 = 16,909,060
   *
   * @param ip
   * @return the numeric representation
   */
static protected Long getNumericIp(String ip) {
    Long[] factorByPosition = {256 * 256 * 256L, 256 * 256L, 256L, 1L};
    String[] ipParts = ip.split("\\.");
    return IntStream.range(0, ipParts.length)
      .mapToLong(i -> Integer.parseInt(ipParts[i]) * factorByPosition[i])
      .sum();
}

To Double

double v = ((Integer) v).doubleValue();

Max Or Null

Integer max = listIntegerValues
                .stream()
                .max(Comparator.naturalOrder())
                .orElse(null);

Sequence


Powered by ComboStrap