Six big questions that Java beginners must understand (organized from the web)

Source: Internet
Author: User
Tags stringbuffer

question one: What did I declare! 1. String s = "helloworld!"; Many people have done this kind of thing, but what exactly do we declare? The answer is usually: a string, the content is "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: 1.  string string = S; We are declaring another reference that can only point to a String object, named String, and no second object is generated, and string is pointing to the original object, that is, to the same object as S.

question two: What is the difference between "= =" and the Equals method? The = = operator is specifically used to compare the values of variables for equality. A better understanding of the point is: 1. int a=10; 2.3. int b=10; Then A==b will be true. But it is not easy to understand the place is: 1. String A=new string ("foo"); 2.3.   String B=new string ("foo"); Then A==b will return false. According to the previous post, the 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 values of two different memory addresses, so using the "= =" operator, the result will be false. Admittedly, A and B refer to objects whose contents 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: 1. Boolean equals (Object o) {2. 3. return this==o; 4.5. 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. Take a look at an extreme class: 1. Class monster{2. Private String content; 3 ..... 4. Boolean Equals (Object another) {5. return true; 6.} 7. I overridden the Equals method. This implementation causes the comparison between them to always return true regardless of the content of the monster instance. 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 toRecognize how the equals logic of this class is implemented. question three: Did the string change? No. Because string is designed as an immutable (immutable) class, all of its objects are immutable objects. Please look at the following code: 1. String s = "Hello"; 2. 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 to the initial value, and should do this: 1. public class Demo {2. Private String S; 3 ..... 4. Public Demo {5. s = "Initial Value"; 6.} 7. ... 8.} rather than 1. s = new String ("Initial Value"), which invokes the constructor every time, generates a new object, has poor performance and memory overhead, and does not make sense because the string object is immutable, so for strings of the same content, Just a 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. ItsNot 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.

question four: 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 is unchanged: 1. Final StringBuffer A=newstringbuffer ("immutable"); 2. Final StringBuffer b=new StringBuffer ("not immutable"); 3. a=b;//compile-time error reference the object that is pointing to is unchanged: 1. Final StringBuffer A=newstringbuffer ("immutable"); 2. A.append ("broken!"); Compilation is visible and final is valid only for the referenced "value" (the memory address of the object it points to), forcing the reference to point only to the object to which it was originally pointed, 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 wrong solution is to declare it as final when the object is newly created, with the intention of making it "forever". In fact, it was futile.

Question five: Exactly how to initialize!
This question discusses the initialization of variables, so first look at what kinds of variables are in Java. 1. The properties of the class, or the domain value 2. The local variable in the method 3. The parameters of the method are initialized automatically for the first variable, and the Java virtual opportunity. 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. 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 code) The default initial value of a long type variable is 0 all object reference type variables The default initial value is null, which means that 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, and it 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.


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 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. As an example: 1. String s = "I AM anobject!"; 2. Boolean IsObject = S instanceof object; We declare a String object reference, point to a String object, and then use INSTANCOF to test whether the object it points to is an instance of an object class, obviously, This is true, so return true, that is, the value of IsObject is true. Instanceof has some use. For example, we wrote a system that handles bills, and there are three of them: 1. public class Bill {//omit details} 2. 3. Public Classphonebill extends Bill {//omit details}4. 5. Public Classgasbill extends Bill {//omit details} There is a method in the handler that accepts an object of type Bill and calculates the amount. Suppose the two billing methods are different, and the incoming Bill object may be either of the two, so use instanceof to determine: 1. Public double Calculate (Bill) {2. if (Bill Instanceof PhoneBill) {3. Calculate Phone Bill 4. } 5. if (Bill instanceof Gasbill) {6. Calculate gas Bill 7. } 8. ... 9.} This allows you to handle two seed classes in one way. 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 the two names and return values are the same, the method of accepting different parameter types can be: 1. Public double Calculate (PhoneBill bill) {2. Calculate Phone Bill 3. } 4. Public doublecalculate (Gasbill Bill) {5. Calculate gas bill}java String Class (Java.lang.String)Is the most used class in Java, is also the most special class, many times, we are both familiar and unfamiliar. First, fundamentally understand the Java.lang.String class and the string pool Firstly, I suggest that we first look at the source code implementation of the String class, which is the fundamental starting point to understand the string class in essence. As you can see: 1, the String class is final and cannot be inherited. Public final class String. 2, the String class is the essence of the character array char[], and its value cannot be changed. PRivate final charvalue[]; then open the API document of the string class, you can see: 3, the String class object has a special way to create, that is, directly specify such as String x = "abc", "ABC" represents a String object. X is the address of the "ABC" object, also called a reference to the "ABC" object. 4. String objects can be concatenated by "+". A new string is generated after concatenation. It can also be concatenated by concat (), which is explained later. 6. The Java runtime maintains a string pool, Javadoc translation is very vague "string buffer". The string pool is used to hold the various strings produced in the runtime, and the contents of the strings in the pool are not duplicated. The normal object does not exist in this buffer pool, and the object created only exists in the stack area of the method. 5, there are many ways to create strings, summed up there are three categories: one, using the new keyword to create a string, such as String S1 = new String ("abc"), and the second, directly specified. For example, string s2 = "abc"; third, a new string is generated using concatenation. such as String s3 = "AB" + "C"; second, the creation of string objects is also very important, the key is to understand its principle. Principle 1: When using any way to create a string object s, the Java runtime (the running JVM) will hold this x in the string pool to find if there is a string object of the same content, if not, create a string s in the pool, otherwise, not add in the pool. In principle 2:java, whenever you use the New keyword to create an object, you must create a new object (in the heap or stack area). Principle 3: Creating a String object using direct designations or concatenation with a pure string only checks the string in the maintenance string pool without creating one in the pool. However, the string object will never be created in the stack area again. Principle 4: Using an expression containing a variable to create a string object will not only examine the maintenance of the string pool, but also create it in the stack areaA string object. In addition, the Intern () method of string is a local method, defined as public native String intern (), and the value of the Intern () method is to allow the developer to focus on the String pool. When the Intern method is called, if the pool already contains a string equal to this string object (which is determined by the Equals (object) method), the string in the pool is returned. Otherwise, this string object is added to the pool, and a reference to this string object is returned. The immutable class immutable string has a great advantage: The compiler can set the string to be shared. Immutable classes string has an important advantage-they are not shared references. So, Java, for the sake of efficiency, has been specially handled for string types--providing a string type with a string that defines a variable of type string in two ways: string name= "Tom"; string name =new When string ("Tom") uses the first method, it uses the string pool, when using the second way, is a normal way of declaring objects if you use the first way, then when you declare a content is "Tom" string, it will use the original memory in the pool, Instead of reallocating memory, that is, string saname= "Tom" will point to the same piece of memory

Six big questions that Java beginners must understand (organized from the web)

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.