Usage of some basic concepts in Java

Source: Internet
Author: User

  Class initialization sequence
In Java, classes may include static variables, static initialization blocks, member variables, initialization blocks, and constructors. There may be inheritance relationships between classes. What is the loading sequence of the above parts when we instantiate an object?

  First, let's look at the Code:

Copy codeThe Code is as follows: class Parent
{
Public static StaticVarible staticVarible = new StaticVarible ("parent class-static variable 1 ");
Public StaticVarible instVarible = new StaticVarible ("parent class-member variable 1 ");

Static
{
System. out. println ("parent class-static block ");
}

{
System. out. println ("parent class-initialization block ");
}

Public static StaticVarible staticVarible2 = new StaticVarible ("parent class-static variable 2 ");
Public StaticVarible instVarible2 = new StaticVarible ("parent class-member variable 2 ");

Public Parent ()
{
System. out. println ("parent class-instance constructor ");
}
}

Class Child extends Parent
{
Public static StaticVarible staticVarible = new StaticVarible ("subclass-static variable 1 ");
Public StaticVarible instVarible = new StaticVarible ("subclass-member variable 1 ");

Static
{
System. out. println ("subclass-static block ");
}

Public Child ()
{
System. out. println ("subclass-instance constructor ");
}

{
System. out. println ("subclass-initialization block ");
}

Public static StaticVarible staticVarible2 = new StaticVarible ("subclass-static variable 2 ");
Public StaticVarible instVarible2 = new StaticVarible ("subclass-member variable 2 ");

}

Class StaticVarible
{
Public StaticVarible (String info)
{
System. out. println (info );
}
}

Then execute the following statement:Copy codeThe Code is as follows: Child child = new Child ();

The output result is as follows:Copy codeThe Code is as follows: parent class-static variable 1
Parent class-static Block
Parent class-static variable 2
Subclass-static variable 1
Subclass-static Block
Subclass-static variable 2
Parent class-member variable 1
Parent class-initialization Block
Parent class-member variable 2
Parent class-instance Constructor
Subclass-member variable 1
Subclass-initialization Block
Subclass-member variable 2
Subclass-instance Constructor

  Conclusion 
From the above results, we can see that when instantiating an object, the loading sequence of each part is as follows:

Parent class static member/parent class static initialization block-> subclass static member/subclass initialization block-> parent class member variable/parent class initialization block-> parent class constructor-> subclass Member variable/subclass initialization block-> subclass Constructor

  Something related to String
First, let's talk about the heap and stack in Java.

• Stack: stores basic types, including char/byte/short/int/long/float/double/boolean
• Heap: stores the reference type, and generally keeps a pointer to it in the stack. Garbage collection determines whether an object can be recycled, is to determine whether there is a pointer in the stack pointing to the object in the heap.
As a special data type, String is not exactly the same as the basic type, nor is it all the reference types. Many interview questions have it.

  Storage Structure of String type variables
The storage structure of String is divided into two parts. We use String a = "abc"; as an example to describe the storage method of String type:

1) create a char array in the stack. The values are 'A', 'B', and 'c '.

2) create a String object in the heap.

  String pool in Java
To save space and resources, JVM maintains a string pool, or caches some of the strings that have appeared before.

  For example, the following code:

Copy codeThe Code is as follows: String v1 = "AB ";
String v2 = "AB ";

Actually, v1 = v2, because after JVM declares v1, "AB" has been cached.

So what is the basis for JVM to cache strings? Let's take a look at the following code, which is very interesting:

Copy codeThe Code is as follows: public class StringTest {
Public static final String constValue = "AB ";
Public static final String staticValue;

Static
{
StaticValue = "AB ";
}

Public static void main (String [] args)
{
String v1 = "AB ";
String v2 = "AB ";
System. out. println ("v1 = v2:" + (v1 = v2 ));
String v3 = new String ("AB ");
System. out. println ("v1 = v3:" + (v1 = v3 ));
String v4 = "abcd ";
String v5 = "AB" + "cd ";
System. out. println ("v4 = v5:" + (v4 = v5 ));
String v6 = v1 + "cd ";
System. out. println ("v4 = v6:" + (v4 = v6 ));
String v7 = constValue + "cd ";
System. out. println ("v4 = v7:" + (v4 = v7 ));
String v8 = staticValue + "cd ";
System. out. println ("v4 = v8:" + (v4 = v8 ));
String v9 = v4.intern ();
System. out. println ("v4 = v9:" + (v4 = v9 ));
String v10 = new String (new char [] {'A', 'B', 'C', 'D '});
String v11 = v10.intern ();
System. out. println ("v4 = v11:" + (v4 = v11 ));
System. out. println ("v10 = v11:" + (v10 = v11 ));
}
}

