Mutable vs Immutable Strings in Java Strings are widely used in Java. Based on modification ability, they are classified into Immutable and Mutable. 🔹 Immutable String (String) An Immutable String cannot be changed after creation. Any modification creates a new object. 📌 Example: Java Copy code String s = "Hello"; s = s.concat(" World"); ✅ Features: • Cannot be modified • Creates new object on change • Stored in String Constant Pool • Memory efficient & secure 🔹 Mutable String (StringBuilder / StringBuffer) A Mutable String can be modified without creating a new object. 📌 Example: Java Copy code StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); ✅ Features: • Can be modified • Same object is updated • Faster for frequent changes • Better performance 🔹 Key Difference Immutable Mutable Cannot change Can change New object created Same object modified Uses String Uses StringBuilder / StringBuffer 🚀 Conclusion: Use String for fixed data. Use StringBuilder/StringBuffer for frequently changing data.
Java String Types: Immutable vs Mutable Strings
More Relevant Posts
-
Most Java developers get confused by this exception. Let me explain why. You run this code: System.out.println("12345".charAt(6)); And the stack trace says StringIndexOutOfBoundsException. But wait... shouldn't it be IndexOutOfBoundsException? 🤔 Here's the thing: it IS an IndexOutOfBoundsException. Java's exception hierarchy uses inheritance to give you MORE specific information, not different information. The hierarchy looks like this: RuntimeException └── IndexOutOfBoundsException ├── StringIndexOutOfBoundsException └── ArrayIndexOutOfBoundsException This is polymorphism applied to exceptions 💡 → charAt() throws StringIndexOutOfBoundsException because the problem happened in a String → array[10] throws ArrayIndexOutOfBoundsException because the problem happened in an array → list.get(99) throws IndexOutOfBoundsException because the problem happened in a collection → A catch(IndexOutOfBoundsException e) block catches ALL of them Why does this matter? When you write catch blocks, you can choose your level of specificity. Catching the parent handles everything. Catching the child gives you precise control over what you handle and what you propagate. This is the same design principle behind Java's entire exception framework: specificity through inheritance. Understanding this hierarchy is what separates a developer who reads stack traces from one who truly understands them. ⚡ What other Java exceptions have tripped you up? Drop them in the comments 👇 📊 Oracle Java SE 17 Docs - IndexOutOfBoundsException API (2025) https://lnkd.in/eN_5XAp4 📊 Baeldung - Java ArrayIndexOutOfBoundsException (2025) https://lnkd.in/evZcjMHs 📊 Rollbar - How to Handle StringIndexOutOfBoundsException in Java (2022) https://lnkd.in/erHwcX4T #Java #SoftwareEngineering #Backend #ExceptionHandling #Programming #OOP #JavaDeveloper #CleanCode
To view or add a comment, sign in
-
🚀 Java Series (2) – Understanding Java Variables (With JVM Memory Mapping) In Java, a variable is a name given to a memory location. It acts like a container that stores data during program execution. 👉 Variable = “vary + able” Meaning: Its value can change. Every variable must have a data type, which defines what kind of data it can store. 🎯 Types of Java Variables 1️⃣ Local Variables 2️⃣ Instance Variables 3️⃣ Static Variables Let’s understand them clearly — and where they are stored inside the JVM. 1️⃣ Local Variable 📌 Declared inside: Method Constructor Block 🔹 Characteristics • Created when method is called • Destroyed when method ends • Must be initialized before use • Scope limited to method/block 📍 Stored In JVM: 👉 Stack Memory When a method is invoked: A new stack frame is created Local variables are stored inside that frame When method completes → frame is removed 2️⃣ Instance Variable 📌 Declared inside class but outside methods. 🔹 Characteristics • Belongs to object • Each object has its own copy • Gets default values • Created when object is created 📍 Stored In JVM: 👉 Heap Memory Object stored in Heap Instance variables stored inside that object Reference variable (s) stored in Stack 3️⃣ Static Variable 📌 Declared using static keyword. 🔹 Characteristics • Belongs to class (not object) • Only one copy exists • Shared among all objects • Loaded once when class is loaded 📍 Stored In JVM: 👉 Method Area (Class Area) Static variables are stored in: Method Area Along with class metadata They are created when class is loaded by ClassLoader.
To view or add a comment, sign in
-
-
Day 4 :2-03-2026 Dynamic input means taking input from the user while the program is running (at runtime), instead of giving fixed values inside the program. In Java, dynamic input allows the program to accept data such as numbers, text, or characters from the user during execution. It makes the program flexible and interactive. The value is not predefined; it changes based on user input. For example (conceptually): The user enters their name → program stores it. The user enters a number → program performs calculation. Java Syntax (Only Syntax, No Example Program) In Java, dynamic input is commonly taken using the Scanner class from the java. util package. Import Statement import java. util. Scanner; Create Scanner Object Scanner variable Name = new Scanner(System.in); Methods to Take Input For integer: variable Name. nextInt(); For float: variableName.nextFloat(); For double: variableName.nextDouble(); For single word (String): variableName.next(); For full line (String): variableName.nextLine(); Short Definition (Exam Point) Dynamic input in Java means accepting user data at runtime using input classes like Scanner.
To view or add a comment, sign in
-
-
❗ Java Bug: Why final List or final Map Is Not Immutable in Java Recently, I ran into immunity issue in Java, which I've never paid attention before. It’s a common misconception that marking a field final automatically makes it “safe” or “immutable.” Unfortunately, this is not true when the field holds a mutable object such as a List or Map. Let’s look at this Java class: @Getter @Builder public class Plan { private final List<String> toDoList; } At first glance, this looks immutable: the field is final, and there is no setter. But watch what happens: List<String> initialToDoList = new ArrayList<>(Arrays.asList("Buy groceries", "Read a book", "Exercise")); var plan = Plan.builder().toDoList(initialToDoList).build(); List<String> firstList = plan.getToDoList(); firstList.size()==3; firstList .add("Learn Java"); //No Exception Obtain list again AFTER adding the item: List<String> secondList = plan.getToDoList(); Now firstList.size()==4 and secondList.size()==4 firstList contains the newly added item 'Learn Java' secondList contains the newly added item 'Learn Java' ❇️ Conclusion: Summary object looks immutable from the outside, but its internal state can be changed at any time. That’s not immutability—that’s an illusion of immutability. I feel it's a Java Bug. If it's final, why not just make it immutable no matter if it's a collection or not 😂. #Java
To view or add a comment, sign in
-
📌 Why Java Doesn’t Support Multiple Inheritance (And How It Solves the Problem) One of the most common Java interview questions: Why doesn’t Java support multiple inheritance? Let’s understand the real reason. 🤯 The Problem – The Diamond Problem Imagine this: class A { void show() { System.out.println("From A"); } } class B extends A { } class C extends A { } // Now what if: class D extends B, C { } // ❌ Not allowed in Java Now think carefully. If both B and C inherit show() from A,and D inherits from both… 👉 Which show() should Java call? This ambiguity is called the Diamond Problem. Languages like C++ allow this and resolve it differently. Java decided to avoid this confusion entirely. 🚫 So Java Does NOT Allow: class D extends B, C No multiple inheritance with classes. ✅ But Java Still Allows Multiple Inheritance (Smartly) Through Interfaces. interface A { void show(); } interface B { void show(); } class D implements A, B { public void show() { System.out.println("Resolved in D"); } } Here: - No ambiguity - No inherited implementation conflict - Child class provides implementation - Clean. Explicit. Safe. 🔥 What About Default Methods? (Java 8+) - Java 8 introduced default methods in interfaces. - Now the ambiguity can reappear. - Java handles it like this: - If two interfaces provide the same default method, the implementing class must override it. - Explicit resolution. - No confusion. #Java #OOP #SoftwareEngineering #InterviewPreparation #JavaDeveloper
To view or add a comment, sign in
-
-
Vector in Java 📖 Definition Vector is a dynamic array that can grow and shrink automatically. It is synchronized, which means it is thread-safe. Key Points:- ->Dynamic in size ->Maintains insertion order ->Allows duplicate elements ->Thread-safe 💻 Example: import java.util.Vector; class VectorExample { public static void main(String[] args) { Vector<String> v = new Vector<String>(); v.add("Apple"); v.add("Banana"); v.add("Mango"); System.out.println(v); } Output [Apple, Banana, Mango] **********Stack in Java********** 📖 Definition Stack is a class that follows LIFO (Last In First Out) principle. Last element added is removed first. Example; import java.util.Stack; class StackExample { public static void main(String[] args) { Stack<String> s = new Stack<String>(); s.push("Book1"); s.push("Book2"); s.push("Book3"); System.out.println(s.pop()); } } Output: Book3
To view or add a comment, sign in
-
🚀 Java Series – Day 7 📌 Strings in Java (Immutable Concept & String vs StringBuilder) 🔹 What is it? A String in Java is a sequence of characters used to represent text. One important concept about Strings is that they are immutable, meaning once a String object is created, its value cannot be changed. If we modify a String, Java actually creates a new object in memory instead of changing the existing one. 🔹 Why do we use it? Strings are widely used to handle text data such as usernames, messages, file names, or product descriptions. However, when we perform many modifications, creating new String objects repeatedly can affect performance. In such cases, Java provides StringBuilder, which allows mutable strings (values can be modified without creating new objects). 🔹 Example: public class Main { public static void main(String[] args) { // String (Immutable) String text = "Hello"; text = text + " Java"; // Creates a new String object // StringBuilder (Mutable) StringBuilder builder = new StringBuilder("Hello"); builder.append(" Java"); // Modifies the same object System.out.println(text); System.out.println(builder); } } 💡 Key Takeaway: Use String for simple text handling, but prefer StringBuilder when performing multiple modifications for better performance. What do you think about this? 👇 #Java #CoreJava #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
✅ Java Features – Step 18: Text Blocks (Java 15) 🧾 Before Java 15, writing multi-line strings required lots of concatenation. Example: String query = "SELECT * FROM users\n" + "WHERE age > 25\n" + "ORDER BY name"; Java 15 introduced Text Blocks, which allow clean multi-line strings. String query = """ SELECT * FROM users WHERE age > 25 ORDER BY name """; Why this matters Cleaner multi-line strings Great for SQL queries, JSON, HTML, and XML Less escaping and string concatenation Much more readable code Example with JSON String json = """ { "name": "Mariya", "role": "Developer" } """; Key takeaway Text blocks make working with structured text much easier and improve code readability. Next up: Java Records (Java 16) 🚀
To view or add a comment, sign in
-
Understanding Collection and List in Java 🔹 What is Collection in Java? The Collection Framework in Java is a unified architecture that provides interfaces and classes to store and manipulate groups of objects dynamically. It is available in the java.util package and offers ready-made data structures like List, Set, Queue, and more. Why use Collections instead of arrays? ✔ Dynamic size (grow/shrink at runtime) ✔ Built-in utility methods ✔ Better performance handling ✔ Easy data manipulation 🔹 What is List in Java? A List is a child interface of the Collection interface. A List: ✔ Maintains insertion order ✔ Allows duplicate elements ✔ Allows null values ✔ Supports index-based access It is mainly used when order and duplicates matter. 🔹 Types of List in Java 1️⃣ ArrayList Uses a dynamic array internally Fast for reading (random access) Slower for insert/delete in the middle Most commonly used List implementation 2️⃣ LinkedList Uses a doubly linked list internally Fast insertion and deletion Slower random access compared to ArrayList 3️⃣ Vector (Legacy Class) Similar to ArrayList Thread-safe (synchronized) Slower due to synchronization Rarely used in modern applications 4️⃣ Stack (Extends Vector) Follows LIFO (Last In First Out) Methods: push(), pop(), peek() In modern applications, Deque is preferred over Stack Additional Useful Methods: 1. remove(index) 2. remove(Object) 3. clear() 4. contains() 5. isEmpty() 6.add() 📌 Summary Collection provides the framework to manage groups of objects. List is an ordered collection that allows duplicates and index-based access. ArrayList and LinkedList are the most commonly used implementations in real-world applications. Frontlines EduTech (FLM) #Java #Collection #list
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development