Skip to content

Integer Operations

Java's integer operations follow the four arithmetic rules, and any nested parentheses can be used. The four operation rules are consistent with elementary mathematics. For example:

java
public class Main {
  public static void main(String[] args) {
    int i = (100 + 200) * (99 - 88); // 3300
    int n = 7 * (5 + (i - 9)); // 23072
    System.out.println(i);
    System.out.println(n);
  }
}

Not only are the numerical representations of integers exact, but integer arithmetic is always exact, even division is exact, because dividing two integers only yields the integer part of the result:

java
int x = 12345 / 67; // 184

The remainder operation uses % :

java
int y = 12345 % 67; // The remainder of 12345÷67 is 17

Special note: Integer division will report an error when the divisor is 0, but the compiler will not report an error.

Overflow

Pay special attention to the fact that integers have range restrictions. If the calculation result exceeds the range, an overflow will occur. Overflow will not cause an error, but a strange result will be obtained:

java
public class Main {
    public static void main(String[] args) {
        int x = 2147483640;
        int y = 15;
        int sum = x + y;
        System.out.println(sum); // -2147483641
    }
}

To explain the above results, we convert the integers 2147483640 and 15 into binary and add them:

  0111 1111 1111 1111 1111 1111 1111 1000
+ 0000 0000 0000 0000 0000 0000 0000 1111
-----------------------------------------
  1000 0000 0000 0000 0000 0000 0000 0111

Since the highest bit evaluates to 1 , the addition result becomes a negative number.

To solve the above problem, you can change int to long type. Since long can represent a larger range of integers, the result will not overflow:

java
long x = 2147483640;
long y = 15;
long sum = x + y;
System.out.println(sum); // 2147483655

There is also a shorthand operator, namely += , -= , *= , /= . They are used as follows:

java
n += 100; // 3409, Equivalent to n = n + 100;
n -= 100; // 3309, Equivalent to n = n - 100;

Self-Increment/Self-Decrement

Java also provides the ++ operation and the -- operation, which can add 1 and subtract 1 to an integer:

java
public class Main {
    public static void main(String[] args) {
        int n = 3300;
        n++; // 3301, Equivalent to n = n + 1;
        n--; // 3300, Equivalent to n = n - 1;
        int y = 100 + (++n); // Don't write like this
        System.out.println(y);
    }
}

Note that the calculation results are different when ++ is written in the front and in the back. ++n means adding 1 first and then citing n, and n++ means citing n first and then adding 1. It is not recommended to mix ++ operations into regular operations, as it can easily confuse yourself.

Shift Operation

In computers, integers are always represented in binary form. For example, the binary representation of the int 7 using 4 bytes is as follows:

00000000 0000000 0000000 00000111

Shift operations can be performed on integers. Shifting the integer 7 to the left by 1 bit will give you the integer 14 , and shifting it to the left by two places will give you the integer 28 :

java
int n = 7;       // 00000000 00000000 00000000 00000111 = 7
int a = n << 1;  // 00000000 00000000 00000000 00001110 = 14
int b = n << 2;  // 00000000 00000000 00000000 00011100 = 28
int c = n << 28; // 01110000 00000000 00000000 00000000 = 1879048192
int d = n << 29; // 11100000 00000000 00000000 00000000 = -536870912

When shifting 29 bits to the left, since the highest bit becomes 1 , the result becomes a negative number.

Similarly, if the integer 28 is shifted to the right, the result is as follows:

java
int n = 7;       // 00000000 00000000 00000000 00000111 = 7
int a = n >> 1;  // 00000000 00000000 00000000 00000011 = 3
int b = n >> 2;  // 00000000 00000000 00000000 00000001 = 1
int c = n >> 3;  // 00000000 00000000 00000000 00000000 = 0

If a negative number is shifted right, the highest bit 1 does not move, and the result is still a negative number:

java
int n = -536870912;
int a = n >> 1;  // 11110000 00000000 00000000 00000000 = -268435456
int b = n >> 2;  // 11111000 00000000 00000000 00000000 = -134217728
int c = n >> 28; // 11111111 11111111 11111111 11111110 = -2
int d = n >> 29; // 11111111 11111111 11111111 11111111 = -1

