Java Code Optimization Series (i) Opening monument

Source: Internet
Author: User

Reprint Please specify Source:http://blog.csdn.net/lhy_ycu/article/details/45506549


Before you begin, add the use of the instanceof keyword in the Java Learning Series and its pitfalls. Brief description: Instanceof is a simple two-dollar operator that is used to determine whether an object is an instance of a class. As long as the instanceof left and right operands have inherited or implemented relationships, the program can be compiled and passed. Here is a simple example to illustrate the use of the instanceof keyword and its pitfalls:

Class A<t> {public boolean isdateinstance (T t) {return T instanceof Date;}} public class Instanceoftest {public static void main (string[] args) {//True. A string object is an object instance (the object in Java is the parent class of all classes) System.out.println ("Zhangsan" instanceof object);//False. Object is a parent class whose objects are clearly not an instance of the String class System.out.println (New Object () instanceof string);//True. A string object is an instance of string System.out.println (new string () instanceof string);//compilation does not pass. ' A ' is a char type, which is the base type//System.out.println (' a ' instanceof Character);//False. As long as the left operand is null (essentially untyped), the result is a direct return of FALSESYSTEM.OUT.PRINTLN (null instanceof String);//False. Even a null strong turn is a nullSystem.out.println (string) null instanceof String);//compilation does not pass. Because Date and String do not inherit or implement the relationship//System.out.println (New Date () instanceof String);//False. When the code is translated into bytecode, T is already an object type, because a "lisi" argument string is passed, so T is actually a string type. System.out.println (New A (). Isdateinstance ("Lisi"));}}
"Note" instanceof can only be used for object judgments and cannot be used for basic types of judgments.

Let's start with the topic, starting with a self-increasing trap.

1) Self-increasing traps

int num = 0;for (int i = 0; i <; i++) {num = num++;} SYSTEM.OUT.PRINTLN ("num =" + num);
What is the print result? The answer is 0, why? Let's take a look at the execution steps, the procedure for the first cycle is as follows: The JVM copies the num value (0) to the temporary variable area, then the NUM value is 1, the value of NUM is 1, then returns the value of the temporary variable area, note that the value is 1 unmodified, and the return value is assigned to Num. At this point the value of NUM is reset to 0. In short, int temp = num; num + = 1; return temp; These 3 steps. So the result of the printing is still 0,num to keep the original state.

Optimization: Will num=num++; Modify to num++.


2) constants into variables?

Can you think of a constant as a variable? The answer is that it is possible, but the practice is not recognized.

public static final int rand_const = new Random (). Nextint ();p ublic static void Main (string[] args) {//by printing several times, you can see that the result has changed, i.e. It is said that constants are not guaranteed to remain constant at the time of definition System.out.println ("constant quantity?"). "+ Rand_const);}
Optimization Recommendations: Be sure that the value of the constant remains unchanged at run time, so that rand_const can be assigned to write dead directly at the time of definition.


3) "L" Can you see if the letter is uppercase of I, number 1, or lowercase letter l?

public static  long L = 11;

optimization: letter suffix L try to capitalize L


4) The type of the three mesh operator is inconsistent?

int i = 70; System.out.println (i < 100? 80:90);
The results of the print unexpectedly, the result is 80.0, this is why? I<100 is true, but because the last operand is 90.0, which is a floating-point number, the compiler converts the second operand 80 to 80.0 floating-point numbers, unifies the result type, and prints the result to 80.0.
optimization: 90.0 change to

5) Do not overload the method containing variable-length parameters

Brief description: The variable-length parameter must be the last parameter of the method, and a method cannot define multiple variable-length parameters.

public class Test01 {public static void Fruitprice (int price, int. discount) {Float Realprice = Price * Discount/100.0f;s YSTEM.OUT.PRINTLN ("Non-variable length parameter results: Realprice =" + Realprice);} public static void Fruitprice (int price, int ... discounts) {Float Realprice = price;for (int discount:discounts) {REALPR Ice = Price * discount/100.0f;} SYSTEM.OUT.PRINTLN ("Variable length parameter results: Realprice =" + Realprice);} public static void Main (string[] args) {Fruitprice (48888, 85);}}
What is the print result? The answer is: the result of the non-variable length parameter: Realprice = 41554.8, that is, the program executes the first method, and does not execute the variable-length parameter method, which is why? Because Java at compile time, the first will be processed according to the number and type of arguments (here are the 2 arguments that are all int types, note that it is not turned into an int array), that is, to find the fruitprice (int price, int discount) method, and confirm that it conforms to the method signature condition, because the compiler also loves "lazy", so the program executes the first method.

Reference: "Writing high-quality Code" mechanical industry Press



Java Code Optimization Series (i) Opening monument

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.