preface


Two days ago, I agreed to write a Java string, but now I have to start. To be honest, WHEN I first learned strings, I also encountered a little trouble, but fortunately, it was solved. (PS: As I write this article, my once steadfast ideals begin to waver, which I’ll leave at the end.)

The general structure of the article is as follows:

Try to think of some of the questions the interviewer will ask you about the title of the essay. The main focus of this article, then, is to further understand the immutability of strings.

The basic use of strings


I’m going to talk about strings in two directions:

  • Start by creating a string
  • Learn to use strings in the API

Start by creating a string

There are two ways to create string objects:

  • Create directly (also called using literals)
  • Use the keyword new

Take a look at the following example:

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) {
        String name = "Yangc";   // The literal is created directly
        String school = new String(Chongqing University of Posts and Telecommunications);  // Use the keyword new}}Copy the code

The above code creates two strings, the first using the literal method and the second using the keyword new. Simple. As for the difference between the two, we’ll talk about it later.

Learn to use strings in the API

Java strings provide a plethora of apis for us to use, and it would be impossible to list them all, which would defeat the purpose of this article. Let me just say a few common ones:

Get the length of the string

The length of a string is calculated using the length() method. Note that this is distinguished from the length of an array, which has no parentheses, whereas a string has parentheses.

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) {
        String[] arr = {"A"."B"."C"};  // Define an array of 3 lengths
        String school = new String(Chongqing University of Posts and Telecommunications);   // The length of the string is 6

        System.out.println(arr.length);  // Output: 3
        System.out.println(school.length()); // Output: 6}}Copy the code

Concatenate two strings

Concatenate two strings using the method concat(String STR) of the form string1. Concat (string2); Here’s an example:

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) {
        String name = "Yangc";   // The literal is created directly
        String school = new String(Chongqing University of Posts and Telecommunications);  // Use the keyword new

        String newString = name.concat(school);  // Concatenate two strings
        System.out.println(newString);  Yangc Chongqing University of Posts and Telecommunications}}Copy the code

Access the character that determines the position

We’ve given a string in advance, we know where a character is in the string, and now to get the character out, we use the charAt(int index) method. This method returns a character at a certain position. Here’s an example:

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) {
        String name = "Yangc";   // The literal is created directly
        String school = new String(Chongqing University of Posts and Telecommunications);  // Use the keyword new

        char newChar = school.charAt(1);
        System.out.println(newChar);  // Output: celebrate}}Copy the code

Intercept string

Given a string and only one part of it is needed, the substring() method takes a part of the string:

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) {
        String name = "Yangc";   // The literal is created directly
        String school = new String(Chongqing University of Posts and Telecommunications);  // Use the keyword new

        String subString = school.substring(1.3);
        System.out.println(subString);  // Output: Qingyou}}Copy the code

Ok, so let’s talk about these methods. Using the methods described above in combination, you can perform various operations on a string. More on this: Beginner’s tutorial -Java string apis

Understand string immutability in depth


As mentioned at the beginning of the article, I suffered a loss in understanding the immutability of strings. Fortunately, under the guidance of my predecessors, I finally realized it, but it also made me realize the importance of learning English more.

If only learned the content in front, so can only be said to have learned a corner of the ice. Now, I’m really starting this article.

The memory model of the Java virtual machine

To understand this thoroughly, we need to know a little bit about the Java Virtual machine. So what is a Java virtual machine? Here’s a quote from the wiki:

1. Java Virtual Machine (Java Virtual Machine, abbreviated as JVM), a Virtual Machine capable of running Java Bytecode, implemented as a stack structure Machine. The first version was developed and implemented by Sun Microsystems, which is part of the Java platform and can run software programs written in the Java language.

2. Java virtual machine has its own complete hardware architecture, such as processor, stack, register, etc., as well as corresponding instruction system. The JVM shields platform-specific information, allowing Java programs to run unmodified on multiple platforms by generating object code (bytecode) that runs on the Java VIRTUAL machine. An implementation that executes compiled Java program code (applets and applications) through a software implementation executed on the central processing unit (CPU).

3. The virtual machine as a programming language is not only dedicated to the Java language, but any language can be compiled and run by the JVM as long as the generated compilation file complies with the JVM’s requirements for loading the compilation file format. In addition, there are other open source and closed source implementations besides Oracle.

Wikipedia explains quite a few concepts, and I thought it would be useful to distill the information:

  • The JVM is a virtual machine that executes Java Bytecode, or bytecode.
  • Thanks to the JVM, the Java language is cross-platform.
  • The JVM can be used for other languages as well as for the Java language.

To start with, the compiler will compile the source file (.java) into a bytecode file (.class). The Java virtual machine will only operate on the bytecode file, not the source file. It is the combination of the JVM and bytecode that makes Java programs cross-platform. Here’s a quick overview of how the JVM actually works inside.

But first, take a look at the JVM memory model:

When Java programs are executed, the computer’s memory is dedicated to a contiguous area of memory made up of five parts (see figure above). The red area is shared by threads, the green area is unique to threads, and the program counter is the only area that does not leak memory. Introduction to the JVM Memory Model

With that in mind, there’s something called a constant pool, and there are two kinds of constants:

  • Static constant pool: the static constant pool is the constant pool in *. Class files. The constant pool in class files not only contains string (number) literals, but also contains information about classes and methods, which occupies most of the space in class files.
  • Runtime constant pool: Runtime constant pool refers to the constant pool of bytecode loaded into the method area when the JVM executes a bytecode file.

By constant pool we usually mean run-time constant pool.

Now, it’s time to explain the differences between the previous two ways of creating strings.

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) {
        String name = "Yangc";   // The literal is created and stored in the string constant pool
        // Using the keyword new, a space is created on the JVM heap for storing objects
        String school = new String(Chongqing University of Posts and Telecommunications); }}Copy the code

