Getting Started: Basics for Java beginners to learn

Source: Internet
Author: User
Tags array comparison final object object variables variable thread stringbuffer
Beginner

question one: What have I declared!

String s = "Hello world!";

A lot of people have done this, but what are we declaring? The answer is usually: a string with the content "Hello world!". Such vague answers are often the source of unclear concepts. If you want to answer correctly, half of the people will probably answer the wrong question.

This statement declares a reference to an object named "s" that can point to any object of type string, currently pointing to "Hello world!" The object of this string type. That's what's really going on. We didn't declare a string object, we just declared a reference variable that could only point to a string object. So if, after that sentence, you run another sentence:

string string = S;

We're declaring another reference that can only point to a String object, named String, and no second object is generated, string or point to the original object, that is, and s points to the same object.

question two: What is the difference between "= =" and the Equals method?

The = = operator is specifically used to compare variable values for equality. The better understanding is that:

int a=10;

int b=10;

Then A==b will be true.

But what's not good to understand is:

String A=new string ("foo");

String B=new string ("foo");

The a==b will return false.

According to the previous post, object variables are actually references whose values point to the memory address where the object resides, not the object itself. Both A and B use the new operator, which means that there will be two strings in memory that are "Foo", and since they are "two", they naturally reside in different memory addresses. The value of a and B is actually a value of two different memory addresses, so using the "= =" operator will result in false. Admittedly, the objects of A and B are all "foo" and should be "equal", but the = = operator does not involve comparison of object content.

The comparison of object content is exactly what the Equals method does.

Look at how the Equals method of Object objects is implemented:

Boolean equals (Object o) {

return this==o;

}

The Object object uses the = = Operator by default. So if your own class doesn't overwrite the Equals method, then your class uses equals and uses = = to get the same result. It can also be seen that the Equals method of object does not achieve the goal that the Equals method should achieve: Compare two object contents for equality. Because the answer should be determined by the creator of the class, object leaves the task to the creator of the class.

Take a look at an extreme class:

       
        
         
        Class monster{private String content;    ... boolean equals (Object another) {return true;} }
       
        

I covered the Equals method. This implementation causes the comparison between them to always return true regardless of the monster instance content.

So when you're using the Equals method to determine whether the object's content is equal, don't take it for granted. 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 his master. If you need to use the Equals method, or use any collection based on the hash code (hashset,hashmap,hashtable), look at the Java doc to see how the Equals logic for this class is implemented.

question three: Has the string changed in the end?

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

String s = "Hello";

s = s + "world!";

Does the object that s points to change? 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 points to a string object, the content is "Hello", and then we have a + operation on S, so does s point to the object that has changed? The answer is no. At this point, S does not point to the original object, but to another string object, the content is "Hello world!", the original object is still in memory, but the reference variable s is no longer pointing to it.

With the instructions above, it is easy to derive another conclusion that if you frequently make various modifications to strings, or unpredictable modifications, then using string to represent strings can cause a lot of memory overhead. Because a string object cannot be changed after it is established, a string object is required for each of the different strings. At this point, you should consider using the StringBuffer class, which allows you to modify instead of generating a new object for each different string. And, these two kinds of object conversion is very easy.

At the same time, we can also know that if you want to use the same string as the content, you don't have to have a string new each time. For example, to initialize a string reference variable named S in the constructor, set it to the initial value, this should be done:

       
        
         
        public class Demo {private String s;  ... public Demo {s = "Initial Value"; }  ...  }
       
        

Rather than

s = new String ("Initial Value");

The latter calls the constructor every time, generates new objects, has low performance and memory overhead, and makes no sense because the string object is immutable, so as long as a string object is used for the same content. It is also said that multiple objects are created by calling the above constructor multiple times, and their string type attribute s is pointing to the same object.

The above conclusion is also based on the fact that for string constants, if the content is the same, Java thinks they represent the same string object. With the keyword new call constructor, a new object is always created, regardless of whether the content is the same.

As for why the string class is designed to be immutable, it is determined by its purpose. In fact, more than string, many classes in the Java Standard Class library are immutable. In developing a system, we sometimes also need to design immutable classes to pass a set of related values, which is also the embodiment of object-oriented thinking. Immutable classes have some advantages, such as because their objects are read-only, so multithreading concurrent access does not have any problems. Of course, there are some drawbacks, such as each of the different states need an object to represent, may cause performance problems. So the Java Standard Class Library also provides a mutable version, that is, StringBuffer.

