
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Methods
- Scala - Functions
- Scala - Methods vs Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala - Polymorphic Functions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - NumericRange
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala Advanced Types
- Scala - Union Types
- Scala - Intersection Types
- Scala - Type Aliases
- Scala - Structural Types
- Scala - Match Expression
- Scala - Singleton Type Operator
- Scala - Abstract Types
- Scala - Dependent Types
- Scala - Abstract Type Bounds
- Scala - Higher-Kinded Types
- Scala - Opaque Type Alias
- Scala - Path-Dependent Types
- Scala - Type Lambdas
- Scala - Type Inference
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Guards
- Scala - Variables in Patterns
- Scala - Type Patterns
- Scala - The Matchable Trait
- Scala - Matching Arrays
- Scala - Matching Lists
- Scala - Matching Tuples
- Scala - Exception Handling
- Scala - Extractors
- Scala - Pattern Bindings
- Scala - Regular Expressions
- Scala - Case Classes
- Scala - Partial Functions
- Scala - Packaging and Imports
- Scala - Implicit Imports
- Scala - Export Clauses
- Scala - Nested Packages
- Scala - Chained Packages
- Scala - Package Objects
- Scala Files I/O
- Scala - Files I/O
- Scala - Writing Files
- Scala - Listing Files
- Scala - Deleting Directories
- Scala - Check File Exists
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Process Management
- Scala - Scaladoc
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala Unit Testing
- Scala - Unit Testing
- Scala - uTest
- Scala - MUnit
- Scala - ScalaTest Runner
- Scala - ScalaMock
- Scala - JUnit
- Scala - Mocking
- Scala - BDD Testing
Scala - StringBuilder
StringBuilder is a mutable data structure. It is used for building strings by appending characters or substrings. StringBuilder is more appropriate when working with string manipulation operations. We will discuss StringBuilder in this article.
Introduction to StringBuilder
StringBuilder is a class in the Scala standard library that builds mutable sequences of characters. It provides an efficient way to construct strings by appending characters, substrings, other data types, etc. StringBuilder has an API that is compatible with java.lang.StringBuilder.
StringBuilder is a mutable type. It has methods to delete parts of a string, insert, replace characters, etc. It is used when you want to modify a string without creating a new object. So, it can boost performance when concatenating many strings together in a loop.
StringBuilder Basic Operations
StringBuilder has various methods for appending, inserting, and modifying strings.
1. Appending
You can use the append method to add characters, strings, and other data types to the StringBuilder. For example,
val builder = new StringBuilder builder.append("Hello, ") builder.append("Scala!") println(builder.toString)
The output will be,
Hello, Scala!
2. Inserting
You can use the insert method to insert characters and strings at a specific position within the StringBuilder. For example,
val builder = new StringBuilder("Scala") builder.insert(0, "Hello, ") println(builder.toString)
The output will be,
Hello, Scala!
3. Updating
You can update characters at specific positions using the update method. For example,
val builder = new StringBuilder("Hello, Scala!") builder.update(7, 'W') println(builder.toString)
The output will be,
Hello, Wcala!
4. Deleting
You can use methods like delete, deleteCharAt, and clear for removing characters and resetting the StringBuilder. For example,
val builder = new StringBuilder("Hello, Scala!") builder.delete(7, 8) println(builder.toString)
5. Replacing
You can replace sequences of characters with new sequences using the replace method. For example:
val builder = new StringBuilder("Hello, Scala!") builder.replace(7, 12, "World") println(builder.toString)
The output will be,
Hello, World!
6. Reversing
You can reverse the entire sequence of characters using the reverse method. For example:
val builder = new StringBuilder("Hello, Scala!") val reversed = builder.reverse.toString println(reversed)
The output will be,
!alacS ,olleH
7. Converting to String
You can convert the entire sequence of characters in a StringBuilder to a String using the toString method. You can use this method when you need immutable String from the mutable StringBuilder. For example:
val builder = new StringBuilder("Hello, Scala!") val str = builder.toString println(str)
The output will be,
Hello, Scala!
Scala StringBuilder Instance Constructors
Following are the important instance constructors for StringBuilder in Scala. These constructors allow for various ways to initialize a StringBuilder with different initial values and capacities.
Sr.No | Constructor | Description |
---|---|---|
1 | new StringBuilder(initCapacity: Int, initValue: String) | Creates a StringBuilder initialized with the string value initValue and additional character capacity initCapacity. |
2 | new StringBuilder(str: String) | Creates a StringBuilder initialized with the characters from the string str. |
3 | new StringBuilder(capacity: Int) | Creates an empty StringBuilder with an initial capacity specified by the capacity argument. |
4 | new StringBuilder() | Creates an empty StringBuilder with the default initial capacity. |
5 | new StringBuilder(underlying: java.lang.StringBuilder) | Creates a StringBuilder that wraps around an existing java.lang.StringBuilder. |
Advantages of StringBuilder
StringBuilder has various advantages when compared to string concatenation using the + operator and string interpolation (s"..."). These are −
- Efficiency − StringBuilder is more efficient for string manipulation operations. Because it avoids the overhead of creating new string objects.
- Mutable − StringBuilder is mutable. So, you can modify them in-place.
- Flexible − StringBuilder has various operations for appending, inserting, updating, and deleting characters. These provide flexibility in string construction.
Important Points About StringBuilder
- You should avoid excessive string appending in loops to prevent performance degradation.
- There should be proper synchronization when manipulating the same StringBuilder instance from multiple threads.
- You can reuse StringBuilder instances to minimize memory overhead and improve performance.
- You should avoid unnecessary conversions between StringBuilder and String to minimize overhead.