On the creation of objects in Java and the conversion of object data type _java

Source: Internet
Author: User
Tags wrapper

Java: The process of object creation and initialization
1. Data types in Java
There are 3 data types in Java: Basic data types (in Java, Boolean, Byte, short, int, long, char, float, double, eight are basic data types), reference types, and null types. Where reference types include class types (including arrays), interface types.
The following statement declares some variables:

int k;
A A; A is the name of the object variable for a data type.
b b1,b2,..., b10000;//assumes B is an abstract class or interface.
String S; 

Note: From the point of view of data type and variable, basic data type variable K, class type variable A and S, abstract class or interface type variable B (10,000), they are all variables (identifiers).
2. About handles (handle)
To differentiate between variable identifiers of reference types and basic data type variable identifiers, we specifically use handle to address the variable identifier of a reference type. B1 to b10000, a, and s are all handle in the example above. Handle intuitive look is the handle, handle, we use the computer industry commonly used in Chinese translation "handle".

2.1 Meaning of the handle in "Windows Programming"
A handle is a unique integer used by wondows to identify objects that are created or used by the application, and Windows uses a variety of handles to identify such things as application instances, Windows, controls, bitmaps, GDI objects, and so on. A Windows handle is somewhat like a file handle in the C language.
As we can see from the above definition, the handle is an identifier, it is to identify the object or project, it is like our name, everyone will have a different person's name is not the same, but, there may be a name and you the same person. From the data type it is just a 16-bit unsigned integer. An application almost always obtains a handle by calling a Windows function, which can then be used by other Windows functions to refer to the object.
If you want to get a better understanding of the handle, I can tell you that the handle is a pointer to a pointer. We know that a pointer is a memory address. After the application is started, the objects that make up this program reside in memory. If we simply understand it, it seems that we can use this address to access the object at any time as long as we know the first address of this memory. However, if you really think so, then you are wrong. As we know, Windows is an operating system based on virtual memory. In this system environment, Windows memory manager often moves objects back and forth in memory to meet the memory needs of various applications. The object being moved means that its address has changed. If the address changes so much, where do we go to find the object?
To address this problem, the Windows operating system frees up some of the internal storage addresses for each application to specifically register address changes in memory for each application object, and this address (the location of the storage unit) itself is unchanged. After the Windows Memory Manager moves the object in memory, the new address of the object is communicated to this handle address to save. So we just remember this handle address to know indirectly where the object is in memory. This address is assigned by the system when the object is loaded (load) and released to the system when the system is unloaded (Unload).
Handle address (Stable) → Record the address of the object in memory ────→ the object in memory (unstable) → actual object

The meaning of handle in 2.2Java
With a deep understanding of the implications of the previous "Windows programming" of the handle, we can say that handle is a very much needed term when we learn java. It is meant to distinguish between the object itself and the object variable (or the strict point: The variable identifier of the data type to which the object belongs).

2.3 Return to the variable declaration in 1:
Now, you should have a glance at the following comment.

int k, J;//k contains an integer number.
a A;//a the address in the store.
B b1,b2,..., b10000;//b1,...,b10000 store address.
String S;//s address.

3. About references (reference)
what is "reference"? "The identifier you are actually a ' reference ' to an object". (Thinking in Java 2e)
The identifier that you manipulate is actually a "reference" to an object. Or, to be precise, the identifier you manipulate is actually a reference to an object. Obviously, reference in the original text is a sense of direction of things.
Back in Java, refer to the ID number, the ID of the object, or the cell phone number of the object that can be imagined. Of course, the more saying is that the reference is the room number where the object lives in memory. Intuitively, the object reference is the return value when the object is created! A reference is the return value of a new expression.
New A (); This really creates an object, but we don't hold it with a handle (hold, hold, save) the reference. From the microscopic point of view, the new expression completes the task of object initialization (three-step, detailed analysis below), as a whole to return a reference.
Return to the variable declaration in 1 and look at the following comment.

