1. Null pointer error
In the use of Java arrays, it is sometimes necessary to compare elements in a string array. The program will run normally when the element is not NULL, however, the program will have a null pointer error if the element being compared is null.
Workaround: Add protection when the element is not NULL when it is judged.
String sr = "A";
for (int i=0;i<sums.length;i++) {
if (Sums[]!=null && sums[i].equals (sr)) {
System.out.println ("Find element" +sums[i]);
Break
}
}
2. Accuracy range and type conversion of data
There are 4 basic types of data in Java:
integral type: -1 2 3 4 ...
Float type:float 1.3f Double 3.2 3.5d (unspecified type, default highest precision)
character type: Unicode encoded, 2 bytes
Boolean : True, False
|
|
Format |
Length |
Accuracy Range |
Whole Type |
Byte |
-1 2 3 4 ... |
1 bytes |
-128~127 |
Short |
-1 2 3 4 ... |
2 bytes |
|
Int |
-1 2 3 4 ... |
4 bytes |
|
Long |
-1l, 2l, 3l, 4l,5l ... |
8 bytes |
|
Floating point Type |
Float |
2.3f (symbol is case insensitive) |
4 bytes |
|
Double |
3.2 2.3d |
8 bytes |
|
Character type |
Char |
A |
2 bytes |
|
Formula : n-bit binary storage accuracy range = -2n-1~2n-1-1 (1 bytes = 8 bits binary) |
The accuracy ranges of the four basic types of data vary and are progressively improved.
If you do not pay attention to the precision range when using the data type, a data overflow occurs and a calculation error occurs.
Of the four underlying types, integer, floating-point and character data can be converted to each other.
The conversion rules are as follows:
① Stealth Conversion: Small precision data values, assigned to a high precision value, can be automatically converted. (Low to Advanced)
② Cast: Large range of data values, (advanced to low level)
③ operation automatic Promotion rule : In the operation, automatic conversion to a high precision data type.
3. Use of three types of loops
①for Cycle: is a finite number of cycles, before the cycle, set a good cycle times.
for (an expression; an expression; an expression) {
Loop body
}
Break statement : After execution, immediately jumps out of the loop, does not execute subsequent statements, and ends all loops.
Continue statement : After execution, immediately jump out of the current word loop, re-determine whether the condition continues to follow.
②while Loop statement: a loop that fits the unknown number of times.
while (conditional expression) {
Statement
};
③do-while cycle : is also the number of unknown cycles. The order must be executed at least once before judging. If the while is set, continue the loop, and vice versa, end the loop.
do {
Statement
}while (conditional expression);
Some common errors in Java