Do you understand the six major problems in Java?

Source: Internet
Author: User

These questions for the serious study of Java people must know, of course, if you are only a beginner is not necessary so strict, if you think you have surpassed the beginner, but do not understand these problems, please return yourself to the ranks of beginners.

  First, exactly how to initialize!

This question discusses the initialization of variables, so first look at what kinds of variables are in Java.

1. Properties of the class, or domain name

2. Local variables in the method

3. Method parameters for the first variable, the Java virtual opportunity is automatically initialized. If the initial value is given, it is initialized to that initial value. If not given, it is initialized to the default initial value of the type variable.

The default initial value of all object reference type variables is null, that is, no object is pointed to. Note that the array itself is also an object, so an array reference that is not initialized is also null after auto-initialization. For two different class properties, the static property is different from the instance property when it is initialized. The instance property is initialized when the instance is created, and the static property is initialized when the class is loaded, that is, when the class is first used, and is not initialized again for subsequent instance creation. This issue will be discussed in detail in a later series. For the second variable, it must be explicitly initialized. If you try to use it before it is initialized, the compiler will protest. If the initialized statement is in a try block or an if block, it must be assigned before the first use. That is, the compiler will also protest if the initialization statement is placed in a conditional judgment statement with only the If block, because execution may not conform to the judgment condition after the IF, so that the initialization statement is not executed, which violates the requirement that the local variable must be initialized before it is used. However, if there are initialization statements in the else block, it can be compiled, because at least one initialization statement will be executed in any case, and nothing that has not been initialized before use will occur. The same is true for Try-catch, if the initialization statement is only in the try block, the compilation department passes. If it is also in catch or finally, it can be compiled. In conclusion, it is important to ensure that local variables are initialized before they are used. So, a good practice is to initialize them when declaring them, and if you don't know what the value is, use the default value above! In fact, the third variable is essentially the same as the second, which is a local variable in the method. Just as a parameter, it must have been initialized, the value passed in is the initial value, so it does not need to be initialized.

  Second, what is instanceof?

Instanceof is a Java two-dollar operator, and ==,>,< is the same kind of stuff. Because it is made up of letters, it is also a reserved keyword for java. Its purpose is to test whether the object on its left is an instance of the class to the right of it, returning a Boolean type of data. However, this practice is often thought of as not taking good advantage of the polymorphism in object-oriented. In fact, the above function requires a method overload can be fully implemented, this is an object-oriented approach should be done to avoid back to the structured programming mode. As long as two names and return values are the same, the method of accepting different parameter types is fine: Therefore, using instanceof is not a recommended practice in most cases, so use polymorphism.

  What is the difference between the "= =" and the Equals method?

The = = operator is specifically used to compare the values of variables for equality. The good thing to understand is that, according to the previous post, an object variable is actually a reference, and their value is pointing to the memory address where the object resides, not the object itself. Both A and B use the new operator, which means that two strings of "Foo" will be generated in memory, and since they are "two", they naturally reside in different memory addresses. The values of A and B are actually two different memory address values, so using the "= =" operator, the result will be false. Admittedly, the objects referred to in A and B are "foo" and should be "equal", but the = = operator does not involve comparisons of object content. The comparison of object content is exactly what the Equals method does. Take a look at how the Equals method for object objects is implemented:

Boolean equals (Object o) {

return this==o;}

The = = operator is used by default for object objects. So if your own class does not overwrite the Equals method, then your class will get the same result using equals and using = =. It is also possible to see that the Equals method of object does not meet the goal of the Equals method: to compare the contents of two objects for equality. Because the answer should be determined by the creator of the class, object leaves the task to the creator of the class. So don't take it for granted when you're using the Equals method to determine whether the object's contents are equal. Because you may think of equality, and the author of this class does not think so, and the implementation of the Equals method of the class is in his hands. If you need to use the Equals method, or use any hash-based collection (hashset,hashmap,hashtable), look at the Java doc to see how the Equals logic of this class is implemented. [NextPage]

  What exactly does the final keyword modify?