A A; Declaration handle A, but uninitialized, so the value inside is null.
B b1,b2,..., b10000;//declaration handle b1,...,b10000, but not initialized, so the value inside is null.
String S;//declaration handle S, but uninitialized, so the value inside is null.

4. The relationship between a handle and a reference

A a;//declaration handle A, the value is null
a=new a ();//handle initialization (handle = reference; Assign a reference to a handle)

Reference: The value of New A (). A reference can be simply viewed as an address where the object occupies the memory space, and can be conveniently distinguished from other objects by reference to the object's unique identity.
After the initialization of the handle is complete, you can use the handle to remotely control the object.
Of course, this is only to explain the creation and initialization of objects on the one hand, understanding the relationship between the handle and the reference, the following analysis of the entire process of object initialization. First do the following preparation work, talk about stacks and heaps.
5. Java medium stack (stack) and heap (heap)
In Java, memory is divided into "stack" and "Heap" (Stack and Heap). The base data type is stored in the stack, the object reference type is actually stored in the heap, and only the address value of the reference memory is retained on the stack.
by the way "= =" and "Equals () method" to help understand the concepts of both (Stack and Heap).
When using "= =" in Java to compare variables, the system uses the values stored in the stack (stack) as the basis for the comparison, and the value that the underlying data type holds in the stack is its content, and the value of the reference type in the stack is the address value of the object in the heap that it points to. The object class in the Java.lang package has public boolean equals (Object obj) methods. It compares two objects for equality. The Equals () method of the object returns true only if the two references being compared point to the same object (the handle is equal). (For the Equals () method of the String class, it overrides the (override) Equals () method, which is not discussed in this article.) )
6. The process of creating and initializing an object
In Java, an object is an instance of a class. In general, when a class is instantiated, all members of the class, including variables and methods, are copied to a new instance of this data type. Analyze the following two pieces of code.

6.1 Vehicle VEH1 = new Vehicle ();
The above statement does the following things:
The "New Vehicle" on the right side of the ① is a Vehicle class template that creates a Vehicle class object (also referred to as the Vehicle object) in the heap space.
The end of the ② () means that the constructor of the vehicle class is called immediately after the object is created, initializing the object just generated. Constructors are definitely there. If it is not created, Java complements a default constructor.
The "Vehicle veh1" on the left of ③ creates a Vehicle class reference variable.
The ④ "=" operator causes an object reference to point to the vehicle object that you just created. (recall the handle and reference)
Divide the above statement into two steps:

Vehicle veh1;
VEH1 = new Vehicle ();

In this way, it is more clear that there are two entities: one is the object reference variable, the other is the object itself. The entities created in the heap space are different from the entities created in the stack space. Although they are also real entities, it seems difficult to "catch" it accurately. Let's take a closer look at the second sentence and find out what's the name of the object you just created. Some people say, it is called "Vehicle". No, "Vehicle" is the name of the class (the creation template for the object). A Vehicle class can create countless objects that cannot be called "Vehicle". Object has no name and cannot access it directly. We can only indirectly access objects through object references.

6.2 Vehicle Veh2;

VEH2 = VEH1;

Since VEH1 and VEH2 are just references to objects, the second line does nothing but assign VEH1 references (addresses) to VEH2, so that VEH1 and Veh2 point to only one vehicle object.

6.3 Veh2 = new Vehicle ();
The reference variable VEH2 to the second object.
From the above narration, we can get the following conclusion: ① an object reference can point to 0 or 1 objects; ② an object can have n references pointing to it.

Java: Data type conversions
1. Java simple types and their wrapper classes
1.1Java Simple Type and encapsulation class
We know that the Java language is a typical object-oriented programming language, but given the simple structure of some basic data types, small memory and fast access, Java still provides support for these non object-oriented simple data types. Of course, Java provides encapsulation classes that correspond to simple data types when providing a large number of other classes, so there are in Java such as int and integer (float and float, double and double ...) Different data types.
There are two broad classes of data types in the Java language: One is a simple type, also known as the primary type (primitive), and the other is a reference type (Reference). A simple type variable stores a specific value, whereas a variable of a reference type stores a reference to the object.
Java determines the size of each of the simple types. These sizes do not change as the structure of the machine changes. This immutable size is one of the reasons why Java programs have a strong ability to migrate.
The following table lists the simple types defined in Java, the number of bits consumed, and the corresponding wrapper classes.

