Do you understand all the six major Java problems?

Source: Internet
Author: User

These questions are required for anyone who seriously studies java. Of course, if you are just a beginner, you do not need to be so strict. If you think you are a beginner, but you do not understand these problems very well. Please repeat yourself as a beginner.


I. How to initialize it!


This topic is discussedVariable InitializationSo let's take a look.JavaWhich typesVariable.


1. Class Attribute, or value range


2. Local variables in the Method


3. For the first variable, the Java Virtual Machine will automatically initialize the method parameters. If an initial value is given, the initialization is the initial value. If not, initialize it as the default initial value of the type variable.


The default value of all object reference type variables is null, that is, they do not point to any object. Note that the array itself is also an object, so the value of the uninitialized array reference after automatic Initialization is also null. for two different class attributes, static attributes and instance attributes, the initialization time is different. The instance attribute is initialized when an instance is created. The static attribute is initialized when the class is loaded, that is, the class is used for the first time. The subsequent instance creation is not initialized again. This issue will be discussed in detail in future series. The second type of variables must be explicitly initialized. If you try to use it before initialization, the compiler will protest. If the initialization statement is in the try block or if block, it must be assigned a value before it is used for the first time. That is to say, the compiler will protest when placing the initialization statement in the condition judgment statement that only contains the if block, because the execution may not meet the judgment condition after the if block, in this way, the initialization statement will not be executed, which violates the requirements that must be initialized before local variables are used. However, if there is an initialization statement in the else block, you can compile it, because in any case, at least one initialization statement will be executed and will not be initialized before use. The same applies to try-catch. If there is an initialization statement only in the try block, the compilation department will pass. If it is in catch or finally, it can be compiled. In short, make sure that the local variables are initialized before use. Therefore, a good practice is to initialize them when declaring them. If you don't know what the values will be, use the default values above! In fact, the third and second variables are essentially the same. They are all local variables in the method. But as a parameter, it must have been initialized. The input value is the initial value, so Initialization is not required.


2. What is instanceof?


Instanceof is a binary operator of Java. It is the same class as =, >,<. Because it is composed of letters, it is also a reserved keyword of Java. It is used to test whether the object on the left is an instance of the class on the right of the object and return boolean data. However, this approach is generally considered to be failing to take advantage of object-oriented polymorphism. In fact, the above functional requirements can be fully implemented by using method overloading, which is an appropriate approach for object-oriented development and avoids returning to the structured programming mode. You only need to provide two methods with the same name and return value, and accept different parameter types. Therefore, using instanceof is not recommended in most cases, and polymorphism should be well utilized.

  Iii. What are the differences between the "=" and equals methods?


= The operator is used to compare whether the values of variables are equal. It is better understood that, according to the previous post, object variables are actually a reference and their values point to the memory address of the object, rather than the object itself. Both a and B use the new operator, which means that two strings with content "foo" will be generated in the memory. Since they are "two" strings, they are naturally located at different memory addresses. The values of a and B are actually two different memory address values. Therefore, the result is false when the "=" operator is used. it is true that the content of objects a and B is "foo" and should be "equal", but the = operator does not involve the comparison of object content. The comparison of object content is exactly what the equals method does. Let's take a look at how the equals method of the Object is implemented:


Boolean equals (Object o ){


Return this = o ;}


The = Operator is used by default for Object objects. Therefore, if your own class does not overwrite the equals method, you will get the same result when using equals and =. We can also see that the equals method of the Object does not meet the goal that the equals method should achieve: compare whether the content of the two objects is equal. Because the answer should be determined by the class creator, the Object leaves this task to the class creator. Therefore, when you use the equals method to determine whether the object content is equal, do not take it for granted. Because you may think they are equal, and the authors of this class do not think so, and the implementation of the equals method of the class is controlled by him. If you need to use the equals method or any hash code-based set (HashSet, HashMap, HashTable ), check the java doc to see how the equals logic of this class is implemented. [Nextpage]


4. What are the final keywords modified?