For a more graphic illustration, take a look at the following chart:

It should be noted that before JDK1.6, string constant pooling was in the method area, while in JDK1.7 and later constant pooling was moved from the method area to the heap area and the rules changed accordingly. Next, I’ll go into more detail about String immutability (multigraph warning ⚠️).

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) {
        String name = "Yangc";   // The literal is created and stored in the string constant pool
        String school = new String(Chongqing University of Posts and Telecommunications);  // Creates a space on the JVM heap for storing objects

        name = "Three small";  // Creates a new object in the constant pool string. The original "Yangc" still exists in the constant pool
        System.out.println(name);   // Output: three small}}Copy the code

That’s the immutability of strings, simple, clear and impressive. They say learning without practice is useless. Now, you need to complete the exercise below.

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) {
        String name = "Yangc";   // The literal is created and stored in the string constant pool
        String newName1 = "Yang" + "c";
        String newName2 = new String("Yangc");
        String newName3 = "Yangc" + "hao";
        String newName4 = name + "hao"; System.out.println(name==newName1); System.out.println(name==newName2); System.out.println(newName3==newName4); }}Copy the code

The following output is displayed:

Now let’s talk about them separately:

  • Name ==newName1, the output is true. The Java compiler optimizes the “+” sign, which is equivalent to newName1 = “Yangc”, and the string created by neme = “Yangc” exists in the string constant pool, in which case they point to the same string. That’s going to be equal.

  • “Name ==newName2”, the output is false. Name refers to “Yangc” in the string constant pool, and “newName2” refers to the “Yangc” object in the heap, so the two are different.

  • “NewName3 ==newName4” is displayed as “false”. The compiler does not optimize the variable name, so name is unknown, so newName4 = name + “hao” is also unknown. Therefore, the output is false.

Talk about intern()