Final makes the modified variable "unchanged", but because the nature of the object-type variable is "Reference", there are two meanings to "invariant": the invariant of the reference itself, and the object that the reference points to is unchanged.

The reference itself does not change:

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

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

a=b;//Compile-time error

The object that the reference points to is the same:

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

A.append ("broken!"); /Compile Through

As you can see, final is only valid for the reference "value", forcing the reference to point only to the object that was initially pointed to, and changing its point to cause a compile-time error. Final is not responsible for the change in the object it points to. This is similar to the = = Operator: the = = operator is only responsible for the reference "value" equality, as to whether the address points to the object content is equal, the = = operator is no matter. Understanding the final question has a very important meaning. Many program vulnerabilities are based on this----final can only guarantee that a reference will always point to a fixed object, and that the state of that object is not guaranteed to be constant. In multi-threaded operations, an object is shared or modified by multiple threads, and a thread's unconscious modification of an object can cause another thread that uses this object to crash. One of the wrong solutions is to declare this object as final when it is newly created, with the intention of making it "never change". In fact, it was futile.

  Five, I declare what!

Many people have done this kind of thing, but what exactly do we declare? The answer is usually: a string with the content "Hello world!". Such vague answers are often the source of unclear concepts. If you want an accurate answer, half of the people will probably answer the wrong question. This statement declares a reference to an object named "S", which can point to any object of type string, currently pointing to "Hello world!" The object of this string type. This is what really happens. We do not declare a string object, we simply declare a reference variable that can only point to a string object. So, if after that sentence, if you run another sentence: string string = s; We declare another reference that can only point to a String object, named String, and no second object is generated, or the string is pointing to the original object, that is, and S point to the same object.

  Six, did the string change?

No. Because string is designed as an immutable (immutable) class, all of its objects are immutable objects. Take a look at the following code:

String s = "Hello";

s = s + "world!";

Has the object pointed to by S changed? It is easy to derive this conclusion from the conclusion of the first article in this series. Let's see what's going on. In this code, s originally pointed to a string object, the content is "Hello", and then we have a + operation on S, then the object pointed to by S has changed it? The answer is No. At this point, S does not point to the original object, and point to another string object, the content is "Hello world!", the original object is still in memory, but s this reference variable no longer points to it. With the instructions above, it is easy to derive another conclusion that if you frequently make a variety of changes to the string, or if the changes are unpredictable, then using string to represent the strings can cause significant memory overhead. Because a string object cannot be changed after it is established, a string object is required for each different string. At this point, you should consider using the StringBuffer class, which allows you to modify instead of creating a new object for each different string. Also, the conversion of these two kinds of objects is very easy. At the same time, we can also know that if you want to use the same content string, you do not have to new a string each time. For example, we want to initialize a string reference variable named S in the constructor, set it as the initial value, and you should do this:

public class Demo {

Private String S;

Public Demo {

s = "Initial Value";}


Rather than

s = new String ("Initial Value");

The latter invokes the constructor every time, generates new objects, performs poorly and has a large memory overhead, and makes no sense, because the string object is immutable, so for a string of the same content, just one string object to represent it. It also says that multiple calls to the above constructor create several objects whose string type property s all point to the same object. The above conclusion is also based on the fact that, for string constants, if the content is the same, Java considers them to represent the same string object. Calling the constructor with the keyword new always creates a new object, regardless of whether the content is the same. As for why the string class is designed as an immutable class, it is the purpose of its decision. In fact, not only string, but many classes in the Java Standard Class library are immutable. In the development of a system, we sometimes need to design immutable classes to pass a set of related values, which is the embodiment of object-oriented thinking. Immutable classes have some advantages, such as because their objects are read-only, so there is no problem with multithreading concurrent access. Of course, there are some shortcomings, such as each different state to have an object to represent, may cause performance problems. So the Java Standard Class Library also provides a mutable version, the StringBuffer.

Finally, there are some Java technologies, including EJB3.0, that you can choose to learn, and EJB is a heavyweight in comparison to the three most lightweight frameworks.

Do you understand the six major problems in Java?

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: 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.