When writing code, especially in digital computing, we often encounter computing boundary problems, that is, overflow problems, such as: what happens to the smallest negative-1? What will happen to the largest positive integer + 1?
Let's take a look at the following code:
package com.test;public class Test {public static void main(String[] args) {Test test = new Test();Operator op = test.getMaxInstance();test.printResult("MaxValue", op);op = test.getMinInstance();test.printResult("MiniValue", op);}public void printResult(String tag, Operator op) {System.out.println(tag + ": " + op.getValue());System.out.println(tag + "+1: " + op.add(1));System.out.println(tag + "-1: " + op.minues(1));}public Operator getMaxInstance() {return new MaxValue();}public Operator getMinInstance() {return new MinimalValue();}interface Operator {int add(int a);int minues(int b);int getValue();}class MaxValue implements Operator {final int value = 0x7fffffff;@Overridepublic int getValue() {return value;}@Overridepublic int add(int a) {return value + a;}@Overridepublic int minues(int a) {return value - a;}}class MinimalValue implements Operator {final int value = 0x80000000;@Overridepublic int add(int a) {return value + a;}@Overridepublic int minues(int b) {return value - b;}@Overridepublic int getValue() {return value;}}}
The result of running the above Code is:
MaxValue: 2147483647MaxValue+1: -2147483648MaxValue-1: 2147483646MiniValue: -2147483648MiniValue+1: -2147483647MiniValue-1: 2147483647
The preceding operations are summarized as follows:
The following is a binary explanation.
The minimum value is 0x10000000 ===> 10000000 00000000 00000000 00000000 <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + 1 + 608yYjMjA1NDA7zqoweDdGRkZGRkZGPT09PT0 + signature + Signature = "s complement operation, just like the above
The maximum value + 1 = 10000000 00000000 00000000 00000000 =======" should be converted to decimal format according to the two's complement operation, just as above
Next we will discuss float and double and how to determine overflow.