Note the output result:Copy codeThe Code is as follows: v1 = v2: true
V1 = v3: false
V4 = v5: true
V4 = v6: false
V4 = v7: true
V4 = v8: false
V4 = v9: true
V4 = v11: true
V10 = v11: false

We will find that not all judgments return true, which seems to be in conflict with the above statement. Actually, it is not because

 Conclusion
1. JVM can only cache constants that can be determined during compilation, rather than runtime constants.

The constValue in the above Code is the compile time, while the staticValue is the run time.

2. The JVM cache method is different for strings created using the new method.

    In the above Code, v1 is not the same as v3.

 Does the String design belong to the meta-mode?
This topic is interesting. Most of the articles about design patterns generally use String as an example when talking about yuan. But does it belong to the meta-mode?

For the relationship between strings and object meta, refer to the following article:In-depth analysis on the use of C # strings and the Flyweight Mode
String inversion output
In this case, the string is generally considered as a character array, and then the string is reversed by means of an array.

Dazzled method calls
  Call methods in an inherited Link Structure
Inheritance is a common method in object-oriented design. It can effectively implement "code reuse", and subclass also has the freedom to override the parent class method, this makes it difficult to call the parent class method or subclass method.

Let's look at the following code:

Copy codeThe Code is as follows: public class PropertyTest {

Public static void main (String [] args)
{
ParentDef v1 = new ParentDef ();
ParentDef v2 = new ChildDef ();
ChildDef v3 = new ChildDef ();
System. out. println ("==== v1 ==== ");
System. out. println ("staticValue:" + v1.staticValue );
System. out. println ("value:" + v1.value );
System. out. println ("===== v2 === ");
System. out. println ("staticValue:" + v2.staticValue );
System. out. println ("value:" + v2.value );
System. out. println ("===== v3 === ");
System. out. println ("staticValue:" + v3.staticValue );
System. out. println ("value:" + v3.value );
}
}

Class ParentDef
{
Public static final String staticValue = "parent static variable ";
Public String value = "parent class instance variable ";
}

Class ChildDef extends ParentDef
{
Public static final String staticValue = "subclass static variable ";
Public String value = "subclass instance variable ";
}

The output result is as follows:Copy codeThe Code is as follows: ==== v1 ====
StaticValue: static variable of the parent class
Value: parent class instance variable
===== V2 =====
StaticValue: static variable of the parent class
Value: parent class instance variable
===== V3 =====
StaticValue: static variable of the subclass.
Value: subclass instance variable

  Conclusion
The method that calls the parent class or subclass method is only related to the declared type of the variable, and has no relationship with the instantiated type.

  Whether it is value transfer or reference Transfer
My opinion on this topic is that value transfer, because the content is stored in the stack, whether it is a basic type of value or a pointer to the object in the heap, all are values rather than references. In addition, during the value transfer process, JVM will copy the value and then pass the copied value to the calling method.

  In this way, let's look at the following code:

Copy codeThe Code is as follows: public class ParamTest {

Public void change (int value)
{
Value = 10;
}

Public void change (Value value)
{
Value temp = new Value ();
Temp. value = 10;
Value = temp;
}

Public void add (int value)
{
Value + = 10;
}

Public void add (Value value)
{
Value. value + = 10;
}

Public static void main (String [] args)
{
ParamTest test = new ParamTest ();
Value value = new Value ();
Int v = 0;
System. out. println ("v:" + v );
System. out. println ("value. value:" + value. value );
System. out. println ("===== change ==== ");
Test. change (v );
Test. change (value );
System. out. println ("v:" + v );
System. out. println ("value. value:" + value. value );
Value = new Value ();
V = 0;
System. out. println ("===== add === ");
Test. add (v );
Test. add (value );
System. out. println ("v:" + v );
System. out. println ("value. value:" + value. value );
}
}

Class Value
{
Public int value;
}

The output result is as follows:Copy codeThe Code is as follows: v: 0
Value. value: 0
===== Change ====
V: 0
Value. value: 0
===== Add ====
V: 0
Value. value: 10

