➡️Mutable Strings in Java In Java, mutable strings are objects whose content can be changed without creating a new object. They are designed for better performance when frequent string modifications are required. 🔸 Why Mutable Strings? String objects are immutable. Every modification creates a new object, which increases memory usage and affects performance. Mutable strings solve this problem. 🔸 Mutable String Classes in Java Java provides two mutable string classes: ✔ StringBuilder Mutable Faster Not thread-safe Used in single-threaded environments ✔ StringBuffer Mutable Thread-safe (synchronized) Slower than StringBuilder Used in multi-threaded environments 🔸 Example StringBuilder sb = new StringBuilder("Java"); sb.append(" Programming"); System.out.println(sb); // Java Programming ✔ Same object is modified ✔ No extra memory wastage 🔸 Common Methods append() → add text insert() → insert at specific index delete() → remove characters reverse() → reverse string replace() → replace characters 🔑 Key Takeaway ✔ Use String for fixed data ✔ Use StringBuilder for fast modifications ✔ Use StringBuffer for thread-safe operations #Java #CoreJava #String #StringBuilder #StringBuffer #Programming #JavaDeveloper
Java Mutable Strings: StringBuilder vs StringBuffer
More Relevant Posts
-
🚀 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
-
📌 Callable vs Runnable in Java — Returning Results from Threads In multithreading, not all tasks are the same. Sometimes we need a thread to return a result. This is where Callable comes in. 1️⃣ Runnable • Introduced in Java 1.0 • Does NOT return a result • Cannot throw checked exceptions Example: Runnable task = () -> { System.out.println("Running task"); }; 2️⃣ Callable • Introduced in Java 5 • Returns a result • Can throw checked exceptions Example: Callable<Integer> task = () -> { return 10; }; 3️⃣ Using Callable with Executor ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Integer> future = executor.submit(task); Integer result = future.get(); executor.shutdown(); 4️⃣ What Is Future? Future represents: • Result of an asynchronous computation • Allows checking if task is complete • Can retrieve result using get() 5️⃣ Key Differences Runnable: • No return value • No checked exceptions Callable: • Returns value • Throws checked exceptions • Used with Future 🧠 Key Takeaway Runnable is for fire-and-forget tasks. Callable is for tasks that produce results. Future bridges asynchronous execution with synchronous result retrieval. #Java #Multithreading #ExecutorService #Callable #Concurrency
To view or add a comment, sign in
-
Day - 28 : Set in Java In Java, the Set interface is a part of the Java Collection Framework, located in the java.util package. It represents a collection of unique elements, meaning it does not allow duplicate values. 1) The set interface does not allow duplicate elements. 2) It can contain at most one null value except TreeSet implementation which does not allow null. 3)The set interface provides efficient search, insertion, and deletion operations. ● Example : import java.util.HashSet; import java.util.Set; public class java { public static void main(String args[]) { Set<String> s = new HashSet<>( ); System.out.println("Set Elements: " + s); } } ● Classes that implement the Set interface a) HashSet: A set that stores unique elements without any specific order, using a hash table and allows one null element. b) EnumSet : A high-performance set designed specifically for enum types, where all elements must belong to the same enum. c) LinkedHashSet: A set that maintains the order of insertion while storing unique elements. d) TreeSet: A set that stores unique elements in sorted order, either by natural ordering or a specified comparator. #Java #JavaProgramming #TreeMap #JavaDeveloper #Programming #Coding #SoftwareDevelopment #LearnJava #JavaLearning #BackendDevelopment EchoBrains
To view or add a comment, sign in
-
-
🚀 Java Series – Day 15 📌 Exception Handling in Java (try-catch-finally & Checked vs Unchecked) 🔹 What is it? Exception Handling in Java is used to handle runtime errors so that the program can continue executing smoothly. Java provides keywords to handle exceptions: • try – Code that may cause an exception • catch – Handles the exception • finally – Always executes (used for cleanup) 🔹 Why do we use it? Exception handling helps prevent program crashes and ensures better user experience. For example: In a file upload system, if a file is not found or an error occurs, instead of crashing, the program can show a proper error message and continue execution. Also, Java classifies exceptions into: • Checked Exceptions – Checked at compile time (e.g., IOException) • Unchecked Exceptions – Occur at runtime (e.g., NullPointerException, ArithmeticException) 🔹 Example: public class Main { public static void main(String[] args) { try { int result = 10 / 0; // Exception } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Execution completed"); } } } 💡 Key Takeaway: Exception handling ensures robust and crash-free applications by managing errors effectively. What do you think about this? 👇 #Java #ExceptionHandling #JavaDeveloper #Programming #BackendDevelopment
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
-
-
Day 47 – Java 2026: Smart, Stable & Still the Future Static Initializer in Java (ClassLoader & Memory Explained) A static initializer block in Java is used to initialize static variables. It executes only once when the class is loaded into memory by the JVM ClassLoader, before any object is created. It is useful when initialization requires logic or multiple statements, not just a direct assignment. class Example { static int number; static { System.out.println("Static block executed"); number = 50; } public static void main(String[] args) { System.out.println("Main method started"); System.out.println("Number: " + number); } } Output Static block executed Main method started Number: 50 How it Works in JVM When a Java program runs, the JVM loads classes using the ClassLoader in three steps: Loading – .class file is loaded into JVM memory (Method Area). Linking – JVM verifies the class and allocates memory for static variables. Initialization – static variables and static blocks execute. Memory Structure Method Area Class metadata Static variables Static blocks Heap Objects created using new Stack Method execution frames Static members are stored in the Method Area because they belong to the class, not to objects. Key Point A static initializer runs only once during class loading, ensuring efficient one-time setup such as configuration loading, driver initialization, or cache preparation. #Java #JavaDeveloper #JVM #ClassLoader #BackendDevelopment #Programming#100series
To view or add a comment, sign in
-
ArrayList ✈️ In Java, an ArrayList is a member of the Java Collections Framework and resides in the java.util package. While a standard Java array (e.g., int[]) is fixed in length, an ArrayList is a resizable-array implementation of the List interface. How It Works: The "Growing" Mechanism When you add an element to an ArrayList, Java checks if there is enough room in the underlying memory. If the internal array is full, the ArrayList performs the following: It allocates a new, larger array ✅Key Features in Java Type Safety: It uses Generics, allowing you to specify what type of data it holds (e.g., ArrayList<String>). Wrapper Classes: It cannot store primitive types (like int, double, char) directly. Instead, Java uses "Autoboxing" to convert them into objects (like Integer, Double, Character). Nulls and Duplicates: It allows you to store duplicate elements and null values. Unsynchronized: By default, it is not thread-safe. If multiple threads access it simultaneously, you must handle synchronization manually. It copies all existing elements to the new array. It updates its internal reference to this new array. ✅ArrayList vs. LinkedList A common interview question is when to use ArrayList over LinkedList. ArrayList: Best for frequent access and storing data where you mostly add/remove from the end. LinkedList: Best if you are constantly inserting or deleting items from the beginning or middle of the list. Would you like me to explain the specific differences between ArrayList and Vector, or perhaps show you how to sort an ArrayList using Collections.sort(). Huge thanks for the mentorship on Java ArrayList Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam #ArrayList #Java #DataStructures #Programming #Coding #SoftwareEngineering #Backend #JavaDeveloper #Algorithms #TechTips #ComputerScience
To view or add a comment, sign in
-
Java Fundamentals Series – Day 5 Garbage Collection in Java : In Java, developers do not need to manually free memory. JVM automatically manages memory using Garbage Collection (GC). The Garbage Collector is an Mechanism were default implemented inside JVM which is Invoke automatically In java there has a method gC() which is present inside the System Class this gC() method is a static method so there is no need for object to invoke this method so we can able to access this particular method by the class name *** System.gC() ***. By help of this method we just provide the request to JVM to call the ** Garbage Collector ** but we cannot assure that it may or may not be call the GC . It is totally depends on JVM here we just provide request. What is Garbage Collection? Garbage Collection is the process of automatically removing unused objects from Heap memory. Why GC is Important? 1 Prevents memory leaks 2 Frees unused memory 3 Improves application performance How GC Works? 1 JVM identifies objects that are no longer referenced 2 These objects become eligible for garbage collection 3 GC reclaims the memory occupied by them 4 It removes the memory for anonymous. object Method : void finalize(): Incase we needed to do some set of work before GC get Called in that particular time we can use this finalize () this method is defined as protected for example - closing the file this like operation.we can able to provide inside this finalize() method #Java #GarbageCollection #JVM #BackendDeveloper #Placements
To view or add a comment, sign in
-
Core Java Fundamentals :Key Traits of Metaspace Permanent Generation in Java PermGen (Permanent Generation) was a memory area in the Java Virtual Machine (JVM) used before Java 8 to store class metadata, interned strings, and static variables. It was part of the JVM heap space and had a fixed size, making it difficult to manage memory efficiently. Fixed and Hard-to-Tune Size in PermGen PermGen had a fixed maximum size, which was often too small for applications with many classes. Correct Tuning was Tricky Even though it was configurable using -XX:MaxPermSize, tuning it correctly was difficult. PermGen was not dynamically expanding Unlike Metaspace, on the other hand, dynamically expands using native memory, eliminating manual tuning issues. OutOfMemoryError If class metadata exceeded 256MB, the application would crash with OutOfMemoryError: PermGen space. Key Features of Metaspace Stores Class Metadata It holds information about classes, methods, and their runtime representations (like method bytecode and field details). Unlike PermGen, it does not store Java objects (which reside in the heap). Uses Native Memory Unlike PermGen, which had a fixed maximum size, Metaspace dynamically expands using native memory(outside the heap), reducing Out of memory errors. Automatic Growth & GC Handling The JVM automatically manages Metaspace size based on the application’s needs. Class metadata is garbage collected when classes are no longer needed (such as when an application uses dynamic class loading). Configurable Maximum Size -XX:MaxMetaspaceSize=256m // Limits Metaspace to 256MB -XX:MetaspaceSize=128m // Initial size before expanding ☕ If this helped you — support my work: 👉 Buy Me a Coffee -https://lnkd.in/ebXVUJn2 #JVMInternals #JavaPerformance #MemoryManagement #SpringBoot #Microservices #SystemDesign
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
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