Java data types are used in real-world development

Source: Internet
Author: User
Tags java reference

  In the front of the blog post, I have introduced the Java core of the container Io, and now I say a bit about the data types in Java. In Java, everything is an object (this means that in Java, the majority of cases are used by the object), very few are not objects, there are corresponding objects (such as the basic data types exist with the corresponding wrapper class, array has a list object can be replaced)

  Data types in Java mainly have "basic data type", "String", "Reference type" (Basic reference type is not much to introduce, in the next Article blog post focuses on "enumeration", also considered as a reference type)

One: basic data Type 1.1 definition of basic data type

  byte, char, int, float, double, long... These are the basic data types that belong to Java. Specific usage can be referenced (summary of Java Basic data types). In Java, the use of basic types is not object-oriented design, so it provides some specialized wrapper classes. In actual development, we do not need to consider whether the basic type or wrapper class (Java provides the automatic boxing mechanism). Of course, the basic type is still necessary to learn a bit.

1.1.1 Understanding basic Types by type

The base types can be divided into three categories, char types, Boolean type Boolean, and numeric type Byte, short, int, long, float, double. Numeric types in Java do not have unsigned, their value range is fixed, and will not change with the machine hardware environment or the operating system changes

Java determines the size of each simple type and does not change as the machine structure changes. This 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, and the corresponding wrapper classes.  

Simple Type

Boolean

Byte

char

Short

Int

Long

Float

double< /p>

Void

Bits number

1

8

+

+

+

+

d>

--

Wrapper class

Boolean

Byte

Character

Short

Integer

Long

Float

Double

Void

This table can be a simple look, but it is not recommended to spend too much time (actual development is not necessary, if it is necessary to remember the exam). Because the Java language is popular, it is hoped that programmers can consume less effort in grammar, and thus save more time to tidy up specific business logic. In the basic data type this piece, Java provides the automatic boxing mechanism, below briefly introduces the automatic boxing.

Automatic Boxing in 1.1.2Java

Automatic boxing can be simply understood to encapsulate the basic data type as an object type to conform to the Java object-oriented. For example, you can directly copy an int value to an integer object

Declares an integer object integer num = 10;

Automatic boxing, there is a detail point is " for values from –128 to 127, they are boxed into an integer object, there will be in memory is reused, there is always only one object ", test as follows

Number of integers outside the -128~127 num1 = 297;   Integer num2 = 297;           System.out.println ("num1==num2:" + (num1==num2));                     Number of integers within -128~127  = num3;   Integer num4 =;   System.out.println ("NUM3==NUM4:" + (num3==num4)); Test result: Num1==num2:false  \  n   

Sometimes, you can only use a wrapper class, not a basic data type, such as a collection

Detailed details can be found in the blog (Java Auto-boxing and unpacking (autoboxing and unboxing), Java Automatic Boxing and unpacking)

1.2 Where to save the base data type

The base type is stored in the stack, in efficiency, and the base type is saved in the stack. To extend, the wrapper class is kept in the heap (note what I said earlier-wrapper class Integer between 127 and 128 )

1.3 A simple introduction to the stack (this is not much related to the basic data type is the extension content)

The Java Heap is a run-time data area that does not require program code to be explicitly released and is responsible for garbage collection. The advantage of the heap is that the memory size can be allocated dynamically, and the lifetime does not have to tell the compiler beforehand (because it is dynamically allocated memory at run time, the Java garbage collector automatically collects the data that is no longer used). However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time.

The advantage of the stack is that the access speed is faster than the heap, after the register, the stack data can be shared. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. The stack mainly contains some basic types of variable data (int, short, long, byte, float, double, Boolean, char) and reference data type (this is not related to the basic data type, do not introduce more)

1.3.1 Data Sharing Simple Introduction

The share of the base data type is not the same as the object, the object share is essentially a reference, the object modification affects the other variable, the base type is only the shared value, and when the change is made, the variable is actually re-pointing to another place.
public static void Main (string[] args) {int a = 5; int b = 5;//must first look for the stack there is no 5, there let B also point to 5 a = 6; First find the stack there is no 6, if not the new 6 and let a point
System.out.println (b); }

1.3.2 local variable and member variable save location Simple introduction

