Directory Summary of Java pitfalls and bugs

Source: Internet
Author: User
Tags case statement deprecated naming convention switch case terminates

A1 Lexical problemsA 1.1 Letter L is similar to the number 1 in many fonts

Rule: in long literal constants, always use uppercase L, never lowercase l. Do not use a lone L as the variable name. Puzzle 4


A 1.2 Negative hexadecimal literal constants that look like positive

Rule: To avoid mixed-type calculations. In the right place, literal constants of type long are substituted for the literal constants of int types. Puzzle 5


A 1.3 octal literal constants are similar to decimal literal constants

Rule: To avoid octal literal constants. If you have to use them, make a note of all the places you use to make your intentions clear. Puzzle 59


A 1.4 Unicode escape character for ASCII characters is easily confusing

Rule: Do not use Unicode escape characters for ASCII characters. If you can, you should use ASCII characters directly. In string literal constants and character literal constants, escape character columns should be preferred rather than Unicode escape characters. Puzzles 14, 16, 17


A 1.5 Backslash must be escaped, even in comments

Rule: If you are writing a system that generates Java source code, you will escape the backslash in the generated character literal constants, string literal constants, and comments. Windows filenames are most likely to cause problems. Puzzles 15, 16


A 1.6 block comment do not nest
Rules use single-line comments to comment out code puzzles 19
A 2 integer OperationA 2.1% operator has a non-0 result with the same positive and negative number as the left operand

Rule: If you need a non-negative remainder, and the result of the% operator is negative, you should add a modulus to the result. Puzzles 1, 64


a 2.2 A sneak overflow of integer operations

Rule: To save the result, including intermediate results, with a sufficiently large type. Puzzles 3, 26, 33, 65


