Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте StringBuilder | Section
Practice
Projects
Quizzes & Challenges
Вікторини
Challenges
/
Java Fundamentals

bookStringBuilder

What is StringBuilder?

StringBuilder is a utility class for manipulating and editing string objects.

StringBuilder provides its own methods, and creating a StringBuilder object is straightforward and intuitive.

Main.java

Main.java

copy
1
StringBuilder builder = new StringBuilder();

Inside the parentheses, we can also pass a string value, and our StringBuilder variable will hold that value:

Main.java

Main.java

copy
1
StringBuilder builder = new StringBuilder("c<>definity");

To print our value to the console, we need to use one of the StringBuilder methods. It's the toString() method, which converts the value of the StringBuilder to a String type value. Let's look at an example:

Main.java

Main.java

copy
123456789
package com.example; public class Main { public static void main(String[] args) { StringBuilder builder = new StringBuilder("c<>definity"); String string = builder.toString(); System.out.println(string); } }

StringBuilder in Action

StringBuilder provides a rich set of methods, with one of the most valuable and frequently used being append(String str). This method allows us to add a specified string to the existing content of a StringBuilder object.

Let's examine a code example:

Main.java

Main.java

copy
12345678910111213141516
package com.example; public class Main { public static void main(String[] args) { // Initializing the new `String` with value "Hello" String hello = "Hello"; System.out.println("Our string before using an append() method: " + hello); // Initializing a new `StringBuilder` with value of our already initialized string StringBuilder builder = new StringBuilder(hello); // Using `append()` method, adding a string world to our `StringBuilder` builder = builder.append(" world!"); // Creating a new `String` variable that has a `StringBuilder` value String result = builder.toString(); System.out.println("Our string after using an append() method: " + result); } }

Why not Use the + Operator?

We prefer StringBuilder's append method because it avoids creating multiple temporary objects, improving performance when modifying content repeatedly. Using the + operator creates a new object each time, which is costly in memory and time. StringBuilder modifies content directly, making it more efficient for repeated changes.

Завдання

Swipe to start coding

You're building a product display for a webpage. Each product has a name and a price, and they are stored in a 2D array.
You need to format the entire list into a nicely structured string using a StringBuilder.

  1. Create a method called buildProductList(String[][] products) that returns a formatted String.
  2. Initialize a StringBuilder and append the header:
    "Product List:\n"
  3. Loop through the products array using a for-each loop.
  4. For each product:
    • Extract the name (product[0])
    • Extract the price (product[1])
    • Append a line to the StringBuilder in the format:
      ProductName - $Price\n
  5. Return the full String from the StringBuilder.

Рішення

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 34
single

single

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

close

bookStringBuilder

Свайпніть щоб показати меню

What is StringBuilder?

StringBuilder is a utility class for manipulating and editing string objects.

StringBuilder provides its own methods, and creating a StringBuilder object is straightforward and intuitive.

Main.java

Main.java

copy
1
StringBuilder builder = new StringBuilder();

Inside the parentheses, we can also pass a string value, and our StringBuilder variable will hold that value:

Main.java

Main.java

copy
1
StringBuilder builder = new StringBuilder("c<>definity");

To print our value to the console, we need to use one of the StringBuilder methods. It's the toString() method, which converts the value of the StringBuilder to a String type value. Let's look at an example:

Main.java

Main.java

copy
123456789
package com.example; public class Main { public static void main(String[] args) { StringBuilder builder = new StringBuilder("c<>definity"); String string = builder.toString(); System.out.println(string); } }

StringBuilder in Action

StringBuilder provides a rich set of methods, with one of the most valuable and frequently used being append(String str). This method allows us to add a specified string to the existing content of a StringBuilder object.

Let's examine a code example:

Main.java

Main.java

copy
12345678910111213141516
package com.example; public class Main { public static void main(String[] args) { // Initializing the new `String` with value "Hello" String hello = "Hello"; System.out.println("Our string before using an append() method: " + hello); // Initializing a new `StringBuilder` with value of our already initialized string StringBuilder builder = new StringBuilder(hello); // Using `append()` method, adding a string world to our `StringBuilder` builder = builder.append(" world!"); // Creating a new `String` variable that has a `StringBuilder` value String result = builder.toString(); System.out.println("Our string after using an append() method: " + result); } }

Why not Use the + Operator?

We prefer StringBuilder's append method because it avoids creating multiple temporary objects, improving performance when modifying content repeatedly. Using the + operator creates a new object each time, which is costly in memory and time. StringBuilder modifies content directly, making it more efficient for repeated changes.

Завдання

Swipe to start coding

You're building a product display for a webpage. Each product has a name and a price, and they are stored in a 2D array.
You need to format the entire list into a nicely structured string using a StringBuilder.

  1. Create a method called buildProductList(String[][] products) that returns a formatted String.
  2. Initialize a StringBuilder and append the header:
    "Product List:\n"
  3. Loop through the products array using a for-each loop.
  4. For each product:
    • Extract the name (product[0])
    • Extract the price (product[1])
    • Append a line to the StringBuilder in the format:
      ProductName - $Price\n
  5. Return the full String from the StringBuilder.

Рішення

Switch to desktopПерейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 34
single

single

some-alt