Let’s take a look at the code first, and then explain the function:

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) { 
        String s = new String("Yangc");
        s.intern();  // Set up a connection in the string constant pool, point to the heap space, and return the reference}}Copy the code

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) {
        String s = new String("Yangc");
        String s1 = "Yangc";
        System.out.println(s.intern() == s1);  // Output: true}}Copy the code

After calling the s.intern() method here, go back to the string constant pool to see if “Yangc” exists, and return the string if it does. There is no difference in JDK versions, but if the string does not exist in the string constant pool. JDK1.6 and before will create this string in the constant pool, and JDK1.7 and after will create a reference in the constant pool to the object in the opposite space, as shown in the figure above.

Strings that can change: StringBuilder

Java strings are immutable, but StringBuilder is used when we need to dynamically alter an existing string. Take a look at the following examples:

/ * * *@author Yangc
 * @TimeThe 2020-5-23 *@ActionImmutability of strings */
public class Test {
    public static void main(String[] args) {
        StringBuilder builder = new StringBuilder("Yang");
        System.out.println(builder);  // output: Yang
        builder.append("c");   // Call the append method
        System.out.println(builder);  // output: Yangc}}Copy the code

Here, we create a StringBuilder object, which is a mutable object that can be added dynamically. More related operations: StringBuilder

The road to the future


It has been nearly two years since I graduated from high school. I can’t help but sigh, how fast time flies! Last year, the summer after my freshman year, I wanted to write this summary, but for some reason I didn’t. Later, I want to write at the end of the winter vacation of sophomore year, but I am not a hard-working person, put off, until now. I finally want to seriously type a keyboard, write their own journey (I know, I may not deserve, hey hey). After all, I am a lazy person, and I don’t like to be constrained, nor do I like metaphysical things.

For the past two years

High school graduation of that I have gone, that just out of the mountain, a face of green youth, has passed in the long river of time. People, will grow up!

With a confused report card, accidentally knocked open the university gate, I was not ready, has become a college student. When I was a child, I wanted to grow up quickly, and when I grew up, I wanted to go back to my childhood. The minute I got the notice, I knew it was over.

So began my freshman year. It was raining during the military training, which was the most comfortable military training I had ever had. My freshman year was very ordinary. I joined a calligraphy club and a student union department, became the assistant of a counselor, participated in the school sports meeting and won a modest prize. I participated in my first marathon (which was a little wish of mine when I was young) and maintained my initial love for competitive sports. At the beginning of the second semester of freshman year, I also felt endless confusion. That’s when I started working part-time (the stupidest decision I’ve ever made, but I’m still proud of it), made $6 or $7, and got a new computer. Then I got into the front end and wrote for a while, but I gave up.

During the summer vacation of my freshman year, I stayed in school and planned to get my driver’s license at school and study hard with my seniors in the school lab. When I was too shy, I didn’t learn much. It was also the driver’s license that delayed me too long. It was also due to my stubborn character, which always liked to finish one thing before starting another.

Sophomore so began, I did not expect to become a class leader, I have to guide my younger students to prepare for school. I was devastated by the fact that I had become a senior with the counselor (which I now see as a mirror image), being involved in the entire grade’s scholarship process, student work, and the crazy final exams of my sophomore year. In the end, I flunked Signals and Systems. Three days was not enough time, which I knew as soon as I finished the test (40% fail rate + not really a brag). So, I gave up the back of the exam, all naked test… Consequences can be imagined, the back of the three doors, only “analog circuit” drift, other all hung. Like simple “probability theory”, there are usually did not listen to the “university physics” (in fact, university physics is really very difficult) all failed.

Actually, the real change didn’t begin until the end of my sophomore year. I also began to have a sense of crisis, AND I began to think about my career after college, what I could do after graduation. With this question in mind, I thought about it for two days, and finally chose the mobile Internet industry. I decided to learn Android from scratch. Once the goal was set, I began to learn without control. First learned Java language, followed the video to learn, brush a lot of big blog, read the core technology of this book, also can be regarded as a systematic learning Java language. Then, I began to learn Android, ahead of the big bull to lead the way, I feel that I still learn quite fast. So I began to write notes in Jane’s book, just for my own reading, of course. Later, I knew that large companies value the basis of computer, so I began to learn computer network, data structure and algorithm, plus my original major courses, several times stayed up all night, often after 3 o ‘clock in the night. I don’t think I worked this hard in high school, especially when I had to go out and play basketball for 30 minutes between classes my senior year. In fact, I wonder how I ever got into college.

Well, I now talk about why I choose the Internet. I think one of the most important reasons is that my family is poor. For me, a poor child who came from the mountains, what I want to know most is how to make money, which is also an important reason for my part-time job in freshman year. The average person may not know, the Internet industry, is not comparable to other industries. You can see a bachelor’s degree on graduation to take more than ten, two hundred thousand annual salary, this in other industry people look is impossible to happen, in the Internet industry is very common (of course the premise is that you have to study hard, and the ability of self-study is very strong).

Focusing on the present

I later learned that the mobile web had leveled off and started to decline, and Android was dead. This for me, obviously is not willing to, do I choose the road is wrong. A couple of days ago, one of my direct seniors in Bytedance also said that the mobile Internet is really not working. My heart began to touch a little, do I want to switch to Java? These two days, my heart is really quite not calm, now a lot of people rush to Java, a few years when Java is not popular what to do? This is a world of contradictions, and a world in which contradictions are resolved, and in such a cyclical process, the human process continues to advance. I think I’ll see it more clearly as I go along. In a word, the basic knowledge of computer is very important now, which is what I am most concerned about (of course, I also care about my professional courses fail).

In the future

College, let’s talk about the rest of sophomore year. Recently, I have been preparing for the final exam and the make-up exam of last semester. I think this is the most important thing for me in this week or two. It would be a waste of time to take the make-up exam or retake it. (I don’t want to take the make-up exam again.) In June, after the make-up exam is over, that is, on June 7th, I can start to prepare for the review of data structure and algorithm (also known as preview) and sort out the relevant knowledge of computer network, hoping to help my friend in the final exam. Before the end of the exam and the arrival of the summer vacation, I have to sort out some current knowledge of Java and Android, write some articles and sort out my knowledge structure.

If I could stay for the summer, I would definitely stay. At this time it is important to prepare for the first semester of the junior autumn recruitment, one year in advance to prepare is also very good. I think this summer vacation must be more than others to find my wasted time before, in order to get more initiative in the autumn recruitment.

As for the next decade, I do not have a clear outline, but I know that since I have chosen the road of the Internet, it is a risky and bumpy road, so I must keep learning. Technology update is very fast, once you stop learning, you can only be eliminated. I think I like this kind of life, unconstrained, advocating freedom. A cup of coffee, a high-quality MBP, writing all afternoon.