Simple types in table Java

1.2 Why use the encapsulation class
For example, int and integer, although they all represent a 32-bit integer, they are different data types. In fact, the integers that are used directly in Java are int (in terms of int and integer) and must be encapsulated in an int as an object only if the data must appear as the object's identity. Intege the integer value.
For example, to add an integer to the vector in a java.util package, you must encapsulate the integer value in an integer instance as follows:

Vector v=new vector ();
int k=121;
V.ADDELEMT (New Integer (k));


In addition, integer as an int corresponding to the wrapper class, provides a number of methods, such as: Integer construction method, integer to the various other numeric types of conversion methods, and so on, and these are not the type int data.
2. Constants in Java
we need to be aware of the following kinds of constants.
2.1 Hexadecimal integer Constants
When represented in hexadecimal, it starts with a 0x or 0X, such as 0xff,0x9a.

2.2-Octal integer constant
Octal must start with 0, such as 0123,034.

2.3 Long Integral type
The long integer must end with L, such as 9l,342l.

2.4 Floating-point constants
Because the default type of a decimal constant is double, you must add F (f) to the back of the float type. The same variable with a decimal number defaults to the double type.
float F;

  f=1.3f;//must declare F.


2.5 Characters Constants Quantity
Character constants are enclosed in two single quotes (note that the string constants are enclosed in two double quotes). Characters in Java account for two bytes.
Some of the commonly used escape characters.
①\r means to accept keyboard input, which is equivalent to pressing the ENTER key;
②\n means to change lines;
③\t represents a tab character, equivalent to a table key;
④\b represents the Backspace key, equivalent to the back space key;
⑤\ ' represents single quotation marks;
⑥\ ' denotes double quotes;
⑦\\ represents a slash \.
3. Conversions between simple data types
There are two ways to convert between simple types of data: automatic conversions and casts, which usually occur in an expression or when a parameter of a method is passed.
3.1 Automatic Conversion
Specifically, when a "small" data with a more "large" data operation, the system will automatically convert "small" data into "large" data, and then operation. In the method call, the actual parameter is more "small", and the method is called when the formal parameter data is more "big" (if there is a match, of course will directly call the matching method), the system will automatically convert "small" data into "large" data, and then the method of invocation, naturally, for multiple overloaded methods with the same name, will be converted to the most " Close to the "big" data and make the call.
These types are from "small" to "large" respectively (Byte,short,char)--int--long--float-double. What we call "big" and "small" here is not how much bytes are occupied, but the size of the range that represents the value.
Take a look at the following example:

① The following statements can be passed directly in Java:

byte B;
int i=b;
Long l=b;
float f=b;
Double d=b;
 

② If the low-level type is char, the conversion to the Advanced Type (integer) is converted to the corresponding ASCII code value, for example

Char c= ' C ';
int i=c; 
System.out.println ("Output:" +i);


Output:

output:99;


③ for Byte,short,char three types, they are lateral and therefore cannot be automatically converted to each other, and you can use the following coercion type conversions.

Short i=99;
Char c= (char) i;
System.out.println ("Output:" +c);

Output:

OUTPUT:C;


If there are methods in ④ object polymorphism:

f (byte x) {...};
f (short x) {...};
f (int x) {...};
F (long x) {...};
f (float x) {...};
f (double x) {...};

Also: Char y= ' a '; So, which method does statement f (Y) call? The answer is: f (int x) {...} method because its formal parameters are "large" and are the most "close" to the argument.

And for the method:

f (float x) {...};
f (double x) {...};

Also: long y=123l; Then the method called by Statement F (Y) is F (float x) {...}.

3.2 Forced conversions
When you convert large data to small data, you can use coercion type conversions. That is, you must use the following statement format:

int n= (int) 3.14159/2;

It can be imagined that this conversion is certainly likely to result in a drop in overflow or precision.

