Common Mistakes and details of Java and common mistakes of Java

Source: Internet
Author: User

Common Mistakes and details of Java and common mistakes of Java

Transferred from the Internet

I stayed in books all day yesterday. I was very disappointed to find some books to learn "Regular Expressions". I didn't find any books with such content. I found a book "in-depth analysis of Java", which involves many misunderstandings that I didn't pay attention to at ordinary times. I may not be able to use it during development, but I cannot blur these concepts. The content in the book is still very useful. Here I summarize some notes.

GotoStatement. Because it is widely usedgotoThe statement reduces the readability and maintainability of the program.goto. At the same time, to prevent programmers from usinggotoThe Java language is stillgotoIt is defined as a keyword, but no syntax is defined, so it is called "reserved word ".

2true,falseAndnullAlthough it is displayed in different colors in IDE,But it is not a keyword, but a "literal constant", AndStringTypeabcSame.

3. Avoid using the name whenever possible.$BecauseWhen the compiler compiles the. java file, it will compile "$" into a connector between the top-level type and the bottom-layer type.See the following example:

Use $ to define variable names

package com.laixintao.Test;public class Outer$Inner {  public static void main(String[] args) {    Outer o = new Outer();    Outer.Inner i = o.new Inner();    i.innerPrint();  }}class Outer {  class Inner {    void innerPrint() {      System.out.println("Inner Print!");    }  }}

Packagecom. laixintao. Test;

PublicclassOuter $ Inner {

Publicstaticvoidmain (String [] args ){

Outero = newOuter ();

Outer. Inneri = o. newInner ();

I. innerPrint ();

} ClassOuter {

ClassInner {

VoidinnerPrint (){

System. out. println ("Inner Print! ");

}}}

During compilation (javac Test3.java) During this code, the compiler reports the following error:Test. java: 12: Error: repeated class: com. laixintao. Test. Outer. Inner class Inner {^

4Unicode escape characters are processed very early before the parsing program.For example:

Unicode compilation Error

// char c1 = '\u00a';// char c2 = '\u00d';

// Char c1 = '\ u00a ';

// Char c2 = '\ u00d ';

The code compilation error of these two lines appears in the program. These two Unicode codes respectively represent "line feed" and "Carriage Return". Therefore, the Code is as follows during compiler Compilation:

Unicode Compilation

// char c1 = '';// char c2 = '';
// Char c1 = ''; // char c2 = '';

5 Unicode Code uses 16-bit encoding, and is used in JavacharType. Now Unicode has been extended to 1 million characters, and more than 16 characters are allowed to be added.All supplementary characters cannot be expressed by character constants.

Whenshort,byte,charThe result isintType, rather than higher types.

If the variable isbyte,short,byteType. When a constant in the compilation period is assigned to it, and the constant does not exceed the value range of the variable, the compiler can perform implicit contraction conversion. This implicit contraction conversion is safe, because it only applies to the value assignment of variables, not to the method call statement, that is, it is not applicable to parameter passing during method calls. (For details, refer to the small problem of default type conversion in java)

7. NotecharType. This is an unsigned type. Therefore,charAndshortOrcharAndbyteType conversion must be displayed. SlavebyteTocharTo extend the contraction conversion, this conversion is special, that is, firstbyteExtended conversionintAnd then contractchar.

8. In the extended conversion between integer datacharType (unsigned type), the extension bit is 0. If the operand isbyte,shortOrint(Signed type), the extension bit is the signed bit of the variable.

9. the contraction and conversion between integer data only truncates and discards the high value without any other processing. 10.1 + 0.2 is not equal to 0.3.System.out.println((double)0.1+(double)0.2);The output result of this statement is // http://www.pprar.com0.30000000000000004. Because the computer uses binary to store data, and many decimal places cannot be accurately expressed using binary (in fact, most decimal places are close ), just as the decimal number cannot accurately represent a score of 1/3. Most floating point models only store their values in an approximate way in a computer, rather than accurately storing them as an integer. Another example is an endless loop:for(float f = 10.1f;f != 11;f+=0.1f){}

10floatType can be retained 7 ~ 8 Valid numbers, whiledoubleType can be retained for 15 ~ 16 valid numbers, so whenintThe value of the type or long type is greaterdoubleOrfloatWhen the number is valid, some of the lowest valid bits of this value will be lost, resulting in loss of precision. In this case, the latest round-off mode of IEEE754 will be used, extract the closest floating point value to this integer.Although integer-to-Floating Point conversion is an extended conversion, when the value is large or small (the absolute value is large), it will produce a certain loss of precision.

11i+++jHow to calculate? (This issue is not significant in C/C ++), because C/C ++ depends on the hardware structure of the implementation, and the results of different environments will also be different. However, in Java, this result is fixed and is not affected by the running hardware environment and platform.) A: According to greedy rules, the front ++ is better than the back ++. The result is:(i++)+j

12I ++ and I are both first + 1 and then assigned a value.++ I, nothing to say; I ++,j=i++;For example, the underlying implementation is as follows:temp = i;i = i + 1; j = temp;So,i=15;i=i++;The result of this expression is 15. (because a value assignment is executed after adding one, it is changed from 16 to 15)

13 + 0 and-0 are different in the storage of floating point variables. When-0 and + 0 are involved in floating point operations (for example, division and remainder operations), different results can be produced.

14 The Division and Division operations of floating point are different from those of integer types. When the division is 0, the floating point operation will not generateArithmeticExceptionException.

15StringA class is a non-mutable class. Once an object is created, it cannot be destroyed.StringThe methods that seem to modify the character sequence are actually returned to the newly createdStringObject instead of modifying its own object.

16 becauseStringObjects cannot be changed, so they have thread security and can be shared freely.

17 InStringClass, is to use a character array (char[]) To maintain the character sequence.StringThe maximum length is the maximum length of the character array. Theoretically, the maximum length is the maximum value of the int type, that is, 2147483647. In practice, the maximum value that can be obtained is generally smaller than the theoretical maximum value.

18main()Methods are similar to other methods in their behavior. They can be reloaded and called, inherited, hidden, or thrown with type parameters. We can also call it through reflection in a program.Main Method(Or other methods ). 2 when the names of two or more methods are the same and the parameter list is different, these methods constitute an overload. The overload method can be distinguished based on the type corresponding to the parameter list and the number of parameters. However, the parameter name and return type of the method, the exception list and type parameter of a method cannot be used as a condition to distinguish between overloaded methods.

19. The order of method calls is as follows:

  • In the first stage, automatic packing (unpacking) and variable parameters are not taken into consideration. You can search for methods that match the actual parameter type and have the same number of parameters as the actual parameter;
  • If no matching method exists in step 1, automatic packing and unpacking will be performed in Phase 2.
  • If there is no qualified method in step 2, the variable parameter method will be considered in stage 3.
  • If no matching method is found in the three phases, a compilation error occurs. If there is more than one method, the most specific method will be selected. The most explicit method is defined as: if the list type of the form parameter corresponding to method A can be assigned to the list type of the form parameter of Method B, method A is clearer than method B. If the most explicit method cannot be selected, a compilation error occurs.

20 The essential difference between rewriting and hiding is that rewriting is dynamically bound, and the member of the relevant class is called according to the actual type of the object to which the runtime reference points. While hiding is static binding, it depends on the static type referenced during compilation to determine the relevant members of the call. In other words, if the subclass overrides the method of the parent class, when the reference of the parent class points to the subclass object, it calls the subclass method through the reference of the parent class. If the subclass hides the parent class method (member variable), the method (member variable) of the parent class is called through the reference of the parent class ).

