Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
19: String and StringBuilder
Why can't I just change one letter in a String?
I see this all the time when people start working with text in Java. You have a String, like a file path or a username, and you want to swap out a character or append a suffix. But you'll quickly realize that Strings in Java are immutable. This means once a String object is created in memory, it can never be changed.
If you try to "modify" a string, Java isn't actually changing the original; it's creating a brand new String object and tossing the old one aside. Here is what's happening under the hood:
String city = "New York";
city = city + " City";
// You didn't change "New York".
// Java created a new string "New York City" and pointed the 'city' variable to it.
It feels inefficient, but there's a reason for it. Immutability makes Strings thread-safe and allows Java to save memory through something called the String Pool. If ten different variables all hold the value "Admin", Java only needs to store that text once in memory.
When do I actually need to use StringBuilder?
If the + operator is so convenient, why bother with StringBuilder? Well, the "hidden" cost of immutability becomes a nightmare when you're in a loop. Imagine you're building a comma-separated list of 1,000 product IDs from a database. If you use + inside that loop, Java creates a new String object on every single iteration. That's a lot of garbage for the JVM to clean up, and your app will slow to a crawl.
This is where StringBuilder comes in. Think of it as a mutable "workspace" for text. It holds a buffer that it can expand without creating new objects every time you add a character.
// The slow way (Don't do this in a loop!)
String report = "";
for (String item : items) {
report += item + ", ";
}
// The professional way
StringBuilder sb = new StringBuilder();
for (String item : items) {
sb.append(item).append(", ");
}
String finalReport = sb.toString();
I generally follow this rule of thumb: if you're joining two or three strings together in one line, just use +. If you're building a string inside a loop or across multiple conditional blocks, reach for StringBuilder.
Is == actually the wrong way to compare strings?
Short answer: Yes. Almost always. I've seen countless bugs caused by this. In Java, == checks if two variables point to the exact same memory address. It does not check if the text inside them is the same.
Because of the String Pool I mentioned earlier, == might actually work sometimes by accident if you're using literals, but as soon as you get a string from a database, a user input field, or a network call, it will fail.
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2); // false - different objects in memory
System.out.println(s1.equals(s2)); // true - the actual characters are the same
Always use .equals(). If you want to ignore whether the user typed "JAVA" or "java", use .equalsIgnoreCase(). Trust me, your future self will thank you when you aren't debugging why a password check is failing even though the letters match.
📋 Practical Task
Build a Custom CSV Receipt Generator
You need to create a program that generates a formatted CSV (Comma Separated Values) string from a list of purchase items. Instead of using a simple array, you'll simulate a list of items and use StringBuilder to assemble the final output efficiently.
- Create a list of items (e.g., "Laptop", "Mouse", "Keyboard", "Monitor").
- Use a
StringBuilderto iterate through the list. - Each item should be appended to the builder, followed by a comma.
- Challenge: Ensure that the very last item does not have a trailing comma at the end of the string.
- Print the final result using
.toString().
There are no comments for now.