I tried to summarize the methods of Java String and StringBuilder

0. Introduction

This is an article that I, who is studying for Java8 Silver acquisition, summarized the methods of String and StringBuilder. Here, we introduce the methods of String and StringBuilder that you should keep in mind when taking the Java Silver exam. As you might expect, I am an inexperienced person, so if you make a mistake, I would appreciate it if you could point it out.

From the next chapter, we will explain the methods of String and the methods of StringBuilder in that order.

1. About String

I'll just give you a rough idea of the String itself. The point to hold down is

-It is a reference type, not a primitive type -Immutable (once defined, it does not rewrite in memory)

Is it a place? String handles strings with char []. Therefore, in the following method, the referenced object will be the same even if the reference value is different (the code is quoted from [Reference 2] ref1).

String a = "Apple";
String b = new String("Apple");
String c = new String(new char[]{'Ri', 'Hmm', 'Go'});
System.out.println(a); //Apple
System.out.println(b); //Apple
System.out.println(c); //Apple

Also, I said Immutable, but that doesn't mean it can't be reassigned. Reassignment switches the reference destination of the variable (for details, see the articles in [Reference 3] and ref2).

2. Main methods of String

Then, the main subject, the following are the methods that "I'm going to test here!" (The list of methods is quoted from Reference 1). (Since the introduction of the method continues lazily, please actually move your hand and write the code)

char charAt(int i) Returns the character at the position specified by ʻi`. The original string does not change. (How to read the code: The character written after // represents the output character string)

String str = "Hello Java!";

System.out.println(str.charAt(4));  // J
System.out.println(str);  // Hello Java!

String concat(String str) The character string specified by str is concatenated at the end. After all, the original character string does not change.

String str = "Hello ";

System.out.println(str.concat("Java!"));  // Hello Java!
System.out.println(str);  // Hello 

boolean equalsIgnoreCase(String str) Compares the target string with str, case insensitive.

String str = "Hello Java!";

System.out.println(str.equalsIgnoreCase("HELLO JAVA!"));  // true

//When compared by equals
System.out.println(str.equals("HELLO JAVA!")); // false

int indexOf(int ch), int lastIndexOf(int ch) Let's remember these two as a set! Both return the position where the character specified by ch first appears.

ʻIndexOf looks for the string from the left and lastIndexOf` looks for it from the right. Then, the leftmost character is set as the 0th character, and it tells you what number the corresponding character is (the space is also counted as one character).

String str = "Hello Java!";
// H  e  l  l  o     J  a  v  a   !
// 0  1  2  3  4  5  6  7  8  9  10

System.out.println(str.indexOf("l"));  // 2
System.out.println(str.lastIndexOf("l"));  // 3

int length() Returns the number of characters in the string. Again, spaces are counted as one character.

String str = "Hello Java!";

System.out.println(str.length());  // 11

String replace(char o, char n) Returns a string in which the characters ʻo in the string are all replaced with the characters n`.

String str = "Hello Java!";

System.out.println(str.replace('a', 'o'));  // Hello Jovo!

boolean startsWith(String prefix), boolean endsWith(String suffix) It looks good to remember this as a set too!

startsWith returns true if the string starts with prefix. ʻEndsWithreturns true if the string ends withsuffix`.

String str = "Hello Java!";

System.out.println(str.startsWith("Hello"));  // true
System.out.println(str.startsWith("Hey!"));   // false

System.out.println(str.endsWith("Java!"));   // true
System.out.println(str.endsWith("python!")); // false

