0% found this document useful (0 votes)
3 views8 pages

String

The document provides an overview of strings in Java, highlighting the three main classes: `String` (immutable), `StringBuilder` (mutable and not thread-safe), and `StringBuffer` (mutable and thread-safe). It details the characteristics, methods, and use cases for each class, emphasizing when to use each based on mutability and thread safety. Key takeaways include the immutability of `String`, the speed of `StringBuilder`, and the thread safety of `StringBuffer`.

Uploaded by

kauramrit1128
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

String

The document provides an overview of strings in Java, highlighting the three main classes: `String` (immutable), `StringBuilder` (mutable and not thread-safe), and `StringBuffer` (mutable and thread-safe). It details the characteristics, methods, and use cases for each class, emphasizing when to use each based on mutability and thread safety. Key takeaways include the immutability of `String`, the speed of `StringBuilder`, and the thread safety of `StringBuffer`.

Uploaded by

kauramrit1128
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

# **Strings in Java**

Strings are sequences of characters used to store


and manipulate text. In Java, strings are
**immutable** (cannot be changed after creation).
Java provides three main classes for string
manipulation:

1. **`String`** (Immutable)
2. **`StringBuilder`** (Mutable, Not Thread-Safe)
3. **`StringBuffer`** (Mutable, Thread-Safe)

---

## **1. `String` Class (Immutable)**


- Once created, its value **cannot be changed**.
- Any modification creates a **new `String`
object**.
- Stored in the **String Pool** (for memory
efficiency).
### **String Creation**
```java
String str1 = "Hello"; // String literal (stored in
String Pool)
String str2 = new String("Hello"); // New object in
heap memory
```

### **Common `String` Methods**


| Method | Description | Example |
|--------|-------------|---------|
| `length()` | Returns string length | `"Java".length()`
→ `4` |
| `charAt(int)` | Returns char at given index |
`"Java".charAt(1)` → `'a'` |
| `concat(String)` | Concatenates strings |
`"Hello".concat(" Java")` → `"Hello Java"` |
| `equals(String)` | Checks content equality |
`"Java".equals("java")` → `false` |
| `equalsIgnoreCase(String)` | Case-insensitive
comparison | `"Java".equalsIgnoreCase("JAVA")` →
`true` |
| `substring(int, int)` | Extracts substring |
`"Hello".substring(1,4)` → `"ell"` |
| `toLowerCase()` | Converts to lowercase |
`"JAVA".toLowerCase()` → `"java"` |
| `toUpperCase()` | Converts to uppercase |
`"java".toUpperCase()` → `"JAVA"` |
| `trim()` | Removes leading/trailing spaces | `" Java
".trim()` → `"Java"` |
| `replace(char, char)` | Replaces characters |
`"Java".replace('a', 'o')` → `"Jovo"` |
| `split(String)` | Splits into an array |
`"A,B,C".split(",")` → `["A", "B", "C"]` |
| `indexOf(String)` | Finds first occurrence |
`"Java".indexOf("a")` → `1` |
| `contains(String)` | Checks if substring exists |
`"Java".contains("av")` → `true` |

### **Example: String Operations**


```java
String s = " Hello Java ";
[Link]([Link]()); // "Hello Java"
[Link]([Link](1, 6)); // "Hello"
[Link]([Link]("Java", "World")); // "
Hello World "
[Link]([Link]()); // " hello java "
```

---

## **2. `StringBuilder` (Mutable & Not Thread-


Safe)**
- **Modifiable** (changes affect the same object).
- **Faster** than `StringBuffer` (no thread safety
overhead).
- Used when **frequent modifications** are
needed.

### **StringBuilder Methods**


| Method | Description | Example |
|--------|-------------|---------|
| `append(String)` | Adds to the end | `[Link]("
World")` |
| `insert(int, String)` | Inserts at given index |
`[Link](5, " Awesome")` |
| `delete(int, int)` | Removes substring | `[Link](5,
10)` |
| `reverse()` | Reverses the string | `[Link]()` |
| `toString()` | Converts to `String` | `[Link]()` |

### **Example: StringBuilder Usage**


```java
StringBuilder sb = new StringBuilder("Hello");
[Link](" Java"); // "Hello Java"
[Link](5, " Awesome"); // "Hello Awesome Java"
[Link](6, 14); // "Hello Java"
[Link](); // "avaJ olleH"
String result = [Link](); // Converts to String
```

---

## **3. `StringBuffer` (Mutable & Thread-Safe)**


- Similar to `StringBuilder` but **thread-safe**
(slower due to synchronization).
- Used in **multi-threaded environments**.

### **StringBuffer Methods**


Same as `StringBuilder`:
- `append()`, `insert()`, `delete()`, `reverse()`,
`toString()`

### **Example: StringBuffer Usage**


```java
StringBuffer sbuf = new StringBuffer("Hello");
[Link](" Java"); // "Hello Java"
[Link](); // "avaJ olleH"
```

---

## **Comparison: `String` vs `StringBuilder` vs


`StringBuffer**
| Feature | `String` | `StringBuilder` | `StringBuffer` |
|---------|----------|----------------|----------------|
| **Mutability** | Immutable | Mutable | Mutable |
| **Thread Safety** | Yes (immutable) | No | Yes
(synchronized) |
| **Performance** | Slow (creates new objects) |
Fast | Slower than `StringBuilder` |
| **Use Case** | Storing fixed strings | Single-
threaded modifications | Multi-threaded
modifications |

---

## **When to Use Which?**


- Use **`String`** if the value **doesn’t change**
(e.g., constants).
- Use **`StringBuilder`** for **efficient string
manipulation** in single-threaded apps.
- Use **`StringBuffer`** for **thread-safe string
operations** (rarely needed in modern Java).

---

## **Key Takeaways**
✅ **`String`** → Immutable, stored in String Pool.
✅ **`StringBuilder`** → Mutable, fast, not thread-
safe.
✅ **`StringBuffer`** → Mutable, thread-safe,
slower.

You might also like