Deep understanding of Java data types

Source: Internet
Author: User

I. Overview

When we solve a specific problem by programming, the first thing to do is to use various "data structures" to represent the entity objects in the problem, before we begin to study the algorithms that describe the specific business logic. This also confirms the "program = data structure + algorithm". The data structure here corresponds to a variety of data types.

A data type refers to a set of values and a related set of actions. There are two classes of data types in Java: primitive (primitive) data types, including Boolean, int, double, and so on, and a reference type, class, Includes classes provided to us by the Java class Library and our own classes defined using the keyword class. Classes in Java can be divided into abstract data types and static code libraries in terms of functionality.

Second, the original data type

1. Declaration and initialization

There are two main scenarios where the original data type is used as a variable:

One is used as a local variable, when we have to declare and initialize before we can use, otherwise we will error:

 Public Static void Main () {    int  A;     int // error, local variable A is not initialized     ...}

The second scenario is used as an instance variable or class variable, at which point the system is "implicitly initialized" if it is not initialized (specifically, the integer is initialized to 0, the float is initialized to 0.0, and the Boolean is initialized to false):

 Public class Counter {    privateint  ID;     Private int count;      Public Counter (int// does not show initialization in the constructor Count,count in the newly created object is implicitly initialized by the system to 0this        . id = ID;    }    ...}

2. Primitive Type Array

As we mentioned above, in Java in addition to the original data type is a reference type, so the array in Java is a reference type. The essential difference between a reference type and the original data type is that the reference type variable holds a reference, where the reference is the memory address. consider the following code snippet:

... int a = 12345; int b == 123456;//a value unchanged, still 12345 ... int [] D = {1, 2, 3}; int [] e = d;e[0] = 0;  Changed e at the same time also changed D, that is now d = {0, 2, 3} ...

In the above code, the phrase "int b = A" Creates a copy of a and assigns it to B, because it is the original data type, so modifying the value of B does not affect a.

the "int e = d" also creates a copy of D and assigns it to E, whereas the value of D is actually a reference to an integer array (that is, the address), so the value of e also becomes the address of the same integer array. So the changes made to the shape array by e are reflected on D. This phenomenon is called an alias, that is, in memory the same integer array now has more than one variable to hold its address, both of which can be modified on the line.

Iii. reference types

As mentioned above, the value of a reference type variable in Java is a reference, which is the address of the actual object. The type of reference in Java is what we often call classes (class), and the class has two main purposes: one is to describe an abstract data Type,adt, and the other is to hold a set of static methods, which are used as static code libraries (for example, The math class in the Java class Library).

1. Memory model

The memory footprint of reference types in Java is not as intuitive as the original type. The primitive type variable does not need to save any information other than its own value. While a Java object tends to occupy more memory, it needs to save all of its instance variables and some extra information (including references to classes that point to objects, garbage collection information, synchronization information). Consider the following Java classes:

 Public class Rect {    privateint  l;     Private int W;    ...}

An object of type rect takes up 24 bytes of memory on a typical 64-bit machine, including 8 bytes of reference to a Rect class, 8 bytes of garbage collection information, and synchronization information and two bytes of instance variables of type int.

2. Equality

The default comparison behavior of the "= =" operator on two objects is to detect whether their identities (that is, references) are equal. In most cases, our definition of two objects is equal to the state of the two objects (the values of each instance variable) . To achieve this behavior we want, we just need to rewrite the Equals () method.

This method is defined in the object class (the parent class of all Java classes), and the Java standard requires that the implementation of this method must accept an object type parameter and satisfy the following properties:

(1) Reflexivity: That is, x.equals (x) must return True

(2) Symmetry: X.equals (y) and y.equals (x) must return the same result

(3) Transitivity: if X.equals (y), y.equals (z) all return True, then X.equals (z) must also return true

(4) Consistency: If the object referenced by x and Y does not change, then no matter how many calls X.equals (Y) should return a consistent result

(5) Non-nullability: x,x.equals (NULL) always returns false for any non-null reference

Take the Rect class mentioned above as an example:

 Public classRect {Private intW; Private intl;  PublicRect (intWintl) {...}  Public Booleanequals (Object otherobject) {if(Otherobjcet = =NULL) {            return false; } Else if( This==otherobject) {            return true;//identity Same, return true directly        }        if( This. getclass ()! =Otherobject.getclass ()) {            return false; } rect rect=(Rect) otherobject; if(( This. GETW () = = RECT.GETW ()) && (( This. Getl () = =Rect.getl ())) {            return true; }        return false; }}            

It is important to note that, in practice, the definition of equality for different objects is often a specific scenario, where we define two rectangular objects equal to the length and width of the two respectively.

3. invariance

in Java, the data type with the final decoration has "invariant". This invariance has different meanings for both the original data type and the reference type. For primitive data type variables, the so-called invariance refers to its value is immutable, for reference type variable, invariance refers to the content of its reference can not be changed, but the contents of the object it refers to may change. In addition, the final decorated class can no longer derive subclasses. For example, the following code snippet:

 Public The value of Class Test {    publicstaticfinalint//A will always be 5 and cannot be changed public    finaldouble//double the identity (reference) of the array object B is not an edge, But it points to a double array that can be changed ...     }

There are a lot of things to discuss about Java data types, and here's just a discussion:

Deep understanding of Java data types

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.