String substring(int start, int end) Returns the string from start to just before the ʻend`, and the string in between. It's hard to understand this "in between", so it may be easier to understand by looking at the code.

The point is to count between the letters, not the letters themselves (in the example below, the original strings are separated and numbered with a pipe (|)).

String str = "Hello Java!";

// | H | e | l | l | o |   | J | a | v | a  | ! |
// 0   1   2   3   4   5   6   7   8   9   10   11

//When both the first argument and the second argument are specified
System.out.println(str.substring(2, 7));  // llo J

//When only the first argument is specified
//The following two output the same string
System.out.println(str.substring(2));  // llo Java!
System.out.println(str.substring(2, str.length()));  // llo Java!

String toLowerCase(), String toUpperCase() toLowerCase () converts uppercase letters to lowercase letters. Characters that were originally lowercase do not change.

toUpperCase () converts lowercase letters to uppercase. That's all.

String str = "Hello Java!";

System.out.println(str.toLowerCase());  // hello java!
System.out.println(str.toUpperCase());  // HELLO JAVA!

String trim() Removes half-width spaces at both ends. It's a little confusing, but it's obvious if you count the number of characters!

String str = " Hello Java! ";

System.out.println(str.trim());           // Hello Java!
System.out.println(str.trim().length());  // 11

System.out.println(str);           //  Hello Java! 
System.out.println(str.length());  // 13

3. About StringBuilder

While Stirng is Immutable, StringBuilder replaces the referenced value when reassigning. The bottom line is that the String method doesn't change the original string, while the StringBuilder method changes the original string.


There are the following ways to declare StringBuilder [^ 20].

// 1.Declared casually, initial capacity is 16 characters
StringBuilder sb1 = new StringBuilder();

// 2.Initial capacity Declared in characters
// 80.If you enter a real number such as 0, a compile error will occur. Only ints can be specified.
StringBuilder sb2 = new StringBuilder(int capacity);

// 3.Initialize with str
StringBuilder sb3 = new StringBuilder(String str);

// 4.Declare and output immediately
System.out.println(new StringBuilder("Hello Java!"));

4. Main methods of StringBuilder

StringBuilder append(String str) Add str after the string. Unlike String, the original string will change.

StringBuilder sb = new StringBuilder("Hello Java!");

System.out.println(sb.append(" World!!"));  // Hello Java! World!!
System.out.println(sb);  // Hello Java! World!!

StringBuilder insert(int offset, String str) This method is also for adding characters, but you can specify the position to add. For clarity, pipes (|) separate the original strings and number them.

StringBuilder sb = new StringBuilder("Hello Java!");
// | H | e | l | l | o |   | J | a | v | a  | ! |
// 0   1   2   3   4   5   6   7   8   9   10   11

System.out.println(sb.insert(10, "Script"));  // Hello JavaScript!
System.out.println(sb);  // Hello JavaScript!

StringBuilder delete(int start, int end) Deletes the characters from the startth to just before the ʻend`th.

StringBuilder sb = new StringBuilder("Hello Java");

System.out.println(sb.delete(2, 4));  // Heo Java!
System.out.println(sb);  // Heo Java!

// length()Can be used in combination with to delete all characters
System.out.println(sb.delete(0, sb.length()));  // (No output)

StringBuilder reverse() Reverse the order of the strings.

StringBuilder sb = new StringBuilder("Hello Java!");

System.out.println(sb.reverse());  // !avaJ olleH
System.out.println(sb);  // !avaJ olleH

void setCharAt(int index, char ch) ʻIndex Replace the** character ** in theth position with ch.

StringBuilder sb = new StringBuilder("Hello Java!");

sb.setCharAt(6, 'j');
System.out.println(sb);  // Hello java!

