Every beginner should understand the problem!

Source: Internet
Author: User
Tags array final object object variables string variable thread stringbuffer
Beginners | Questions for this series of questions, every Java learner should understand. Of course, it doesn't matter if you just learn to play Java. If you think you have gone beyond beginners, but do not understand these questions, please return yourself to the ranks of beginners. The content comes from CSDN's classic old stickers. 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 and the content is "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 you run a:string string = s; after that sentence, 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. A better understanding is that:int a=10;int b=10; a==b will be true. But it is not easy to understand the place is: string a=new string ("foo"); String b=new string ("foo"); 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. 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), check 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 look at 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 string objects are not created after they are establishedCan be changed again, so for each different string, a string object is required to represent it. 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";} ...} Instead of s = new string ("Initial value"), the latter calls the constructor every time, generates new objects, has low performance and memory overhead, and is meaningless because the String object is immutable, So for a string with the same content, just a string object to represent it. 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;//the object to which the compile-time error reference does not change: final stringbuffer a=new  stringbuffer ("immutable"); A.append (" broken!");  //compilation by visible, final only for the reference "value" (that is, the object that it points to the memory address) is valid, it forces a reference can only point to the original point of the object, change its point will cause 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. The properties of the 1.  class, or the parameters of the local variable 3.  method called the domain 2.  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 0float type variable default initial value is 0.0fdouble type variable default initial value is 0.0boolean type variable default initial value is FALSECHAR type variable default initial value is 0 (ASCII) The long type variable default initial value is 0 all object reference type variables default initial value is null, that is, does not point to any object. 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 the。 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. Give an example:string s =  "i am an object!"; boolean isobject = s instanceof object; we declared a string object reference, pointing to a String object, Then use INSTANCOF to test whether the object it points to is 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 {//omitted details}public class phonebill  extends bill {//omitted details}public class gasbill extends bill {//omitted details} There is a method in the handler that accepts a bill type of 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 judge: Public double calculate (Bill bill)  { if  (Bill instanceof phonebill)  {//computing phone Bill}if  (Bill instanceof gasbill)   {//Calculate 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 the two names and return values are the same, you can accept different methods for the parameter types: public double calculate (phonebill bill)  {//calculate the phone bill}public  double calculate (Gasbill bill)  {//calculate gas bill} Therefore, using instanceof is not recommended in most cases and should take advantage 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.