There is also an unsigned right shift operation, using >>> . Its characteristic is that regardless of the sign bit, the high bit is always filled with 0 after the right shift. Therefore, if a negative number is shifted right, It will become positive because the highest bit 1 becomes 0 :

java
int n = -536870912;
int a = n >>> 1;  // 01110000 00000000 00000000 00000000 = 1879048192
int b = n >>> 2;  // 00111000 00000000 00000000 00000000 = 939524096
int c = n >>> 29; // 00000000 00000000 00000000 00000111 = 7
int d = n >>> 31; // 00000000 00000000 00000000 00000001 = 1

When shifting byte and short types, they will first be converted to int and then shifted.

If you observe carefully, you can find that moving left is actually ×2 continuously, and moving right is actually ÷2 continuously.

Bit Operations

Bitwise operations are bitwise operations such as AND, OR, NOT, and XOR.

The rule of AND operation is that both numbers must be 1 at the same time for the result to be 1 :

java
n = 0 & 0; // 0
n = 0 & 1; // 0
n = 1 & 0; // 0
n = 1 & 1; // 1

The rule of the OR operation is that as long as any one is 1 , the result is 1 :

java
n = 0 | 0; // 0
n = 0 | 1; // 1
n = 1 | 0; // 1
n = 1 | 1; // 1

The rule for NOT operations is that 0 and 1 are interchanged:

java
n = ~0; // 1
n = ~1; // 0

The rule of XOR operation is that if the two numbers are different, the result is 1 , otherwise it is 0 :

java
n = 0 ^ 0; // 0
n = 0 ^ 1; // 1
n = 1 ^ 0; // 1
n = 1 ^ 1; // 0

Performing bitwise operations on two integers is actually aligning them bitwise, and then performing operations on each bit in turn. For example:

java
public class Main {
    public static void main(String[] args) {
        int i = 167776589; // 00001010 00000000 00010001 01001101
        int n = 167776512; // 00001010 00000000 00010001 00000000
        System.out.println(i & n); // 167776512
    }
}

The above bitwise AND operation can actually be regarded as the IP addresses 10.0.17.77 and 10.0.17.0 represented by two integers. Through the AND operation, you can quickly determine whether an IP is within a given network segment.

Operation Priority

In Java calculation expressions, the operation priority from high to low is:

  • ()
  • ! ~ ++ --
  • * / %
  • + -
  • << >> >>>
  • &
  • |
  • += -= *= /=

It doesn't matter if you can't remember it. You only need to add parentheses to ensure that the priority of the operation is correct.

Type automatic promotion and forced transformation

During the operation, if the types of the two numbers involved in the operation are inconsistent, the calculation result will be an integer of the larger type. For example, when calculating short and int , the result is always int . The reason is that short is automatically converted to int first:

java
public class Main {
    public static void main(String[] args) {
        short s = 1234;
        int i = 123456;
        int x = s + i; // s is automatically converted to int
        short y = s + i; // Compilation error!
    }
}

The result can also be forced to transform, that is, a large range of integers can be transformed into a small range of integers. Casting uses (type) , for example, casting int to short :

java
int i = 12345;
short s = (short) i; // 12345

It should be noted that forced conversion outside the range will give wrong results. The reason is that during the conversion, the two high-order bytes of int are directly thrown away, and only the two low-order bytes are retained:

java
public class Main {
    public static void main(String[] args) {
        int i1 = 1234567;
        short s1 = (short) i1; // -10617
        System.out.println(s1);
        int i2 = 12345678;
        short s2 = (short) i2; // 24910
        System.out.println(s2);
    }
}

Therefore, the results of forced transformation are likely to be wrong.

Practise

Calculating the sum of the first N natural numbers can be calculated according to the formula:

(1+N) * N
---------
    2

Please calculate the sum of the first N natural numbers according to the formula:

java
// Calculate the sum of the first N natural numbers
public class Main {
    public static void main(String[] args) {
        int n = 100;
        // TODO: sum = 1 + 2 + ... + n
        int sum = ???;
        System.out.println(sum);
        System.out.println(sum == 5050 ? "Test passed" : "Test failed");
    }
}

Summary

The results of integer operations are always accurate;

The operation result will be automatically improved;

Forced conversion is possible, but forced conversion beyond the scope will give wrong results;

You should choose an integer type of appropriate range ( int or long ). There is no need to use byte and short for integer operations to save memory.

Integer Operations has loaded