From the course: Java 11+ Essential Training

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Build a string from multiple values

Build a string from multiple values - Java Tutorial

From the course: Java 11+ Essential Training

Start my 1-month free trial

Build a string from multiple values

- [Man] As I described previously, a string object in java is immutable, its value can't be changed. So, when you append or replace a string's value, you're really discarding the existing object, and creating a new one in memory. To create a complex string from scratch, without leaving a trail of temporary string objects in your wake, you can use the string builder class. First, a bit about builders. A builder is a software pattern that can be used to create or build an object. First, you create the builder itself, and then you call a series of methods to create the target object. In JShell, I'll create an instance of the string builder class, using type inference. I'll name the variable sb, and I'll initialize it with new StringBuilder, and I'll pass in an initial string of Welcome. Now, I'll append the value with sb.append and I'll pass in space, and to California. The output shows me the current context of the…

Contents