The sign of the difference between a 2.3 int value cannot reliably indicate its size order
Rule: Do not use subtraction-based comparators unless you can be sure that the difference in values will not be greater than ingeter.max_value. Puzzle 65
A 2.4 Compound assignment operator may result in a quiet narrowing transition
Rule: Do not use a compound operator on a variable of type Byte, short, or char. Puzzles 9, 31
A 2.5 integer type asymmetry: Integer.min_value is its own negative value, Long.min_value is the same
Rule: To program conservatively, use long instead of int if necessary. Puzzles 33, 64
A 2.6 shift operator only uses the low of its right-hand operand
Rule: The number of bits to shift should be constant. If the number of bits in the shift must be a variable, then be sure to check if the shift distance is within the allowable range. Puzzle 27
A 2.7 when converting between integer types, perform symbol expansion if the source type is signed
Rule: Be careful when manipulating a numeric value of type Byte, it is signed. To suppress a symbol extension, you can use a bitmask. Puzzle 6
A 3 floating point arithmeticA 3.1 floating-point arithmetic is imprecise
Rule: Do not use floating point where precise results are required, you should use an integer type or BigDecimal.
To avoid circular indexing of floating-point types.
To avoid using the + + and-operators on floating-point variables, these operations have no effect on most floating-point numbers.
Avoid testing whether floating-point values are equal.
Would rather use a double than float. Puzzles 2, 28, 34
A 3.2 nan is not equal to any floating-point value, it also includes itself
Rule: To avoid testing the equality of floating-point numbers. Doing so doesn't always avoid problems, but at least it's a good start. Puzzle 29
A 3.3 conversion from int to float, from long to float, and from long to double is a lossy precision
Rule: To avoid the calculation of integer and floating-point blends. To optimize integer arithmetic instead of floating-point arithmetic. Puzzles 34, 87
A 3.4 BigDecimal (double) constructor returns the exact value of its floating-point parameter
Rule: You should always use the BigDecimal (String) constructor, and never use BigDecimal (double). Puzzle 2
A 4 expression calculationA 4.1 Mixed type calculation is easily confusing
Rule: To avoid mixed-type calculations.
When to put? : When the operator acts on a number operand, the second and third operands use the same numeric type. Prefer to use immutable variables rather than using built-in magic numbers. Puzzles 5, 8, 24
The operand of a 4.2 operator is calculated from left to right
Rule: To avoid assigning values to the same variable multiple times in the same expression. Multi-compound assignment operators in the same expression especially confusing puzzles 7, 25, 42
The priority of a 4.3 operator is not always obvious
Rule: Use parentheses instead of spaces to make the precedence more noticeable. Replace the inline constant expression with the constant quantity of the appliance name. Puzzles 11, 35, 95
A 4.4 operator = = and! = Perform a reference comparison on the wrapped base type
Rule: To force a value comparison, you need to assign or transform an operand to the appropriate base type before comparing it. Puzzle 32
A 4.5 constant volume is inline in the place where it is used
Rule: To avoid exporting constant fields unless they represent true constants that never change. You can use an identity function to turn an expression into a very mass. Puzzle 93
A 4.6 operator & and | Even when a numeric value is acting on a Boolean type, it also calculates its two operands
Rule: To avoid & and | action with Boolean type operands. Be annotated with conscious use. Puzzle 42
A 5 Control FlowA 5.1 Missing break in the switch case statement will cause the control flow to be consistent
Rule: Do not go from one non-empty case to another: a break terminates every non-empty cases. Be annotated with any conscious consistency. Puzzle 23
A 5.2 It is difficult to terminate an int-indexed loop on a integer.max_value
Rule: to terminate an int-indexed loop at Integer.max_value, you need to use a long-type circular index, or you can write the loop very carefully. Puzzle 26
The unexpected completion of a 5.3 finally statement block will mask the pending control transfer
Rule: To ensure that each finally statement block is completed properly to prevent fatal errors. Do not return or throw an exception from a finally statement block. Puzzles 36, 41
A 5.4 Using exceptions for normal control flow will result in bugs and poor performance
Rule: You should only use exceptions for exception cases, never use exceptions for normal control flows. Puzzle 42
Class A 6 initializationa.6.1 class initialization is top-down
Rule: To ensure that static fields are initialized in the proper order. To use inertia initialization to resolve the initialization loop problem, the problem can involve one or more classes. Puzzle 49 52
a.6.2 Onoclassdeffounderror The timing of the appearance is unreliable.
Rule: Do not capture noclassdeffounderror, but you should use reflection and capture classnotfoundexception. More generally, do not capture the error and its subclasses. Puzzle 44
creation and destruction of A.7 instancesThe a.7.1 instance initializer is executed before the constructor method body
Rule: If an instance field of its own type raises recursion during the construction phase, make sure that the recursion terminates. Puzzle 40
a.7.2 calling an overridden method in the constructor causes the method to run before the instance is initialized
Rule: Never call a method that can be overridden in a constructor. To resolve the initialization loop problem with deferred initialization. Puzzle 51
a.7.3 Invalid reference failure causes memory leak
Rule: To be able to invalidate an obsolete object reference in an object that has a long life cycle. Failure to do this can lead to memory leaks, and in a garbage-collected language such as Java, it is more appropriate to say that an unconscious object is reserved.
a.7.4 adding a private constructor fails to instantiate the class
Rule: If you want a class to be non-instantiated, add a private constructor. More generally, you should always provide at least one constructor, and never rely on the default constructor.
The a.7.5 terminator is unpredictable, dangerous, and slow
Rule: to avoid using finalizers.
a.7.6 objects that are cloned can share internal state
Rule: To avoid implementing the Cloneable interface. If you implement it, you should replicate any internal objects that you do not want to share between the object and its clones.
a.8 Other topics related to classes and instancesa.8.1 does not have any dynamic dispatch on the static method
Rule: Never use an expression to qualify a static method call, it should always be qualified with a type. Puzzle 48
a.8.2 inner class is confusing.
Rule: Prioritize using static member classes instead of inner classes. Puzzle 80 89 92
A. 8.3 Can not do protection copy will destroy invariance
Rule: When needed, the input parameters and output values are protected from replication.
a.8.4 implementing an interface can affect the API of the implementation class
Rule: Do not implement an interface that can gain unlimited access to its static fields. Do not write interfaces that consist only of fields, known as constant interfaces. At 5.0 and later, you can use static import as a substitute for the harmful mode of static interface.
a.8.5 int constant is unsafe as an enumeration value
Rule: You should use the enum type, or if you use a version earlier than 5.0, you should implement type-safe enumeration.
a.8.6 mixed use of basic types and parameterized types will weaken the type checking mechanism
Rule: You should eliminate the reported "unchecked" warnings in your code.  Avoid using basic types at 5.0 and beyond. Puzzle 88
A. 8.7 returns null instead of a 0-length array or collection with a tendency to produce errors
Rule: Do not return null from a method that returns an array or collection.
a.9 Name Reusea.9.1 can easily become overloaded when you want to overwrite it.
Rule: Mechanically copy the declaration of each superclass method you want to overwrite, but it's best to let the IDE help.   If you use 5.0, use the @override comment. Puzzle 58
a.9.2 overload parsing rules are not obvious
Rule: to avoid overloading.  If you have two methods in the API that can be applied to some calls, make sure that the two methods have the same behavior on the same argument. Puzzle 11 46 74
a.9.3 hidden entities are difficult to understand
Rule: To avoid hidden puzzles 66 72 92
a.9.4 the process of obscuring entities is difficult to understand
Rule: to avoid shadowing. Do not reuse the names in the Java.lang.Object in the public API.  Do not attempt to use static import on a name that has already been defined. Puzzle 71 73 89
a.9.5 the process of concealing entities is difficult to understand
Rule: to avoid concealment.  To follow the naming convention. Puzzle 68 69
a.9.6 a method that has the same name as the same class looks like a constructor
Rule: To abide by the naming convention. Puzzle 63
a.9.7 procedures for reusing platform class names are difficult to understand
Rule: Avoid reusing the name of the platform class, and never reuse the class name in Java.lang. Puzzle 67
a.10 Stringa.10.1 Array cannot overwrite object.tostring
Rule: For a char array, you should use String.valueof to get the string that represents the specified sequence of characters. For other types of arrays, you should use arrays.tostring, or use Arrays.aslist if you are 5.0 ago. Puzzle 12
a.10.2 String.replaceall as the first argument with a regular expression
Rule: Make sure that the parameter is a valid regular expression, or else use String.Replace instead. Puzzle 20
a.10.3 String.replaceall to replace a string as the second argument
Rule: To make sure that the parameter is a valid permutation string, use String.Replace instead. Puzzle 20
a.10.4 repeated string connections can lead to very poor performance
Rule: To avoid using string connections in loops.
a.10.5 the conversion from a byte array to a character array requires the specified character set
Rule: When converting a byte array into a string or a char array, always select a character set; If you do not, you will use the default character set of the platform, leading to unpredictable behavior. Puzzle 18
The a.10.6 char type value will only be converted by default from int, not string
Rule: To convert a char to a string, you should use String.valueof (char). Puzzle 11 23
A One-I/Oa.11.1 Stream.Close can throw IOException exceptions
Rule: To catch an exception on close, and the general practice is to ignore these exceptions. Puzzle 41
a.11.2 printstream.write (int) does not flush the output stream
Rule: To avoid using printstream.write (int). If you use it, call flush when you need to. Puzzle 81
a.11.3 to consume the output of a process, or the process may hang
Rule: You should always consume the output of the process you are creating. Puzzle 82
A 12 Threada.12.1 Call Thread.run cannot start a thread.
Rule: Never call Thread.run. Puzzle 76
a.12.2 Library classes may lock or notify instances of them
Rule: If you are extending a library class, do not use instance locks. Instead, you should use a separate lock object that is stored in a private field. Puzzle 77
a,12,3 thread.interrupted will clear the interrupt state
Rule: Do not use thread.interrupted unless you want to clear the interrupt state of the current thread. Puzzle 84
Locks for this class will be held during initialization of the a.12.4 class
Rule: To avoid the risk of deadlock, never wait for a background thread during class initialization. Puzzle 85
a.12.5 synchronization fails when sharing mutable state, which can cause changes in the observed state
Rule: To synchronize access to the mutable state of the share.
a.12.6 calling an external method in a synchronized statement block may result in a deadlock
Rule: Never give control flow to an external method that is called in a synchronized method or block of statements.
a.12.7 calling the wait method outside the while loop causes unpredictable behavior
Rule: Never call wait outside of a while loop.
a.12.8 dependency on thread scheduler can lead to erratic and platform-dependent behavior
Rule: In order to write robust, responsive, and portable multithreaded programs, you should ensure that only a handful of threads are operational at any given moment.
A 13 Reflectiona.13.1 Reflection checks access to the class to which the entity and entity belongs
Rule: Instantiate a class with reflection and access the instance with an interface. Puzzle 78
a.13.2 instantiating an inner class with reflection requires an extra parameter
Rule: Do not use reflection on inner classes. The use of static member classes rather than inner classes is preferred. Puzzle 80
a.13.3 Class.newinstance can throw an undeclared checked exception
Rule: You should use java.lang.reflact.Constructor.newInstance instead of class.newinstance whenever there is any possibility that the constructor will throw a check exception. Puzzle 43
serialization of A 14a.14.1 let a class serializable introduce a common pseudo-constructor
Rule: Be sure to think twice a class before it can be serialized. Be sure to think twice before accepting the default ReadObject method. When writing the ReadObject method, protective measures are taken.
a.14.2 serialization form is part of the public API of a class
Rule: When designing a serialization form, you should be careful as you design any other API.
a.14.3 uses the default serialization form to expose private fields in the class's public API
Rule: You should consider using some sort of custom serialization format
a.14.4 using the default serialization form may result in poor performance
Rule: You should consider using some kind of custom serialization format.
a.14.5 maintaining an instance-controlled invariant rule requires a Readresolve method
Rule: You should always write a readresolve method for Singleton, self-compiled type-safe enumeration types, and instantiated classes controlled by other instances. Puzzle 83
a.14.6 declaring a sequence version UID failure can cause fragility.
Rule: an explicit sequence version UID should be declared in a serializable class.
a.14.7 an object that deserializes a loop may cause a crash if readobject or Readresolve calls an overridden method
Rule: If a hashset, HashMap, or Hashtable is to be serialized, make sure its contents are not returned to be referenced to it.   In the ReadObject and Readresolve methods, to avoid calling methods on objects that are currently being serialized, if you are unable to follow this advice, make sure that there are no problematic loops in the object graph. Puzzle 91
A 15 Other librariesa.15.1 overriding the Equals method without overwriting the Hashcode method may cause erratic behavior
Rule: When overriding the Equals method, always overwrite the Hashcode method puzzle 57
a.15.2 Calendar and date are poorly designed.
Rule: Be sure to refer to the API documentation when using calendar and date.
a.15.3 many classes, regardless of their method name, are immutable
Rules: Do not be misled to consider immutable types to be mutable, immutable types include string, Integer,long,short, Byte, Character, Boolean, Float, Double, BigInteger, BigDecimal. Puzzle 56
a.15.4 some deprecated methods are poison to the program.
Rule: Avoid using methods that have been deprecated, such as Thread.stop,thread.suspend, Oruntime.runfianlizersnexit, and System.runfianlizeronexit. Puzzle 39 43
A.15.5 using a self-compiled solution rather than a library can lead to effort wasted, bug-generated, and very poor performance

Rule: To understand and use library Puzzles 60 62 94.



Directory Summary of Java pitfalls and bugs

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.