1: Put the String string in the front
Prevent the NullPointerException exception. We usually place the String string on the left side of the equals method to compare, so that it can effectively avoid it.
The occurrence of a null pointer exception.
In the first case, if the variable is Null, a null pointer exception will occur; in the second case, even if the variable is Null, a null pointer exception will not occur, and no data will be lost. So it is recommended
When programming, put the direct quantity on the left.
Two: Don't believe in the early JDK API
In early programming, the JDK API was not very mature, such as the following code block:
File file=new File("..."), file encapsulates a directory or file, calls the list() method, if it is a directory, it returns a string array; if it is not, it returns null;
So we can add some checks in advance, as shown in the following code:
Three: Don't believe it-1
It is clearly stipulated in javadoc that if the return value of String.indexOf() is -1, it means that the character does not exist in the string; or when we use IO stream to read the file, it is also defined as -1
When reading is completed. The following code:
At present, this method seems to be very effective, but if Java changes the encoding method and defines the return -2 as a better way, so it is recommended to use the second one.
Four: Avoid unexpected assignments
The following code:
The first case: if the == sign is written as =, it will accidentally assign 5 as a variable; the second case: there will be no unexpected assignment;
The third case: === is a congruent symbol in JavaScript, with the same type and the values are also equal.
Five: Check Null and Length
In any case, as long as you have a collection or array, first make sure it exists and is not empty.
The code is as follows:
The second method is better, avoiding errors in earlier versions of JDK APIs.
Six: All methods are final
Avoid subclasses inherit all methods of parent class.
The above common java programming techniques (recommended) are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.