Initialization with an empty string to an instance of Java String type

What is the String type after all?

I just thought I was taking a bath. In the Java language, literals are the values of primitive types, String types, and null types that are directly represented in the code. Primitive types have different characteristics from reference types, "that's why it can't be helped" (although you shouldn't say that), and null types are also "null", so you can directly describe and handle that data. I can agree with that. Then why is there a literal only for String in the reference type? Why? Why is it sensuously? I thought. Alright, let's find out.

My environment

For the time being, look at the String type

This is the beginning of all the mistakes, but since it is a string "literal" (meaning "literally") in the first place, it is the String itself. But "empty". Not null, but "empty". "Sky" is a fairly important concept, isn't it? I don't think it's written that you can understand why string literals were prepared even if you go to see the String class. But without any thought, I vaguely pressed the F3 key and went to see the String class. Hello. One hour of my mystery. The first thing that jumps in

String.class


private final char value[];

Field. It is an array of immutable char values that stores String type string data. Since the sequence and flow are important, it is called a sequence. I learned at first that new data will be generated when new. That's why you can use StringBuilder for modifiable strings.

Looking at the beginning of the huge number of constructors, it seemed like "Yeah," and I was surprised even now.

String.class


public String() {
    this.value = "".value;
}

 
public String(String original) {
    this.value = original.value;
    this.hash = original.hash;
}

//Omitted below

What happens with this.value =" ". value;? is. I see that it is initialized with String str =" "; because it is an empty string, and I learned it a long time ago, but when I think about it, I think that char c =''; is impossible. .. Isn't it possible to create an instance but not assign an initial value? ?? ??

Sample.java


String str = "";
System.out.println(str.length()); // 0
System.out.println(str.charAt(0)); // Exception!

If you think about it, the initial value is not included. I can generate it, but there is no value in it. I had a dream that it contained data called an empty string. That wasn't the case. No, there is a character that is not the character "empty", but it is not a character even though the memory area is secured. Since the data as characters is "empty", the memory area is secured even if the length of the character string is 0. There is, but there is no such thing as the concept of "empty". It's profound. String.charAt () just stopped whispering StringIndexOutOfBoundsException. Alright, re-challenge.

Sample.java


String str = "I love you.";
System.out.println(str.length()); // 11
str = "I love you." + "";
System.out.println(str.length()); // 11

Yeah, the string length doesn't change. Of course. Because it is "empty". I suddenly returned to myself here. For example, Point p = new Point (); may be set with an initial value of 0 for both x and y because it is not a sequence.

sequence

The String class implements CharSequence, as does StringBuilder and StringBuffer. So, if they create an instance without giving anything to the argument, only the area to put the data is secured, and that is the characteristic of the array itself. It's a little different from String, but I didn't realize why I couldn't just generate it. I am writing this in agony. Collection is also different from an array, but first an instance of the framework itself such as List is created, and data is entered later. Even if it was an empty string, I wasn't relaxed that the string would be a string (some significant data). Why did you forget it? The foundation of the foundation is important, isn't it? I was keenly aware. At the same time, I felt the greatest disappointment for myself in this century.

Significance of initialization of a String type instance with an empty string

I think that initialization is to assign a value together with a declaration. Even if the data of a clear character string cannot be assigned, the information of an instance of String is generated and completed, so I think that initialization is initialization, but thanks to the wonderful concept of "empty", it is somehow. I feel that it contains some initialization complexity that other instances do not have. Well, since an empty string is a literal of a character string, it may be meaningful to have information that it is a character string type (String type), but I was convinced in the past. One of the meanings (I knew) of the empty string assignment of "reducing the possibility of exceptions caused by null" is not right now. Is it because Optional is now available? However, the usage is strange, such as Optional for instance initialization using string literals. I think Optional can be used nicely when the return value of a method is expected to be null. I don't feel thankful for such a place. On the contrary, it's just annoying. When using Eclipse, if you try to use a variable without initialization, you will get angry like a demon, and it seems useless to initialize with null or an empty string. I'm substituting an empty string with the feeling that it's unpleasant to just declare and not enter a value anymore. Null can be initialized, but it's null (nothing, no reference), so it feels like a crap. This is bad.

Always in the same way (2017-1-24 postscript)

@hiuchida commented that the fun of not having to separate null from non-null is wonderful. I will post the example as it is.

String empty = "";
for (char ch : empty.toCharArray()) {

Sure, it's tiring to always be aware of null or non-null. As you said, the point of view that you can enjoy yourself is also wonderful.

It was gudaguda, but I will leave it as it is as a commandment not to be caught again by the same "why?" Then, we set out on a journey to find a sound way to use the empty string.

Conclusion

What I swore to my heart

Recommended Posts

Initialization with an empty string to an instance of Java String type
About an instance of java
[Java] How to convert one element of a String type array to an Int type
[Java] Correct comparison of String type
[Java] Convert Object type null to String type
[Java] Comparison of String type character strings
Type conversion from java BigDecimal type to String type
Initialization of for Try to make Java problem TypeScript 5-4
GetXxxx of ResultSet was addicted to primitive type (Java)
[Java] One type of alphabet prohibited FizzBuzz with binding [Binding]
An unsupported Java version How to get rid of errors
How to use trained model of tensorflow2.0 with Kotlin / Java
Java to play with Function
[Java] One type of alphabet prohibited With binding Hello, world! [Binding]
Deploy a Java application developed locally with the Cloud Toolkit to an Alibaba Cloud ECS instance
Convert String type to Timestamp type
[Java] How to convert a character string from String type to byte type
[Java] To know the type information of type parameters at runtime
Connect to DB with Java
Connect to MySQL 8 with Java
What happens to instance variables when copying an instance with ruby
I tried to convert a string to a LocalDate type in Java
To receive an empty request with Spring Web MVC @RequestBody
How to handle an instance
How to develop an app with Jersey Java RESTful API on Alibaba Cloud ECS instance
Be sure to compare the result of Java compareTo with 0
[Introduction to Java] Handling of character strings (String class, StringBuilder class)
[Introduction to Java] Variables and types (variable declaration, initialization, data type)
A story of connecting to a CentOS 8 server with an old Ansible
The story of toString () starting with passing an array to System.out.println
Cast an array of Strings to a List of Integers in Java
I tried to make an Android application with MVC now (Java)
I tried to summarize the methods of Java String and StringBuilder
[Java] How to convert from String to Path type and get the path
How to check for the contents of a java fixed-length string
How to get the length of an audio file in java
[Java] Speed comparison of string concatenation
Create an immutable class with JAVA
Java to learn with ramen [Part 1]
Dare to challenge Kaggle with Java (1)
I tried to interact with Java
Java, arrays to start with beginners
Run an application made with Java8 with Java6
How to use Java enum type
[Introduction to Java Table of Contents] I compared Java with other languages (interpreter type, compiler type, dynamic typing, static typing)
[Java] Output the result of ffprobe -show_streams in JSON and map it to an object with Jackson
[Java] How to turn a two-dimensional array with an extended for statement
Use static initialization block to initialize List / Set of static fields in Java
How to convert an array of Strings to an array of objects with the Stream API
Get the type of an array element to determine if it is an array
[Java] How to use substring to cut out a part of a character string
[Java] [ibatis] How to get records of 1-to-N relationship with List <Map <>>
[Java] How to get to the front of a specific string using the String class
Memo: [Java] Identify files with an update date of 1 day or less
I want to ForEach an array with a Lambda expression in Java
Practice of Java programming basics-I want to display triangles with for statements ②
How to make an app with a plugin mechanism [C # and Java]
<Java> Quiz to batch convert file names separated by a specific character string with a part of the file name
How to crop an image with libGDX
[Java] Implicit type cast (AOJ10-sum of numbers)
Let's create an instance with .new yourself. .. ..