151 recommendations for writing high-quality code to improve Java programs

Source: Internet
Author: User

Example 1: The trap of the ternary operator
1 int i =n; 2 String str1 = string.valueof (i < 90:100); 3 String str2 = string.valueof (i < 90:100.0); 4 System.out.println (STR1); // Output: 5 System.out.println (STR2); // Output: 90.0
When you use the ternary operator and the type of the operands on both sides is inconsistent, this involves the conversion rule of the ternary operator:
    1. If two operands are not convertible, no conversion is done and the return value is object type;
    2. If the two operand is an expression of a definite type (such as a variable), it is converted according to the normal binary number. The int type is converted to a long type, and the long type is converted to float type;
    3. If one of the two operands is a number s and the other is an expression, and its type is T, then if the number S is in the range of T, then the T is converted to type "T", and if s exceeds the range of T, it is converted to S type;
    4. If the number of two operations is a number. The return value type is the larger of the range.

Example 2: A trap about self-increment

1 int count = 0; 2  for (int i=0; i<=100; i++) {3     count = count++; 4 }5 System.out.println ("Count =" + count); // output: Count = 0

"Count = count++" in the body of the loop; The detailed processing steps for the first execution of the statement are as follows:

    1. The JVM copies the count value (0 at this time) to the temporary variable area;
    2. Add the value of Count to 1 (this is 1);
    3. Returns the value of the temporary variable area (0 at this time);
    4. Assigns the return value to count (that is, count is assigned a value of 0).

The expression in code is equivalent to the following statement:

1  Public Static int mockadd (int  count) {2     int temp = count; 3     Count = count + 1; 4     return temp; 5 }

However, in C + +, "Count = count++" is equivalent to "count++" and PHP is the same as Java (not equivalent)

Example 3: How to deal with the variable business with JS script
1 // JS Code 2 var factor; 3 function formula (VAR1, var2) {4     return var1 + var2 * factor; 5 }
1 //Java Code2 intFirst = 11;3 intSecond = 22;4String FilePath = "D:/test.js";5Scriptenginemanager Manager =NewScriptenginemanager ();6 //get a JavaScript execution engine7ScriptEngine engine = Manager.getenginebyname ("javascript");8 //Establishing context Variables9Bindings bind =engine.createbindings ();Ten //assign a value to a parameter in the JS file OneBind.put ("factor", 5); A //binding context, scope is current engine scope - engine.setbindings (Bind, scriptcontext.engine_scope); -FileReader FR =NewFileReader (filePath); theEngine.eval (FR);//Execute JS Code - //determine if the method is callable - if(Engineinstanceofinvocable) { -Invocable invocable =(invocable) engine; +Double result = (double) invocable.invokefunction ("formula", First, - second); +SYSTEM.OUT.PRINTLN ("Result of operation:" +Result.intvalue ()); A}
Example 5: Use of the instanceof method
1 Importjava.util.Date;2  3  Public classInstanceofdemo {4      Public Static voidMain (string[] args) {5System.out.println ("Sting"instanceofObject);//Output: True6         //Parse: "String" is a string, and the string inherits the object7         /***********************************/8  9System.out.println (NewString ()instanceofString);//Output: TrueTen         //Analysis: An object of a class is, of course, an instance of it One         /***********************************/ A   -System.out.println (NewObject ()instanceofString);//Output: False -         //parsing: Object is a parent class whose objects are certainly not instances of the string class.  the         //It is important to note that this statement was compiled, because as long as the left and right two operands of the instanceof keyword have inheritance or implementation relationships, you can compile the -         /***********************************/ -   -System.out.println (NULL instanceofString);//Output: False +         //Analysis: instanceof Unique rules: If the left operand is null, the result will be returned directly false, do not need to judge what the right operand of the operation is, similar to the short-circuit operation.  -         //therefore, when using the instanceof operator, it is not necessary to care about whether the class being judged (that is, the left operand) is null, unlike the Equals and ToString methods we often use.  +         /***********************************/ A   atSystem.out.println (String)NULL instanceofString);//Output: False -         //Analysis: Do not look at a coercion type conversion to consider the result to be true. Because NULL is a universal type, it can also be said to have no type, even if a type conversion is a null -         /***********************************/ -   -System.out.println (' A 'instanceofCharacter);//Compile Error -         //Analysis: in         //because ' a ' is a char type, which is a basic type, not an object, instanceof can only be used for object judgments and cannot be used for basic types of judgments, so compile an error -         /***********************************/ to   +System.out.println (NewDate ()instanceofString);//Compile Error -         //Analysis: Because the date class and string do not inherit or implement the relationship, so at compile time directly to the error, the instanceof operator must have the left and right operand inheritance or implementation of the relationship, otherwise it will compile does not pass the         /***********************************/ *   $System.out.println (NewGenericclass<string> (). Isdateinstance ("test"));//Output: FalsePanax Notoginseng         //Analysis: Here T is a string type, there is no inheritance or implementation relationship with Date, why is the statement "return T instanceof Date" compiled?  -         //because Java generics are for encoding services, when the code is translated into bytecode, T is already an object type, the passed argument is a string type, that is, the surface type of T is object, the actual type is string the         //So, the "return T instanceof Date" statement here is equivalent to "return Object instanceof Date". +     } A } the   + classGenericclass<t> { -     //determine if it is a date type $      Public Booleanisdateinstance (T t) { $         returnTinstanceofDate; -     } -}

151 recommendations for writing high-quality code to improve Java programs

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.