[Java plasterer] Java components: Java String (there must be something you don't understand.)

Source: Internet
Author: User

Mud and brick pulp carpenter
Website: http://blog.csdn.net/jeffli1993
Personal signature: The person who intends to work out a masterpiece is often unable to insist on completing the first chapter.
1.1 Preface

Speaking of string, we are most familiar with it. That's what I said, but it seems like there's a lot of detail in the familiar, or something we don't know. Often there are many old things that burst out with a lot of light points. For example, author Mason recently found a 100 cash in winter jeans (not happy). Back to the point, let's talk about the following string below. Divided into two parts:
Base part: (JDK source document)

    • 1.2 Hello String
    • 1.3 String string manipulation

Extension section:

    • 1.3 = = equals not in-laws
    • 1.4, it's not difficult for Masons to recruit again.
    • 1.5 equals meet n long string?
    • 1.6 Intern Magical

The landlord is not the character of Daniel, Mason has always thought that "the people who want to work out a masterpiece, often can't insist on completing the first chapter." "So, with the keyboard, listen to the music you like." Humorous to you that I understand the experience.
(I hope Daniel points out the mistake, thank you very much!) )

1.2 Hello String

With the first sight of you, Masons open JDK1.7 documents with you. I recently want to write some understanding of JDK1.7, all know JDK8 come out, new features I am ready to study in the next stage.
Masons want to say that reading the E-document is beneficial to the authenticity. But after all, the domestic Daniel translation is very good, we do not judge, like what kind of self-pick. Can catch mice, can solve the actual project, adapt to the business environment is what you learned. Take a look at the following small example:

Listing 1.1