We can see that when we call the change method, even if we pass the pointer to the object, the final object property is not changed because in the change method body, we created an object, and then directed the copied pointer to the original object to the new object, and adjusted the attributes of the new object. However, the "pointer to the original object before copying" still points to the "original object", and the attributes remain unchanged.

  Differences between final/finally/finalize
Final can modify classes, member variables, methods, and method parameters. Classes modified using final cannot be inherited. The final modification method cannot be overwritten. Variables modified using final can only be assigned once.

  When to declare the value assignment of a variable using final:

1) assign values when defining declarations

2) initializing block or static initializing Block

3) constructor

Let's look at the following code:

Copy codeThe Code is as follows: class FinalTest
{
Public static final String staticValue1 = "static variable 1 ";
Public static final String staticValue2;

Static
{
StaticValue2 = "static variable 2 ";
}

Public final String value1 = "instance variable 1 ";
Public final String value2;
Public final String value3;

{
Value2 = "instance variable 2 ";
}

Public FinalTest ()
{
Value3 = "instance variable 3 ";
}
}

  Finally is generally used with try... catch, mainly used to release some resources.

Let's look at the following code:

Copy codeThe Code is as follows: public class FinallyTest {

Public static void main (String [] args)
{
FinallyTest1 ();
FinallyTest2 ();
FinallyTest3 ();
}

Private static String finallyTest1 ()
{
Try
{
Throw new RuntimeException ();
}
Catch (Exception ex)
{
Ex. printStackTrace ();
}
Finally
{
System. out. println ("Finally statement executed ");
}
Try
{
System. out. println ("Hello World ");
Return "Hello World ";
}
Catch (Exception ex)
{
Ex. printStackTrace ();
}
Finally
{
System. out. println ("Finally statement executed ");
}
Return null;
}

Private static void finallyTest2 ()
{
Int I = 0;
For (I = 0; I <3; I ++)
{
Try
{
If (I = 2) break;
System. out. println (I );
}
Finally
{
System. out. println ("Finally statement executed ");
}
}
}

Private static Test finallyTest3 ()
{
Try
{
Return new Test ();
}
Finally
{
System. out. println ("Finally statement executed ");
}
}
}

The execution result is as follows:Copy codeThe Code is as follows: java. lang. RuntimeException
At sample. interview. FinallyTest. finallyTest1 (FinallyTest. java: 16)
At sample. interview. FinallyTest. main (FinallyTest. java: 7)
Finally statement executed
Hello World
Finally statement executed

Finally statement executed

Finally statement executed
Finally statement executed
Test instance created
Finally statement executed

Note that in the loop process, finally executes a loop even if break or continue is called.

Finalize is mainly used to release resources. When the GC method is called, this method will be called.

  Let's look at the following example:

Copy codeThe Code is as follows: class FinalizeTest
{
Protected void finalize ()
{
System. out. println ("the finalize method is called ");
}

Public static void main (String [] args)
{
FinalizeTest test = new FinalizeTest ();
Test = null;
Runtime. getRuntime (). gc ();
}
}

The execution result is as follows:Copy codeThe Code is as follows:The finalize method is called.

  Some things about basic types
There are nine basic types, including byte, short, int, long, float, double, boolean, and void. Each basic type corresponds to a "Packaging class". Other basic information is as follows:
Copy codeThe Code is as follows:. Basic Type: byte binary digits: 8
. Packaging class: java. lang. Byte
. Minimum value: Byte. MIN_VALUE =-128
. Maximum Value: Byte. MAX_VALUE = 127
. Basic Type: short binary digits: 16
. Packaging class: java. lang. Short
. Minimum value: Short. MIN_VALUE =-32768
. Maximum Value: Short. MAX_VALUE = 32767
. Basic Type: int binary digits: 32
. Packaging class: java. lang. Integer
. Minimum value: Integer. MIN_VALUE =-2147483648
. Maximum Value: Integer. MAX_VALUE = 2147483647
. Basic Type: long binary digits: 64
. Packaging class: java. lang. Long
. Minimum value: Long. MIN_VALUE =-9223372036854775808
. Maximum Value: Long. MAX_VALUE = 9223372036854775807
. Basic Type: float binary digits: 32
. Packaging class: java. lang. Float
. Minimum value: Float. MIN_VALUE = 1.4E-45
. Maximum Value: Float. MAX_VALUE = 3.4028235E38
. Basic Type: double binary digits: 64
. Packaging class: java. lang. Double
. Minimum value: Double. MIN_VALUE = 4.9E-324
. Maximum Value: Double. MAX_VALUE = 1.7976931348623157E308
. Basic Type: char binary digits: 16
. Packaging class: java. lang. Character
. Minimum value: Character. MIN_VALUE = 0
. Maximum Value: Character. MAX_VALUE = 65535

  Some conclusions on the basic types (from Java interview questions)
