[Java guru] One of Java Components: Java String (you certainly don't understand), componentsstring

Source: Internet
Author: User

[Java guru] One of Java Components: Java String (you certainly don't understand), componentsstring

Author: sand, brick, and mortar carpenter
Website: http://blog.csdn.net/jeffli1993
Personal Signature: the person who intends to write a huge work in Hong Kong may not be able to complete the first chapter.

1.1 Preface

Speaking of String, everyone is most familiar with it. I also said that, but it seems that there are many details in the familiar, or something we don't know. There are often many bright spots in old things. For example, the author's bricklayer recently found 100 yuan in cash in his winter jeans (not happy ). Back to the topic, let's talk about the following strings. There are two parts:
Basic Section: (JDK source code Documentation)

  • 1.2 Hello String
  • 1.3 String operations

Extensions:

  • 1.3 = not related to equals
  • 1.4 is not difficult for the bricklayer
  • 1.5 What if equals encounters n long strings?
  • 1.6 intern

The Lord is not a big bull-level character, and The bricklayer has always recognized it as "the person who intends to write a huge work in Hong Kong may not be able to finish the first chapter ." So listen to your favorite music on the keyboard. My understanding is humorous.
(Thank you very much for pointing out the mistake !)

1.2 Hello String

With the feeling of seeing you for the first time, the bricklayer opens the JDK1.7 document with you. Recently I want to write some understanding about JDK1.7, and I know that JDK8 is coming out. I am going to study new features later.
The bricklayer wants to say that reading the E document is helpful for the original taste. But after all, Chinese Daniel translation is very good. We don't need to judge which one we like to pick. You have learned how to grasp the mouse and solve actual projects and adapt to the business environment. See the following small example:

Configuration 1.1

String abc = "abc";char data[] = {'a','b','c'};String abcStr = new String(data);System.out.println("abc");String cde = "cde";System.out.println("abc" + cde);String c = "abc".substring(2,3);String d = cde.substring(1, 2);System.out.println(c);System.out.println(d);

Are you kidding me? What do you want to say about such a simple program. To be honest, it is indeed the foundation, but only with a solid foundation can we achieve a higher breakthrough. I want the bricklayer to lay the foundation for myself and for the future.

As you can see, String is a class that does not need to use new to create a new object. It is immutable (Constant), and its value (such as "abc" cannot be changed after it is created ). Naturally, String actually implements the sequence function of the basic char type. Therefore, the Chinese name is "String ". You may be confused here. The bricklayer will find the JDK source code evidence to show you:

This code is from the JDK1.7 source code. The char-type value array forms the content of the String class. The operation is to operate on the value array. In this way, I want to see whether it is clear, and then I like "so easy ". As a matter of fact, let's take a look at the difficulties below.

 

1.3 String operations

Still look at code list 1.1. Java provides a special concatenation operator + for concatenating strings directly. Common Operations are listed as follows:

Method function s. length () returns the length of string s. charAt (1) returns the character s marked as 1 in the s string. substring (0, 2) returns the substring s from 0 to 2 in the s string. indexOf ("nsg") returns the subscript s of the sub-string "nsg. startsWith ("") determines whether s starts with a space. endsWith ("end") determines whether s ends with "end"

Run List 1.1 With The bricklayer. You can see the following:

abcabccdecd

The answer is what we want. Here, I do not intend to explain the api in detail, which will lead to loss of interest in the article and readers. I like to use examples to guide and summarize the strings in my project and experience.
The following describes the source code using the substring () method. The implementation details are as follows:

The logic is roughly summarized as follows:
1. First, determine the reliability of the input, determine the start and end of the input, and the length of the sub-string. This is a concern in the details of each system development. Only when you care about the details can you do things.
2. Then judge whether it is the original String. If yes, this is returned directly. If not, a new substring is returned. It is not difficult to implement this constructor. If you are interested, you can check whether it is actually a copy of the char array.

Here we will introduce the basic part of String, where we can conclude that design originates from life and comes from simplicity. The design of a method and a class structure is simple. Therefore, after learning, the design method should be simple and the coupling degree should not be too high. Now, you can listen to a song, such as a piano or a song. The rest will continue. 1.3 = not related to equals

Some people will be surprised when they see this, and then ask, "the teacher said, String and = do not matter, are you blind ". Haha, I can only say that the practice is in reality. Let's take a look at it.
See list 1.2 below

static String b = "ab";private static void test(){String a = "a" + "b";System.out.println(a == b);}

Do you think this is so simple? I think it must be "false. It's really funny ." Running, the result is

true

Conclusion: For =, We Need To Know That = is used to match the content of memory units. Java compares the content of two memory units (actually a string of numbers ). Directly compare the values of the eight basic types. For example, in listing 1.2, two references are compared, and the two references compare the logical values of the referenced objects (that is, the content of the two objects corresponding to the memory unit ).


The memory palace of The bricklayer: It is equivalent to comparing our two fathers with my sisters. After all, the father is the one, of course, true.

What is the life of "a" + "B? Some network coders may find that the process is similar to the following:

StringBuilder temp = new StringBuilder();temp.append("a").append("b");return temp.toString();

How does JVM know that "a" + "B" and "AB" are the same. We will review that String is an unchangeable class, that is, the characteristics of the static Java language. This involves the JVM optimization solution. But the JVM is very rigid, and it will not be very artificial intelligence like the human brain. It will only be able to handle it, so a good understanding of JVM will help develop better programs. For example, if it is enough to define an AB String constant, it will not subscribe a B. This is its optimization solution.
The memory palace of The bricklayer: this is the concept of laziness. Today I want to see my father, and tomorrow I want my sister to see my father. Merge and see your father the day after tomorrow.
In this regard, we can draw a conclusion: the compiler brings me the optimization of the program, in order to improve the program efficiency and memory resources, so we can understand how to master its features to write better code.

 

1.4 is not difficult for the bricklayer

Let's add an example. Can you see if you have mastered it?

private static String getA(){ return "a";}private static void test2(){String a = "a";String b = a + "b";String e = getA() + "b";System.out.println(b == "ab");System.out.println(e == "ab");}

This involves JVM optimization. The answer is:
falsefalse

If you have guessed it, it means you understand it. The bricklayer patiently explained the following:
The first false: B contains a constant and a referenced value.
The second false: You can also guess that the constant of the external method is only a reference in this method. So.
The conclusion is as follows: if we do not know how the JVM is optimized during the compilation period, we will understand them slowly.

 

1.5 What if equals encounters n long strings?

This example is not easy to write. The bricklayer will show you the source code. Equals is no stranger. I believe there are many designs in the system.

In fact, equals implements the Object's equals method, while in the Object's equals:

It is actually implemented = the content of the memory.
Q: Why does String rewrite the Object by The bricklayer? Doesn't this cause inconsistency?
A: neither is nor is it true. String is A String. The logic of the transaction to be processed by String is completely different from that of the business and Object. Equals, as its name implies, is equal to, and does not indicate completely equal. It is the same or similar. The so-called business depends on the situation. For example, if the bricklayer processes financial data with a decimal point of 10 digits, do you still care about the value after the decimal point of 10 digits? when they are compared, you don't care, so this is similar.

Let's take a look at the equals method implemented by String:

In a simple description, the best condition for traversing two arrays is that the length is either different or the previous several differences. Returns false directly.
Q: If we encounter a large string, this is a tragedy. So how to deal with some large strings.
A: Actually, big strings are hard to see. However, if processing is done, you can consider splitting and matching large strings.

Q: Is equals rewriting related to hashCode?

A: Here, we need to first describe the hashCode value of the object provided by the hashCode method. The returned result is consistent with the default System. identityHashCode. It is widely used in collection frameworks. I will talk about it later. HashCode is derived from a computer, rather than an object. Therefore, a hashCode value identifies an object and generates many algorithms related to the object. However, the default hashCode is too costly to initiate local calls.

Tired and tired. The bricklayer drinks water and finishes talking about the following. We end here with String. 1.6 intern

Intern is a bit unfamiliar to everyone. First, we need to popularize the concept of a constant pool. A constant pool refers to data that is determined during the compilation period and saved in the compiled. class file. It includes constants in classes, methods, interfaces, and other fields, as well as string constants. Then let's look at the example below:

private static void test5(){    String a = "a";    String b = a + "b";    String c = "ab";    String d = new String("ab");    System.out.println(c == d.intern());    System.out.println(b.intern() == d.intern());}

When the intern () method is called, JVM will use the equals () method in this constant pool to find out whether the equivalent String exists. If so, the address of the String object in the constant pool is directly returned; if no value is found, an equivalent string is created and its address is returned.
Think for improvement: What is the purpose?
Q: It can be used for storage and comparison of some constants. enumeration (underlying enumeration is string, haha ). If you want to compare constants to constants, you can choose intern () instead of equals for efficiency.

Summary

String is an important part of Java basic components. I slowly summarized the J2EE Java component system and added the content. Or that sentence, The bricklayer wants to say:

If the above article or link is helpful to you, don't forget to click "like" in the article button or in the lower right corner of the page. You can also click the "share" floating button on the right side of the page to let more people read this 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.