String ABC = "ABC"char data[] = {' A ', ' B ', ' C 'new  String (data); SYSTEM.OUT.PRINTLN ("abc"= "CDE"; SYSTEM.OUT.PRINTLN ("abc" += "abc". SUBSTRING (2,3= cde.substring (1, 2); System.out.println (c); System.out.println (d);

Mason, aren't you kidding me? So simple program, what do you want to say. It is really the foundation, but the foundation is solid to have a higher breakthrough. Just want Masons silently for themselves, for the family for the future lay the groundwork.

As you can see, string is a class that does not need to create a new object using new. It is immutable (Constant), and its value (like "ABC" is created, cannot be changed). Naturally, string actually implements the function of the sequence of the basic type char, so the Chinese name "string". Here it is possible to doubt that Mason will find the JDK source code evidence to show you:

This code is from the JDK1.7 source, the Char type value array form the contents of the string class. Its operation is for the value array operation. Such thinking whether the enlightened, and then in the heart self-pleased "so easy." In fact, under the difficult point, we slowly look down.

1.3 String string manipulation

Still looking at the code listing 1.1,java provides a special connection operator (concatenation operator) + for directly stitching strings. The methods commonly used in these operations are listed below:

Method effect
s.length ()                        returns s string length S.charat (1)                       returns the character of the s string labeled 1 s.substring (0, 2)                 Returns the substring of the S string subscript 0 through 2 s.indexof ("NSG")                  returns the sub-string "NSG" Subscript s.startswith ("")                 Determines if s starts with a space S.endswith ("End")                 to determine if s ends with "end"

Follow the Masons run under listing 1.1 and you can see the print out:

Abcabccdecd

It is easy to find the answer is what we want in the mind. I'm not going to explain the API in detail here, which will lose interest in the article and the reader. I like to use examples to guide the summary of string in my project and experience.
here is the substring () method to explain the next source, you can see the implementation of the details:

The logic is broadly summarized as follows:
1. First determine the incoming reliability, determine the beginning and end of the incoming, and the length of the substring. This is what needs to be cared for in detail in every system development. Care for details, to do great things.
2. Then the judgment is not the original string, if yes, return this directly, if not the new substring. This constructor implementation is also not difficult, if you are interested to see, in fact, the implementation of a char array copy.

Here is what we can draw from the conclusion that the design originates from life and is derived from simplicity. Like a method and a class structure of the design, single simple. So we study the design method to be simple, the coupling degree can not be too high. Here, the reader can listen to a song first, such as what the Piano, what Moonlight song. The rest will continue to speak.1.3 = = equals not in-laws

Some people see this will be surprised, and then questioned that "the teacher said, String and = = no matter, you are not nonsense". Haha, I can only say, but practice in practice. Give me a little chestnut.
See listing 1.2 below

Static String B = "AB"privatestaticvoid= "a" + "B"= = b);}

See here, whether you feel so simple, in the mind is certainly "false, Mason really funny." "Run, the result is

True

       Conclusion: about = =, we want to know = = is used to match the contents of the memory unit. Java compares the contents of two memory units (in fact, a bunch of numbers). As for the eight basic types of direct comparison values. For example, listing 1.2 compares two references, and two references compare the logical values of the referenced objects (that is, the contents of the memory cells for the two objects).


Mason's Memory Palace : that is the equivalent of Masons and my sister compared to the two of our fathers, after all, the father is that one, of course, is true.

What is the life of "a" + "B"? Some anti-compilation of the network bull will find a process similar to the following:

New StringBuilder (); Temp.append ("a"). Append ("B"return temp.tostring ();

How does the JVM know they are the same as "a" + "B" and "AB"? We look back, because string is an immutable class, which is the characteristic of the static Java language. This involves the JVM's optimization scheme. But the JVM is very rigid, it is not very artificial intelligence like the human brain, it will only be able to handle it, so a good understanding of the JVM helps to develop a better amount of programs. For example, define an AB string constant enough, it will not be in the substring a B. This is the optimization scheme.
Mason's Memory Palace : This is lazy thought, today I want to see my father, tomorrow sister to see Dad. Together, the day after tomorrow to see Dad.
In this context, we can conclude that the compiler gives me the optimization of the program, in order to improve the efficiency of the program and memory resources, so we can understand how to master its characteristics to write better code.

1.4, it's not difficult for Masons to recruit again.

Add an example to see if you really know what you're up to?

Private Static return "A"privatestaticvoid= "a"= a + "b"= Geta () + "B" /c10>== "AB"= = "AB");}

this involves optimization of the JVM, and the answer is:
false false

If you guessed it, prove that you know it. The Masons are also patiently explained under the following:
The first false:b is to include a constant and a reference value, so.
Second false: You can also guess that the constants of an external method are just a reference in this method. So.
The conclusion is as follows: If we do not know how the JVM is optimized at compile time, we will understand them slowly.

1.5 equals meet n long string?

This example is not good to write, Mason will take you to see the source code and so on. Equals is not unfamiliar, I believe everyone's system inside there are many design to this method.

In fact, equals is the Equals method that implements the object, while the Equals in object:

It is actually realized = = Compare the contents of memory.
Q: Mason, why is string rewriting object, does this not cause any inconsistency in meaning?
A: Non-Also, string is the thing that String,string uses to handle the logic and the business and object are completely different. Equals, as the name implies, does not mean exactly equal. But the same or similar. is the so-called business to see the situation, such as Mason processing financial data is generally a decimal point of 10, then you will also care about the value of the decimal point 10, when they compare, you do not care, so this is similar.

So let's take a look at the Equals method implemented by string:

Simply described, the best condition to traverse two arrays is either a different length, or a few differences in the front. returns false directly.
Q: It's tragic if you hit a big string. So how do some large strings handle it.
A: Actually, the large string is difficult to see. But to deal with it, the big string match can be considered as a split match or something that doesn't unfold here.

Q: Does the equals rewrite have anything to do with hashcode?

A: Here we first explain the Hashcode method provides the Hashcode value of the object, and returns the same as the default System.identityhashcode (). It is widely used in the collection framework. I'll talk about it in the back. The hashcode of the computer is derived from the numbers, not the objects. So a Hashcode value identifies an object that produces many algorithms related to the object. However, the default hashcode is very expensive to initiate local calls.

Good tired tired, Mason drink saliva, finish the following, we string to this end.1.6 Intern Magical

Intern people are a little strange. We first have to popularize the concept of a constant pool, Chang (constant pool) refers to some data that is determined at compile time and saved in the compiled. class file. It includes constants in classes, methods, interfaces, and so on, and also includes string constants. Then take a look at the following example:

Private Static void Test5 () {    = "a";     = A + "b";     = "AB";     New String ("AB");     = = D.intern ())    ; = = D.intern ());}

When the Intern () method is called, the JVM looks through the Equals () method in this constant pool to find out if there is an equivalent string, and if so, returns the address of the string object in the constant pool, if it is not found, the equivalent string is created and the address is returned.
Thinking about Ascension : What is the use of this?
Answer: can be used for some constant storage comparison, enumeration (enumeration is the bottom of the string, haha). When you think of constants more than constants, in most cases, consider efficiency by choosing intern () instead of equals.

Summarize

String is an important part of the Java Foundation component. I slowly summed up the Java EE Component Architecture and then added the content in. Still, the Mason wants to say:

if the above articles or links are helpful to you, don't forget to click the "Like a" button on the article button or in the bottom right corner of the page. You can also click on the right side of the page "share" hover button oh, let more people read this article

[Java plasterer] Java components: Java String (there must be something you don't understand.)

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.