Common java programming technologies, java programming

Source: Internet
Author: User

Common java programming technologies, java programming

I. Put the String at the beginning to prevent NullPointerException. We usually place the String on the left side of the equals Method for comparison, which can effectively avoid

Null Pointer exception occurs.

In the first case, if variable is Null, a Null pointer exception occurs. In the second case, even if variable is Null, no Null pointer exception occurs and no data is lost. Therefore, we recommend that you

When you program, place the direct quantity on the left.

Ii. Do not trust early JDK APIs

In early programming, JDK APIs are not very mature, for example, the following code block:

File file = new File ("... "), file encapsulates a directory or file and calls the list () method. If it is a directory, a string array is returned. If not, null is returned;

Therefore, you can add some verification codes in advance, as shown in the following code:

3. Do not trust-1

In javadoc, specify String. indexOf (). If the returned value is-1, this character does not exist in the String. Or, when I/O Stream is used to read the file, it is also defined as-1.

Read is complete. The following code:

Currently, this method is very useful, but if java changes the encoding method, it is better to define return-2. Therefore, the second method is recommended.

4. Avoid accidental assignment

The following code:

First case: If the = sign is written as =, 5 is accidentally assigned as a variable. Second case: No unexpected assignment will occur;

Case 3: = indicates the all-round sign in JavaScript. The type is the same and the value is equal.

V. Check Null and Length.

In any case, as long as you have a set or array, make sure that it exists and is not empty.

The Code is as follows:

The second method is better, avoiding errors in earlier JDK APIs.

6. All methods are final.

Avoid subclass inheriting all methods of the parent class.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.