Final makes the modified variable "unchanged", but because the object type variable is essentially "Reference", "unchanged" also has two meanings: The reference itself remains unchanged, and the referenced object.


The reference itself remains unchanged:


Final StringBuffer a = new StringBuffer ("immutable ");


Final StringBuffer B = new StringBuffer ("not immutable ");


A = B; // compilation Error


The referenced object remains unchanged:


Final StringBuffer a = new StringBuffer ("immutable ");


A. append ("broken !"); // Compiled


It can be seen that final is only valid for the referenced "value", which forces the reference to point only to the object initially pointed to. changing its direction will lead to compilation errors. Final is not responsible for the changes to the objects it points. This is similar to the = Operator: = Operator is only responsible for the equal value of the referenced "value". As to whether the content of the object pointed to by this address is equal, the = operator does not matter. Understanding final issues has important meanings. Many program vulnerabilities are based on this ---- final can only ensure that the reference always points to a fixed object, but cannot ensure that the state of that object remains unchanged. In multi-threaded operations, an object will be shared or modified by multiple threads. Unintentional modifications made by one thread to the object may cause another thread to crash. The solution to an error is to declare the object as final when it is created, so that it is "never changed". In fact, it is futile.

  5. What did I declare!


Many people have done such a thing, but what have we declared? The answer is usually a String with the content "Hello world !". Fuzzy answers are usually the root cause of unclear concepts. If you want to answer the question accurately, half of them will probably make a wrong answer. This statement declares a reference pointing to an object named "s". It can point to any object of the String type and currently points to "Hello world !" This String type object. This is what actually happens. We didn't declare a String object. We just declared a reference variable that can only point to the String object. Therefore, if we run another sentence after the statement: String string = s; we declare another reference that can only point to the String object, named string, no second object is generated. string still points to the original object, that is, and s points to the same object.


6. Have the String changed?


No. Because String is designed as an immutable class, all its objects are immutable objects. See the following code:


String s = "Hello ";


S = s + "world !";


Is the object pointed to by s changed? It is easy to draw this conclusion from the first article in this series. Let's see what happened. In this Code, s originally points to a String object with the content "Hello". Then we perform the + operation on s. Does the object s points to change? The answer is no. At this time, s does not point to the original object, but points to another String object with the content "Hello world !", The original object still exists in the memory, but the reference variable s no longer points to it. Through the above description, we can easily draw another conclusion, if you often make various modifications to the string, or make unforeseen modifications, therefore, using String to represent strings will cause a large memory overhead. Because the String object cannot be changed after it is created, a String object is required for each different String. In this case, you should consider using the StringBuffer class, which allows modification, instead of generating a new object for each different string. In addition, the conversion between the two types of objects is very easy. At the same time, we can also know that if you want to use a String with the same content, you do not have to create a new String every time. for example, we need to initialize a String reference variable named s in the constructor and set it as the initial value. We should do this:


Public class Demo {


Private String s;


Public Demo {


S = "Initial Value ";}


}


Rather


S = new String ("Initial Value ");


The latter calls the constructor every time to generate a new object, which has low performance and high memory overhead and has no significance. Because the String object cannot be changed, for strings with the same content, it can be expressed as long as a String object. That is to say, the constructor above is called multiple times to create multiple objects, and their String type attribute s points to the same object. The above conclusion is based on the fact that for String constants, if the content is the same, Java considers them to represent the same String object. Using the new keyword to call the constructor always creates a new object, regardless of whether the content is the same or not. The reason for designing a String class as an immutable class is determined by its purpose. In fact, classes in many Java standard library are not variable. When developing a system, we sometimes need to design immutable classes to pass a set of related values, which is also the embodiment of Object-oriented thinking. The immutable class has some advantages. For example, because its object is read-only, concurrent multi-thread access will not have any problems. Of course, there are also some shortcomings. For example, each State must be represented by an object, which may cause performance problems. Therefore, the Java standard library also provides a variable version, namely, StringBuffer.


Finally, some java technologies, including EJB3.0, can be learned. Compared with the three lightweight frameworks, EJB is a well-deserved heavyweight.

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.