StringBuilder replace(int start, int end, String str) Replace the characters from the startth to just before the ʻendth with str. It is okay if the number of characters to replace and the number of characters in str` do not match. Unlike setCharAt, it replaces ** string ** and returns a StringBuilder.

StringBuilder sb = new StringBuilder("Hello Java!");

System.out.println(sb.replace(6, 10, "python"));  // Hello python!
System.out.println(sb);  // Hello python!

String substring() It can be used in exactly the same way as [String substring ()](# string-substring int-start-int-end).

String toString() As you can see [^ 40], it converts StringBuilder to String. It is used when comparing with String.

StringBuilder sb = new StringBuilder("Hello Java!");
String str = "Hello Java!";

//Compare if str and sb values are the same
System.out.println( str.equals(sb.toString()) );  // true

CharSequence subSequence(int start, int end) In fact, it behaves exactly like [String substring ()](# string-substring int-start-int-end). If there is a difference, is the return value an object called CharSeqence? Then the original object is immutable.

StringBuilder sb = new StringBuilder("Hello Java!");

  System.out.println(sb.subSequence(2, 8));  // oll Ja

  if (sb.subSequence(2, 8) instanceof CharSequence ) {
    System.out.println("this is CharSequence Object");  //Will be executed

5. Finally

In Java Silver, there are many questions about String / StringBuilder methods. It seems to be a so-called basic thing, but it is difficult (was) to investigate and summarize. I hope this article will help you understand String / StringBuilder and pass the exam.

6. Reference

    1. Michiko Yamamoto (2015) Java Programmer Silver SE 7 (5th print issued) Published by Shoeisha Co., Ltd.
  1. [Java reference understood in the figure] ref1
    1. [[Java beginner] Passing by value and passing by reference (The word "pass by reference" has been corrected because it is misleading)] ref2

[^ 20]: Personally, I was surprised to think that method 4 would result in an error. [^ 40]: I wondered where you can see it later, but I decided not to fix it.

Recommended Posts

I tried to summarize the methods of Java String and StringBuilder
I tried to summarize the basics of kotlin and java
I tried to summarize the methods used
[Java] The confusing part of String and StringBuilder
I tried to summarize the key points of gRPC design and development
I tried to summarize the state transition of docker
I tried to summarize Java learning (1)
I tried to summarize Java 8 now
I tried to summarize the basic grammar of Ruby briefly
I tried to summarize Java lambda expressions
I tried to summarize the Stream API
[For Swift beginners] I tried to summarize the messy layout cycle of ViewController and View
I compared the characteristics of Java and .NET
[Ruby] I tried to summarize the methods that frequently appear in paiza
[Ruby] I tried to summarize the methods that frequently appear in paiza ②
I translated the grammar of R and Java [Updated from time to time]
I tried to measure and compare the speed of GraalVM with JMH
[Rails] I tried to summarize the passion and functions of the beginners who created the share house search site!
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
[Java] About String and StringBuilder
I summarized the types and basics of Java exceptions
I tried to implement the Euclidean algorithm in Java
[Java] Handling of character strings (String class and StringBuilder class)
I didn't understand the behavior of Java Scanner and .nextLine ().
Command to check the number and status of Java threads
I tried to verify this and that of Spring @ Transactional
[Swift] I tried to implement the function of the vending machine
I tried JAX-RS and made a note of the procedure
I tried to make Java Optional and guard clause coexist
I tried to summarize personally useful apps and development tools (development tools)
I tried to convert a string to a LocalDate type in Java
I tried to build the environment of WSL2 + Docker + VSCode
I tried to summarize personally useful apps and development tools (Apps)
I tried to make a client of RESAS-API in Java
[Introduction to Java] Handling of character strings (String class, StringBuilder class)
[Java] I thought about the merits and uses of "interface"
Various methods of Java String class
I tried to summarize iOS 14 support
I tried to interact with Java
I tried to explain the method
I tried the Java framework "Quarkus"
Various methods of the String class
I read the source of String
I tried using GoogleHttpClient of Java
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
I finished watching The Rose of Versailles, so I tried to reproduce the ending song in Java
I tried to solve the problem of "multi-stage selection" with Ruby
[Java] Various summaries attached to the heads of classes and members
I tried to summarize the words that I often see in docker-compose.yml
I tried to summarize what was asked at the site-java edition-
I want to return to the previous screen with kotlin and java!
[Ruby] Tonight, I tried to summarize the loop processing [times, break ...]
Special Lecture on Multi-Scale Simulation: I tried to summarize the 5th
I tried the input / output type of Java Lambda ~ Map edition ~
Special Lecture on Multi-Scale Simulation: I tried to summarize the 8th
I tried to check the operation of gRPC server with grpcurl
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
[Java] I tried to make a maze by the digging method ♪
I tried to move the Java compatible FaaS form "Fn Project"
I tried to display the calendar on the Eclipse console using Java.