[Java] I felt as a java beginner. "Why is the first letter of the String type capitalized?" I faced the String type.

Introduction

This is a memo of what I learned to deepen my understanding of how to handle the String type while I was learning to acquire the java silver qualification. I would appreciate it if you could point out any mistakes in the interpretation.

String type seems to be a reference type, not a basic data type

When defining a variable, I specified the data type such as ʻint, double, boolean, char, and defined the variable. When defining a variable that handles strings in the same way, it was quite natural to specify the String` type and define the variable.

Like this ↓

Variable definition.java


int i = 100
 // ->Substitute integer 100 for int type that can handle integers
char c = 'Ah'
 /* ->Char type that can handle characters`Ah`Substitute
Single quotes instead of double quotes for char type*/
double d = 10.0
 // ->10 for "floating point type" that can handle decimal points.Substitute 0
String s = "It is a character string."
 /* ->String type that can handle character strings"It is a character string."Substitute
Double quotes instead of single quotes for String*/

However, I was always wondering. That is ** "Why does only the String type start with a capital letter?" **

There are basic data types and reference types

** "Why does only the String type start with a capital letter?" ** The answer was that the String type is ** not a basic data type **. In other words, the ** String type was a class **. Sure, the first letter of the class is capitalized, I see! I am convinced.

Take a peek inside the String class

String is a class. If so, you can see the contents. So, looking at the contents of the String class, one of the instance fields has this definition.

String.java


private final char value[];

This is an array of basic data type char type! So, it seems that the identity of String was a set of arrays of basic data type char type. In other words, the String s =" string. " Defined in the variable definition .java earlier.

private final char value[] = {'Sentence','Character','Column','so','Su','。'}

It was that.

It seems that there are not only String types but also StringBuilder types.

If you proceed with learning like this, there is also a StringBuilder other than String.

What's the difference?

This is what I understand at this point.

String type StringBuilder type
Variable declaration Can be without new You can't declare it without using new
Reassign to variable The reference destination changes Rewrite the contents

~~ It wasn't enough to make it a table ... ~~

As with how to handle data, the classes are different in the first place, and the methods provided are also different.

Variable declaration

The method of variable definition is decided between String and StringBuilder.

Variable definition.java


String a = "AIUEO"; // ->it can
String b = new String("Kakikukeko");  // ->it can
StringBuilder c = "SA Shi Su Se So"; // ->Can not
StringBuilder d = "TA Chi Tsu Te to"; // ->it can

What is the difference depending on how to declare the String type?

It seems that the way of managing strings is different. If new is not used, a character string will be prepared for the area managed by the String class. If you use new, a string will be created separately from the area managed by the String class.

So, even if it is the same String type, if you define it with new, it seems that a lone wolf String variable is created. You can probably imagine how it will be different by using the method intern () that the String class has. (See below)

About reassignment to variables

"Can't you reassign to a variable? No. You can!" Those who think so. is not it. I feel like it's definitely done

Variable reassignment.java


String a = "AIUEO";
a = "Kakikukeko";
// ->The contents of a"Kakikukeko"become

However, this is not rewritten, but it seems that the reference destination of a is ** switched from "aiueo" to "kakikukeko" **.

So, strictly speaking, it is not rewritten, but switched. it seems like.

About String type comparison

I think that it may be necessary to compare String type strings for implementation. In such a case, it is mainstream to use the comparison operator, but in the case of String type, use the ʻequals () `method instead of the comparison operator.

Is it Naze?

From the conclusion, it seems that the comparison operator ** compares the reference source **. To put it more simply, s1 and s2 are the same "aiueo", but when s1 == s2, it becomes false in some cases.

String comparison with comparison operator.java


package sample20200728;

public class Sample02 {
    public static void main(String[] args){
        String s1 = new String("Ah");
        String s2 = "Ah";
        String s3 = "Ah";

        //Compare s1 and s2 with comparison operator
        if(s1 == s2){
            System.out.println("The strings for s1 and s2 are the same");
        }else{
            System.out.println("The strings for s1 and s2 are different");
        }

        //Compare s1 and s3 with comparison operator
        if(s1 == s3){
            System.out.println("The strings for s1 and s3 are the same");
        }else{
            System.out.println("The strings of s1 and s3 are different");
        }

        //Compare s2 and s3 with comparison operator
        if(s2 == s3){
            System.out.println("The strings for s2 and s3 are the same");
        }else{
            System.out.println("The strings for s2 and s3 are different");
        }
    }
}

** Output result ** スクリーンショット 2020-07-28 23.21.44.png The strings are the same, but some are different. Has been denied. It seems that the comparison operator compares the referrer without comparing the strings.

I think this is fine when deciding whether the reference sources are the same, but considering the actual operation, whether the character strings match. Do you often check? I think. In that case, if false is returned because the reference source is different even though the character string is the same, it will cause a bug, right?

I don't care about the details. All you have to do is match the strings! The male method equals () is active.

equals()Comparison in.java