question four: What exactly does the final keyword modify?

Final makes the modified variable "invariant", but because the nature of the object variable is "reference", the "invariant" has two meanings: the invariant of the reference itself, and the object that the reference refers to.

The invariant of the reference itself:

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 does not change:

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

A.append ("broken!"); Compiling through

It is visible that final is valid only for reference "value" (that is, the memory address of the object that it points to), forcing the reference to point only to the object that was initially pointed to, and changing its point will result in a compile-time error. Final is not responsible for the change in the object it points to. This is very similar to the = = Operator: = = operator is only responsible for reference "value" equal, as to the object of this address is equal to the content, = = operator is regardless.

Understanding the final question has a very important meaning. Many program vulnerabilities are based on this----final can only guarantee that the reference always points to the fixed object, and cannot guarantee that the object's state is unchanged. In a multithreaded operation, an object is shared or modified by multiple threads, and a thread's unconscious modification of the object may cause another thread that uses this object to crash. The wrong solution is to declare it as final when the object is new, with the intention of making it "never change." In fact, it was futile.

question five: exactly how to initialize!

This question discusses the initialization of variables, so let's take a look at what kinds of variables are in Java.

1. The attribute of a class, or the domain name

2. Local variables in the method

3. Parameters of the method

For the first variable, the Java virtual opportunity is automatically initialized. If the initial value is given, it is initialized to the initial value. If it is not given, it is initialized to the default initial value of the type variable.

int type variable default initial value is 0

Float type variable default initial value of 0.0f

Double type variable default initial value is 0.0

Boolean type variable default initial value is False

Char type variable default initial value is 0 (ASCII code)

The long variable default initial value is 0

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 has not been initialized has a value of NULL after it is initialized automatically.

For two different class attributes, the static property and the instance property, the timing of initialization is different. The instance property is initialized when the instance is created, and the static property is initialized when the class is loaded, which is the first time the class is used, and is not initialized again for the creation of subsequent instances. This issue will be discussed in detail in a later series.

For the second variable, you must explicitly initialize it. If you try to use it before you initialize it, the compiler will protest. If the initialized statement is in a try block or in an if block, it must be able to get an assignment before it is used for the first time. In other words, the compiler will protest the initialization statement in a conditional judgment statement that has only if blocks, because the execution may not conform to the condition of 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. But if there is also an initialization statement in the else block, it can be compiled, because at any rate at least one of the initialization statements will be executed and not be initialized before it is used. The same is true for Try-catch, if the initialization statement is only in a try block, the compilation department passes. If you have it in catch or finally, you can compile it. In short, make sure that local variables are initialized before they are used. Therefore, a good practice is to declare their time to initialize them, if you do not know what the accident to the value of good, the above default value it!

In fact, the third variable is essentially the same as the second, which is the local variable in the method. As a parameter, it is definitely initialized, and the incoming value is the initial value, so no initialization is required.

question six: 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 in java. Its role is to test whether the object on its left is an instance of its right class, and returns a Boolean type of data. As an example:

String s = "I AM an object!";

Boolean IsObject = s instanceof Object;

We declare a String object reference, point to a String object, and then use INSTANCOF to test whether it points to an instance of the object class, which, obviously, is true, so return true, that is, the IsObject value is true.

Instanceof is of some use. For example, we wrote a billing system with three classes:

public class Bill {//omit details}

public class Phonebill extends Bill {//omit details}

public class Gasbill extends Bill {//omit details}

There is a method in the handler that accepts a bill type object and calculates the amount. Suppose the two bills are calculated differently, and the incoming Bill object may be either of two, so use instanceof to determine:

       
        
         
        Public double Calculate (Bill instanceof Phonebill) {//Calculate phone bill} if (Bill instanceof Gasbill) {//Calculation burn Gas bill ...}
       
        

  

This allows you to handle two of seed classes in one way.

However, this approach is often considered to be a failure to take advantage of the object-oriented polymorphism. In fact, the above features require method overload can be fully implemented, this is an object-oriented approach should be to avoid the return to structured programming mode. As long as two names and return values are the same, methods that accept different parameter types are available:

Public double Calculate (Phonebill bill) {

Calculate phone bills

}

Public double Calculate (Gasbill bill) {

Calculate gas bill

}

Therefore, the use of instanceof in most cases is not recommended practice, should make good use of polymorphism.



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.