Six questions each Java beginner should understand

Source: Internet
Author: User

Everyone who learns Java should understand the problems in this series. Of course, it doesn't matter if you just want to learn Java. If you think you are a beginner, but you do not understand these problems, repeat yourself as a beginner. The content is from the classic post of csdn.

Question 1: What have I declared!

String S = "Hello world! ";

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 you run the following statement:

String string = s;

We declared another reference that can only point to the string object, named string, and no second object is generated. The string still points to the original object, that is, the same object as S.

Question 2: What is the difference between "=" and equals?

= The operator is used to compare whether the values of variables are equal. A better understanding is:

Int A = 10;
Int B = 10;

Then a = B will be true.
But what is hard to understand is:

String A = new string ("foo ");
String B = new string ("foo ");

If a = B, false is returned.

According to the previous post, object variables are actually a reference. Their values point to the memory address of the object, not 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 the values of two different memory addresses. Therefore, if you use the "=" operator, the result is false. 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.

Take a look at the next extreme class:

Class monster {
Private string content;
...
Boolean equals (Object another) {return true ;}
}

Overwrite the equals method. This implementation will always return true regardless of the content of the monster instance.

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.

Question 3: 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 points to another string object instead of the original object, and the content is "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, we 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 each 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 represented by 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.

Question 4: What are the final keywords modified?

Final makes the modified variable "unchanged", but because the object type variable is essentially a "Reference", it 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" (that is, the memory address of the object it points to), and it forces the reference to only point to the object initially pointed, changing the point will cause compilation errors. Final is not responsible for the changes to the objects it points. This is very 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-thread operations, an object will be shared or modified by multiple threads. Unintentional modification 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.

Question 5: How to initialize it!

This topic discusses variable initialization, so let's first look at the types of variables in Java.

1. Class Attribute, or value range
2. Local variables in the Method
3. method parameters

For the first variable, the Java Virtual Machine will automatically initialize it. 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 int type variables is 0.
The default initial value of a float variable is 0.0f.
The default value of the double type variable is 0.0.
The default value of a Boolean variable is false.
The default initial value of the char type variable is 0 (ASCII code)
The default value of long type variables is 0.

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 items 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, it can be compiled, because no matter what it is, there is always at least one initialization statement that will be executed and will not be initialized before use. The same applies to try-catch. If an initialization statement is available only in the try block
. 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.

Question 6: 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. For example:

String S = "I am an object! ";
Boolean isobject = s instanceof object;

We declared a String object reference, pointing to a string object, and then using instancof to test whether the object it points to is an instance of the object class. Obviously, this is true, so true is returned, that is, the isobject value is true.

Instanceof is useful. For example, we have written a bill processing system, which has three classes:

Public class Bill {// omitting details}
Public class phonebill extends Bill {// omitting details}
Public class gasbill extends Bill {// omitting details}

There is a method in the handler that accepts a bill-type object and calculates the amount. Assume that the two billing methods are different, and the incoming Bill object may be either of them. Therefore, use instanceof to judge:

Public double calculate (bill ){
If (Bill instanceof phonebill ){
// Calculate the telephone bill
}
If (Bill instanceof gasbill ){
// Calculate the gas bill
}
...
}

In this way, two subclass classes can be processed in one way.

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 the methods with different parameter types:

Public double calculate (phonebill Bill ){
// Calculate the telephone bill
}

Public double calculate (gasbill Bill ){
// Calculate the gas bill
}

Therefore, using instanceof is not recommended in most cases, and polymorphism should be well utilized.

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.