3.3 Automatic data type elevation of expression
For automatic promotion of types, note the following rules.
① the value of all Byte,short,char types will be promoted to int type;
② if one of the operands is a long, the result is a long type;
③ if one of the operands is float, the result is a float type;
④ if one of the operands is a double, the result is a double type;
Cases

byte B;
  b=3;
  B= (Byte) (b*3);//must declare byte.


3.4 Wrapper class Transition type conversion
In general, we first declare a variable, and then generate a corresponding wrapper class, you can use the wrapper class of various methods for type conversion. For example:
① when you want to convert a float to a double type:

float f1=100.00f; 
Float f1=new Float (F1); 
Double D1=f1.doublevalue ();//f1.doublevalue () method for returning a double value of float class


② when you want to convert a double to an int type:

Double d1=100.00;
Double D1=new double (D1);
int I1=d1.intvalue ();


A variable of a simple type is converted to the appropriate wrapper class, which can take advantage of the constructor of the wrapper class. That is: Boolean (boolean value), Character (char value), Integer (int value), long (Long value), float (float value), double (double Value
and in each wrapper class, the total visible as Xxvalue () method, to get its corresponding simple type of data. By using this method, we can also realize the transformation between different numerical variables, for example, for a double-precision real class, Intvalue () can get its corresponding integer variable, and Doublevalue () can get its corresponding double precision real variable.
4. Conversion between strings and other types
4.1 Conversion of other types to strings
① invoke the string conversion method of the class: X.tostring ();
② Automatic conversion: x+ "";
③ method using String: String.volueof (X);

4.2 Strings as values, to other types of conversions
① first to the corresponding wrapper instance, then calls the corresponding method to convert to other types
For example, the format for the value of the character "32.1" to convert a double is: New Float ("32.1"). Doublevalue (). can also be used: double.valueof ("32.1"). Doublevalue ()

② static Parsexxx method

String s = "1";
byte B = byte.parsebyte (s);
Short T = Short.parseshort (s);
int i = Integer.parseint (s);
Long L = Long.parselong (s);
Float f = float.parsefloat (s);
Double d = double.parsedouble (s);

The

 
③character getnumericvalue (char ch) method
specifically consulted the API.
5. There is no direct correspondence between the date class and the other data type's conversion
integer and Date class. It's just that you can use int to represent the year, month, day, time, minute, and second, so that a corresponding relationship is established between the two, and in making this transition, You can use the three forms of the Date class constructor:
①date (int year, int month, int date): int, month, day
②date (int years, int month, int date, int hr s, int min): An int represents the year, month, day, time, and minutes
③date (int year, int month, int Date, int hrs, int min, int sec): In int, the year, month, day, time, minute, second
in the long An interesting correspondence between the integer and the date classes is to represent a time as the number of milliseconds from January 1, 1970 0:0 Greenwich Mean Time. For this correspondence, the date class also has its corresponding constructor: date (long date).
Gets the year, month, day, time, minutes, seconds, and weeks in the date class you can use the Date class getyear (), getmonth (), GetDate (), getHours (), getminutes (), getseconds (), Getday () method, you can also interpret it as converting the date class to int.
and the GetTime () method of the date class can get the long integer corresponding to the time we mentioned earlier, as with the wrapper class, the date class also has a ToString () method that can convert it to a string class.
Sometimes we want to get a specific format for date, such as 20020324, we can use the following methods, starting with the introduction of the file,

Import Java.text.SimpleDateFormat;
Import java.util.*;
Java.util.Date Date = new Java.util.Date ();
 
If you want to get the YyyyMMDD format
simpledateformat sy1=new simpledateformat ("YyyyMMDD");
String Dateformat=sy1.format (date);
 
If want to separate get year, month, day
SimpleDateFormat sy=new simpledateformat ("yyyy");
SimpleDateFormat sm=new SimpleDateFormat ("MM");
SimpleDateFormat sd=new SimpleDateFormat ("DD");
String Syear=sy.format (date);
String Smon=sm.format (date);
String Sday=sd.format (date);

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.