public class Sample02 {
    public static void main(String[] args){
        String s1 = new String("Ah");
        String s2 = "Ah";
        String s3 = "Ah";

        //Compare s1 and s2 with equals method
        if(s1.equals(s2)){
            System.out.println("The strings for s1 and s2 are the same");
        }else{
            System.out.println("The strings for s1 and s2 are different");            
        }

        //Compare s1 and s3 with equals method
        if(s1.equals(s3)){
            System.out.println("The strings for s1 and s3 are the same");
        }else{
            System.out.println("The strings of s1 and s3 are different");            
        }

        //Compare s2 and s3 with equals method
        if(s2.equals(s3)){
            System.out.println("The strings for s2 and s3 are the same");
        }else{
            System.out.println("The strings for s2 and s3 are different");            
        }
    }
}

Execution result スクリーンショット 2020-07-28 23.24.06.png

Yup. They compare the strings well!

Bonus intern method

The String class has an intern method. The method description says "returns a unique string in the string pool". Ok in Japanese.

But I thought that it would appear in the java test.

I wrote the source code to understand the intern method

"Returning the first string in the string pool" didn't come to my mind at all, so I actually wrote the source and checked the behavior.

What I could understand is like this

  1. The intern () method checks whether the target character string exists in the area of the String type. If there is the same string-> Refer to it. ** Image that can be reused ** If there is no same character string-> Prepare the character string in the area of the String type.
  2. If you define a value using new when defining a variable of String type, it will be out of the jurisdiction of the area of String type. -> Intenr () cannot be used to make the reference source the same

intern().java


public class Sample01 {
    public static void main(String[] args){

        String s1 = new String("test"); //Area of String type class"Outside"With s1 variable"test"Create
        String s2 = s1.intern();  /* s1.intern()Of the return value of"test"Is assigned to s2.
However, since s1 is created with new, it is a character string created outside the area of the String type class, so it is inside the String type class."test"Does not exist.
In this case, intern()In the area of the String type class at the timing using"test"Prepare the character string*/
        String s3 = "Mumumu"; //Area of String type class"Inside"With s3 variable"Mumumu"Create
        String s4 = s3.intern(); /*s3.intern()Of the return value of"Mumumu"Is assigned to s3.
Unlike s1, s3 is in the area of String typeclass"Mumumu"I have already made it"Mumumu"(That is, not only the string but also the place to refer to)*/
        
        System.out.println("s1 is a variable using new" + s1);
        System.out.println("s2 is s1.intern()Variable to which the return value of" + s2);
        System.out.println("s3 is\"Mumumu\"Variable to which" + s3);
        System.out.println("s4 is s3.intenr()Variable to which the return value of" + s4);   

        //Made with new"test"And s1.intern()Made with"test"Compare
        if(s1 == s2){
            System.out.println("true:The references for s1 and s2 are the same");
        }else{
            //Since the reference destination of s1 and s2 is different, it becomes false
            System.out.println("false:References for s1 and s2 are different");
        }

        //S3 prepared using the area managed by String type"Mumumu"And s3.intern()Picked up at"Mumumu"Compare s4 with
        if(s3 == s4){
            //s3,Both s4 are generated from the String type area, for s4 s3.intern()Is assigned by referring to the character string of s3 in
            System.out.println("true:The references for s3 and s4 are the same");
        }else{
            System.out.println("false:References for s3 and s4 are different");
        }

        /*s2 is"test"Is created in the area of the String type class
Therefore, s5= s2.intern()Then, s5 will refer to the same thing as s2.*/
        String s5 = s2.intern();

        //Check if the referrers of s2 and s5 are the same
        if(s2 == s5){
            //s2.intern()Since it is assigned to s5 using, the reference source is the same.
            System.out.println("true:The references for s2 and s5 are the same");
        }else{
            System.out.println("false:References for s2 and s5 are different");
        }
        System.out.println("============");
    }
}

Execution result スクリーンショット 2020-07-28 22.55.05.png

No matter how you struggle, s1 defined in new will be out of the group.

end

The above is the content facing the String type. There are many things that I haven't understood yet, so I'm sure there are some misinterpretations. In that case, we apologize for the inconvenience, but we would appreciate it if you could point out.

Then thank you m (_ _) m

Recommended Posts

[Java] I felt as a java beginner. "Why is the first letter of the String type capitalized?" I faced the String type.
[Delete the first letter of the character string] Ruby
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
I tried to convert a string to a LocalDate type in Java
[Java beginner] Conversion from character string to numerical value-What is the parseInt method of the Integer class? ~
I tried the input / output type of Java Lambda ~ Map edition ~
I tried to summarize the methods of Java String and StringBuilder
How to check for the contents of a java fixed-length string
Why I think the NullObject pattern is inappropriate and Either is appropriate as a way to express failure
[Java] Correct comparison of String type
I read the source of String
[Java Servlet] The road of Senri is also the fifth step from the first step
[Java Servlet] The road of Senri is also one step to the first
[Java Servlet] The road of Senri is also the third step from the first step
[Java] How to get to the front of a specific string using the String class
[Java Servlet] The road of Senri is also the fourth step from the first step
[Java] Check if the character string is composed only of blanks (= Blank)
[day: 5] I summarized the basics of Java
[Java] Comparison of String type character strings
[Java] How to convert one element of a String type array to an Int type
[Java] Difference between equals and == in a character string that is a reference type
Whether the total product of the first n prime numbers plus 1 is a prime number
[Java] When putting a character string in the case of a switch statement, it is necessary to make it a constant expression
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...