• Integers without character suffixes are of the int type by default, while floating-point numbers without character suffixes are of the double type by default.
• If the value of an integer is beyond the range that can be expressed by the int type, the suffix "L" must be added (case insensitive, it is recommended to use uppercase letters, because the lower-case L and Arabic numerals 1 are easily confused), expressed as long.
• Integers and floating-point numbers with the "F" (case-insensitive) Suffix are float; integers and floating-point numbers with the "D" (case-insensitive) Suffix are double.
• The Compiler checks the values of byte, short, int, long, float, double, and char variables during compilation. If the values exceed the value range, an error is returned.
• Int values can be assigned to all numeric variables; long values can be assigned to long, float, and double variables; A float value can be assigned to a float or double type variable. A double value can only be assigned to a double type variable.
  Conversion Between Basic Types
The following conversions are lossless conversions:

• Byte-> short
• Short-> int
• Char-> int
• Int-> long
• Float-> double
  The following conversion will result in loss of precision:

• Int-> float
• Long-> float
• Long-> double
The conversion is invalid.

  Date-related things
In Java, there are two classes related to Date, one is Date and the other is Calendar. Let's take a look at the following example:

Copy codeThe Code is as follows: public class DateTest {

Public static void main (String [] args) throws ParseException
{
Test1 ();
Test2 ();
Test3 ();
}

Private static void test1 () throws ParseException
{
Date date = new Date ();
System. out. println (date );
DateFormat sf = new SimpleDateFormat ("yyyy-MM-dd ");
System. out. println (sf. format (date ));
String formatString = "2013-05-12 ";
System. out. println (sf. parse (formatString ));
}

Private static void test2 ()
{
Date date = new Date ();
System. out. println ("Year:" + date. getYear ());
System. out. println ("Month:" + date. getMonth ());
System. out. println ("Day:" + date. getDate ());
System. out. println ("Hour:" + date. getHours ());
System. out. println ("Minute:" + date. getMinutes ());
System. out. println ("Second:" + date. getSeconds ());
System. out. println ("DayOfWeek:" + date. getDay ());
}

Private static void test3 ()
{
Calendar c = Calendar. getInstance ();
System. out. println (c. getTime ());
System. out. println (c. getTimeZone ());
System. out. println ("Year:" + c. get (Calendar. YEAR ));
System. out. println ("Month:" + c. get (Calendar. MONTH ));
System. out. println ("Day:" + c. get (Calendar. DATE ));
System. out. println ("Hour:" + c. get (Calendar. HOUR ));
System. out. println ("HourOfDay:" + c. get (Calendar. HOUR_OF_DAY ));
System. out. println ("Minute:" + c. get (Calendar. MINUTE ));
System. out. println ("Second:" + c. get (Calendar. SECOND ));
System. out. println ("DayOfWeek:" + c. get (Calendar. DAY_OF_WEEK ));
System. out. println ("DayOfMonth:" + c. get (Calendar. DAY_OF_MONTH ));
System. out. println ("DayOfYear:" + c. get (Calendar. DAY_OF_YEAR ));
}
}

The output result is as follows:Copy codeThe Code is as follows: Sat May 11 13:44:34 CST 2013
-05-11
Sun May 12 00:00:00 CST 2013
Annual: 113
Month: 4
Day: 11
Hour: 13
Minute: 44
Second: 35
DayOfWeek: 6
Sat May 11 13:44:35 CST 2013
Sun. util. calendar. ZoneInfo [id = "Asia/Shanghai", offset = 28800000, dstSavings = 0, useDaylight = false, transitions = 19, lastRule = null]
Annual: 2013
Month: 4
Day: 11
Hour: 1
HourOfDay: 13
Minute: 44
Second: 35
DayOfWeek: 7
DayOfMonth: 11
Dayofyear: 131

Note that the getxxx method in Date has become deprecated, so we try to use the calendar. get method to obtain detailed information about the Date.
In addition, note DateFormat, which not only formats the date output, but also reversely converts a string that matches the Format to the date type.

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.