For member variables and local variables: member variables are external to the method, variables defined internally by the class, and local variables are variables defined inside a method or statement block. Local variables must be initialized.

    • The formal parameter is a local variable, and the data for the local variable exists in the stack memory. Local variables in the stack memory disappear as the method disappears.
    • The member variable is stored in the object in the heap and is collected by the garbage collector
1.class BirthDate {
2. private int day; Day is a member variable
3. private int month;
4. private int year;
5. Public BirthDate (int d, int m, int y) {
6. Day = D; D is a local variable
7. Month = m;
8. Year = y;
9.}
10. Omit the Get,set method ...
11.}
1.3.3 A simple introduction to constants in Java
    • Hexadecimal integer constants: When in hexadecimal, you need to start with 0x or 0X, such as 0xaa,0x9f.
    • Octal integer constant: octal must start with 0, such as 0123,034.
    • Long integer: Long integer must end with L, such as 9l,342l.
    • Floating-point constants: Because the default type of the decimal constant is double, you must add F (f) after the float type. The same variable with decimals defaults to the double type. such as: float f;f=1.3f;//must declare f.
    • Character constants: Literal constants are enclosed in two single quotes (note that string constants are enclosed in two double quotes). The characters in Java account for two bytes.
1.4 "type conversion" for Java primitive types

There are two ways to convert a simple type of data: auto-convert and cast, usually in an expression or when a method's arguments are passed.

1.4.1 Automatic Conversion: It is the JVM that automatically helps us convert based on conditions, so you can get a quick look at the conversion rules.

When a smaller data is calculated with a larger data, the system will automatically convert the "small" data into "big" data and then perform the operation.

These types from "small" to "large" respectively (Byte,short,char)--int--long--float-double, here we say "big" and "small", not refers to the number of bytes occupied, but refers to the size of the range of values. So byte--char--short can not be automatically converted between

1.4.2 Cast:

When converting "large" data to "small" data, you must use forced type conversions. That is, you have to use the following statement format: int n= (int) 3.14159/2; it can be imagined that this conversion could lead to a drop in overflow or precision

    1. The data type of the expression automatically increases the value of the Byte,short,char type of eg all will be promoted to the int type;
    2. Wrapper classes and basic type conversions: In fact, Java has an automatic boxing mechanism that he can convert automatically. However, we can use the constructor to turn the wrapper class, and the wrapper class to the basic type with the wrapper class object's Xxxvalue ().
    3. Convert to string between other types: the string conversion method of the ① call class: X.tostring ();  ② Automatic conversion: x+ ""; ③ method of using String: string.volueof (X);
    4. The string to other type ① is first converted to the corresponding wrapper instance, and then the corresponding method is called to convert to the other type new Double ("3.1"). Doublevalue (). or double.valueof ("32.1"). Doublevalue () ② static Parsexxx method String s = "1"; byte B = Byte.parsebyte (s);
    5. The date class interacts with other data types: There is no direct correspondence between the integer and date classes, except that you can use the int to represent the year, month, day, time, minute, and second, thus establishing a correspondence between the two. Specific conversions, which may be used in the format class
1.4.3 Notes

Only Boolean does not participate in conversion of data types

Two: String type

String is very widely used in real-world development. As a result, the Java designer has made a lot of optimizations for string to improve efficiency, which improves the efficiency of the program, but to a certain extent it will also improve the difficulty of our development, so in thinking in Java, the string as a separate chapter. I'll summarize the string as a whole, some specific ways to query the API (Java API)

2.1 String Creation Method

New is based on the standard object-oriented syntax and there is a great waste of memory usage. Therefore, the creation of a string object does not require new (which improves efficiency, but does not error if you create a string with new)

2.1.1 Here, to extend, there are five ways in which objects are created in Java:

Are the new keyword, the class newinstance method, the newinstance method of the constructor class, and the clone method of the string object. , and the deserialization mechanism. But the string object also has a special way of creating it by using the " or" wrap character sequence

    public static void Main (string[] args)    {        String s = "Hello world!"; /actually when "" the Java created the object        
}

The following code details the difference between the normal form of Java creation ("") and the new (refer to the java:string from the in-depth understanding)