21 The constructor is called recursively. The constructor of the subclass calls the constructor of the parent class until the constructor of the Object class is called.

22. The constructor does not create objects. The constructor is called by the system when the new object is used to initialize instance members of the class. In order, first create an object and then call the constructor.(The constructor does not generate new objects)

23 The default constructor is not empty. The constructor calls the non-argument constructor of the parent class and may execute initialization of instance member variables. Therefore, the default constructor calls at least the constructor of the parent class. It may do more work, including declaring initialization of instance variables and instance initialization blocks, all are executed in the constructor.

24 when = or! = The two operands of the operator are of the basic data type, and the other is the reference type of the packaging class, then compare the values of the two basic data types to see if they are equal.

25 in Java, arrays are also classes. The referenced variables declared by arrays point to objects of the array type. All arrays inheritObjectClass, and implementsjava.lang.CloneableAndjava.io.SerializableInterface. The elements of the array include variables.length(Implicitly) it is a member inherited from the Object class.CloneableAndSerializableIs two marked interfaces, which do not explicitly declare any members.

26 The interface is completely abstract and cannot be instantiated. UsenewThe method used to create an excuse type is actually to create an anonymous class, which implements the interface type.

27 if the two interfaces declare the same variable x, when an interface inherits the two interfaces at the same time or a certain class simultaneously implements the two interfaces, access through simple names will generate a compilation error.

28 if the method m with the same name is declared in the two interfaces, and the two methods do not constitute an overload, when an interface can inherit both interfaces at the same time, or a certain class can inherit both interfaces at the same time, A Method signature must exist so that the signature is both a sub-signature of two m-methods, and a type must exist in the return type of the method, so that this type is the replaceable type of the return type of both m methods.


Java FAQ

CLASSPATH.; E: \ jdk \ lib \ tools. jar; E: \ jdk \ lib \ dt. jar
PATH.; E: \ jdk \ bin

Note that there is a.; in front of it to indicate the root directory. You can add it.

Your file name should be HelloWorld. java, not Welcome. java

I also use Windows 7, so there will be no conflict.

Use javac Welcome. java first
Then use java Welcome

If javac succeeds and java errors are shown in screenshots, there are two possible errors:
1. Your class name and file name are inconsistent;
2. Your environment variable configuration is incorrect:

Assume that the JDK installation path is E: \ jdk,
Add the following variables and attribute values to the system variables.
CLASSPATH.; E: \ jdk \ lib \ tools. jar; E: \ jdk \ lib \ dt. jar
PATH.; E: \ jdk \ bin

Hope to help you ~!

Java FAQ

Classpath
In the advanced tutorial, we use polymorphism.
J2ee is mvc. Develop a framework by yourself

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.