Some good habits and details of Java ------ updating..., ------ updating

Source: Internet
Author: User

Some good habits and details of Java ------ updating..., ------ updating

1. Do not place the variable on the left side of the Operator During condition determination. This prevents NULL pointer exceptions. Take string comparison as an example:

1 String name = "Tom"; 2 // This method is not recommended. if the variable name is empty, a null pointer exception occurs. 3 if (name. equals ("Tom") {4 // balabala .... 5} 6 // we recommend that you call the equals method of the String constant "Tom" to avoid NULL pointer exceptions. 7 if ("Tom ". equals (name) {8 // balabala9}

2. For Integer type comparison, you must use equals for comparison. If you use = for comparison, the problem may occur. In-128 ~ In the range of 127, the result of using = and equals for Integer is the same. However, if the result exceeds the range of =, an error occurs. Example:

1 Integer a = 128; 2 Integer B = 128; 3 Integer c = new Integer (127); 4 Integer d = 127; 5 Integer e = 127; 6 System. out. println (". equals (B): "+. equals (B); 7 System. out. println ("a = B:" + (a = B); 8 System. out. println ("d. equals (c): "+ d. equals (c); 9 System. out. println ("d = c:" + (d = c); 10 System. out. println ("d = e:" + (d = e ));

Result:

For specific reasons, please refer to the Java Integer Cache Policy [transfer]. In short, it is in-128 ~ The Integer value between 127, using the instance objects included in the cache, instead of creating a new instance.

 

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.