public static voidMain (string[] args) {String S1 = "ABC"; ↑ An object was created in the string pool S2 = "abc"; ↑ String Pool already exists object "ABC" (shared), so create 0 objects, accumulate an object System.out.println ("S1 = = S2:" + (S1 = =S2)); ↑true points to the same object, System.out.println ("S1.equals (S2):" +(S1.equals (S2))); String s3 = new String ("ABC"); ↑ created two objects, one stored in a string pool, one exists in the heap area;//↑ also has an object reference s3 stored in the stack string s4 = new String ("ABC"); ↑ an "ABC" Object already exists in the string pool, so only one object is created in the heap System.out.println ("S3 = = S4:" + (S3 = =S4)); The address of the ↑false S3 and S4 Stack is different, pointing to the different address of the heap area System.out.println ("S3.equals (S4):" +(S3.equals (S4))); The values of ↑true S3 and S4 are the same System.out.println ("S1 = = S3:" + (s1==S3)); ↑false Storage area Many different, one stack area, a heap area System.out.println ("S1.equals (S3):" +(S1.equals (S3))); ↑true values are the same/** * Scenario three: * Because the value of a constant is determined (optimized) at compile time. * Here, "AB" and "CD" are constants, so the value of variable STR3 can be determined at compile time. * This line of code compiles the effect equivalent to: String STR3 = "ABCD"; */String str1 = "AB" + "CD"; 1 objects of String Str11 = "ABCD"; System.out.println ("str1 = Str11:" + (str1 = =STR11)); /** * Scenario Four: * Local variable STR2,STR3 stores the address of two detained string objects (intern string objects)
* The third line of code principle (STR2+STR3): * The runtime JVM will first create a StringBuilder class in the heap, * at the same time complete the initialization with the detention string object that str2 points to, * and then call the Append method to complete the merge of the detention string pointed to by STR3, * The ToString () method of StringBuilder is then called to create a string object in the heap, * Finally, the heap address of the newly generated string object is stored in the local variable STR3
* While STR5 stores the address of the detention string object corresponding to "ABCD" in the string pool. * STR4 and STR5 address of course not the same. * There are actually five string objects in memory: * Three detention string objects, a string object, and a StringBuilder object. */string str2 = "AB";//1 object String str3 = "CD";//1 object String str4 = str2+str3; String STR5 = "ABCD"; System.out.println ("STR4 = STR5:" + (STR4==STR5)); False//↑------------------------------------------------------over/** * Scenario Five: * Java compiler pair string + base type/constant is optimized as a direct evaluation of a constant expression. * The two strings of the runtime are added, resulting in a new object, stored in the heap (heap) */ string STR6 = "B"; String STR7 = "a" + STR6; String str67 = "AB"; System.out.println ("STR7 = str67:" + (STR7 = = str67)); ↑STR6 is a variable that is parsed at run time. Final String str8 = "B"; String STR9 = "a" + str8; String str89 = "AB"; System.out.println ("STR9 = str89:" + (STR9 = = str89)); ↑STR8 is a constant variable and the compilation period is optimized}
2.1.2 A simple summary:

When you create an object with "", the string object is placed in a constant pool, and only one is created, and each time you look for a constant pool.

Create an object with new, create an object in the team, and then create the object app within the stack, each time it's newly created

2.2 String class is immutable after initialization (immutable)

The string class is immutable after initialization, because the Java designer does not want our method to pass arguments as strings, and in-method modifications affect the outer strings, so we take a way of passing copies (that is, passing values).

string SS = "This is the Origen String"; Teststring.showstring (ss);p ublic static void showstring (String s) {    System.out.println (s);} 
2.2.1 What's the matter of string immutable in Java

In Java, once a string object is produced, the object will not change. But string on the other hand does provide a way to modify the string. This seems contradictory, in fact, we don't have a thorough understanding of the methods of modification.

For example, replace (), if you can see the source code, it is clear to see that the method actually creates a new string, the replacement operation is for the new string. (Refer to the Java Advanced String class for a simple indication of when the replace () method is invoked

Change of s)

                                  

The following code: I added a sentence based on the original string, and then judged whether they are the same (if the same object is modified, = = The output should be true)

String S1 = "I";

s1+= "I want to add something";
System.out.println (S1 = = s2)//output is False

Think about the "what is the string in the object that S1 points to" (we subconsciously think that S1 will also be modified, but when s2 = "S2", actually S2 's reference has been modified, it doesn't matter to S1)

String S1 = "S1"; String s2 = s1;s2 = "S2"; What is the string in the object that the//s1 points to?
System.out.println (S1);//output is S1

Again, either the method of modifying the string or assigning a value to a string is different from a normal object. The assignment is to have the string point to a new string, and the method argument is a copy of the value, passed in.

Again, for example: String str= "kv" + "ill" + "+" ans "; There are 4 string constants, first "KV" and "ill" generate "Kvill" in memory, then "Kvill" and "Generate" Kvill "exist in memory, and finally generated" Kvill ans ", and the address of the string to the Str

So the + will produce a lot of temporary variables. The following will talk about StringBuilder to avoid this situation. But there is a special case. "AB" + "CD" is the same as "ABCD" after the JVM has been compiled

String str1 = "AB" + "CD";  1 Objects of  String str11 = "ABCD";   

2.2.2 Java is how to do the immutable string

In string source code, the use of private final char value[] to implement the storage of the string, that is, because final, the string type is immutable

/** The value is used for character storage. */    Private final char value[];
2.3 Where string is saved

In a little bit, let's look at where the string is stored (you can refer to the difference between the java+ memory allocation and the storage location of the variable [],java in the string-class constant pool]

String constants are saved in a constant pool. The Chang in the JVM exists as a table in memory, and for string types there is a fixed-length constant_string_info table for storing literal string values, note that the table stores only literal string values and does not store symbol references. In this case, there should be a clearer understanding of where the string values in the constant pool should be stored. When the program executes, the constant pool is stored in the method area, not the heap. There are many string objects stored in a constant pool and can be shared so that it improves efficiency

What is a constant pool

Chang refers to some data that is determined at compile time and is saved in the compiled. class file.

In addition to the constant values (final) that contain the various basic types defined in the code (such as int, long, and so on) and object types (such as strings and arrays), there are also some symbolic references that appear as text.

2.4 Main methods
  • S.length () returns s string length
  • S.charat (2) returns the characters in the S string labeled 2
  • S.substring (0, 4) returns a substring of 0 to 4 in the S string
  • S.indexof ("Hello") returns the subscript of the substring "Hello"
  • S.startswith ("") determines whether s starts with a space
  • S.endswith ("oo") to determine if S is "oo" end
  • S.equals ("Good world!") Determining if S equals "good world!" = = only determines if the string is stored in the same location. You need to use Equals () to determine whether the contents of the string are the same.
  • S.compareto ("Hello nerd!") Compare S string with "Hello nerd!" In the order of the dictionaries, return an integer if <0, stating S in "Hello nerd!" Before if >0, explain s in "Hello nerd!" Then if ==0, explain s with "Hello nerd!" Equal.
  • S.trim () Remove the space string around s and return the new string
  • S.touppercase () converts s to uppercase and returns a new string
  • S.tolowercase () converts s to lowercase and returns a new string
  • S.replace ("World", "Universe") replaces "world" with "Universe" and returns a new string
2.5: Brief summary of details in string

On the whole, if you're still confused about string, you might as well hold on to the "Create Time" if you know what it is and throw it into a constant pool.

    1. The strings created by using the "" quotation marks alone are constants, and the compilation period is determined to be stored in the string pool;

    2. Objects created with the new String ("") are stored in the heap and are newly created at run time;

    3. A constant is created with a string connector that contains only constants, such as "AA" + "AA", and is determined by the compilation period and is determined to be stored in the string pool;

    4. The object created by using a string connector containing a variable, such as "AA" + S1, is created at run time and stored in the heap;

    5. Intern (): string instance calls this method to let the JVM check the constant pool, if there is no string sequence corresponding to the Value property of the instance, put this instance into a constant pool, if any, return a reference to the corresponding instance in the constant pool instead of the current instance

2.6 StringBuilder and StringBuffer and +

First StringBuilder and StringBuffer differences are stringbuffer thread safety (there is a heap of synchronized)

Secondly, we recommend using StringBuilder instead of +, although the + number is essentially built StringBuilder in the JVM, but every s = s+ "1", a StringBuilder object is introduced

  String [] aaa = {"1", "2", "3"};  for (String s:aaa) {            s+= "1";//each cycle produces a StringBuilder object}  

In addition: StringBuilder allows us to specify the size at the time of the declaration, to avoid multiple allocations of cache

Three: Java reference types

Java has 5 reference types (object types): Class interface Array enumeration callouts.

New objects are placed in the Java heap, and then the references are placed on the stack, which is not described in more detail.

  

Java data types are used in real-world development

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.