TOPIC: StringBuffer in Java : StringBuffer is a class in Java used to create mutable (changeable) strings. Unlike the normal String class, the content of a StringBuffer object can be modified without creating a new object. This makes it more efficient when many string modifications are required. Key Characteristics Mutable: Content can be changed. Efficient: No new object created for every modification. Important Methods in StringBuffer : 1. append() Adds text to the end of the existing string. Example StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); System.out.println(sb); Output Hello World Explanation: append() simply adds the new string at the end. 2. insert() Inserts a string at a specific position (index). Example Java StringBuffer sb = new StringBuffer("Hello World"); sb.insert(5, ", Java"); System.out.println(sb); Output Hello, Java World Explanation: insert(5, ", Java") adds text at index position 5. 3. replace() Replaces characters between two index positions. Example StringBuffer sb = new StringBuffer("Hello Java World"); sb.replace(6, 10, "Amazing"); System.out.println(sb); Output Hello Amazing World Explanation: Characters from index 6 to 10 are replaced with "Amazing". 4. reverse() Reverses the entire string. Example StringBuffer sb = new StringBuffer("Hello Amazing World"); sb.reverse(); System.out.println(sb); Output dlroW gnizamA olleH Explanation: The entire string is reversed. append() → Adding new words at the end insert() → Adding a word in the middle replace() → Erasing and writing a new word reverse() → Writing the whole sentence backward #java #Codegnan #StringBuffer #StringHandling My big thanks to my mentor #AnandKumarBuddarapu #SakethKallepu #UppugundlaSairam
Java StringBuffer: Mutable Strings with append, insert, replace, and reverse methods
More Relevant Posts
-
Day 48 – Java 2026: Smart, Stable & Still the Future Non-Static Initializer in Java (Instance Initializer Explained) A non-static initializer block (also called an instance initializer block) is used to initialize instance variables of a class. Unlike static blocks, it executes every time an object of the class is created. It runs before the constructor but after the object memory is allocated in the heap. Syntax { // initialization code } This block does not use the static keyword because it works with object-level variables. Example class Example { int number; { System.out.println("Non-static initializer executed"); number = 100; } Example() { System.out.println("Constructor executed"); } public static void main(String[] args) { Example obj1 = new Example(); Example obj2 = new Example(); } } Output Non-static initializer executed Constructor executed Non-static initializer executed Constructor executed Execution Flow in JVM Class is loaded by the ClassLoader. Memory for the object is allocated in the Heap. Non-static initializer block executes. Constructor executes. Object becomes ready for use. Flow: Object Creation ↓ Memory allocated in Heap ↓ Non-static initializer executes ↓ Constructor executes Memory Structure Method Area Class metadata Static variables Static methods Heap Object instance variables Non-static initialization Stack Method execution frames Non-static initializers belong to object creation, so they work with Heap memory. When It Is Used Non-static initializer blocks are useful when: Common initialization code is required for all constructors Reducing duplicate logic inside multiple constructors Preparing instance-level configuration before constructor logic runs Key Point A non-static initializer executes every time an object is created, making it useful for object-level initialization before the constructor runs. #Java #JavaDeveloper #JVM #OOP #Programming #BackendDevelopment
To view or add a comment, sign in
-
🚀 Java Series – Day 28 📌 Reflection API in Java (How Spring Uses It) 🔹 What is it? The **Reflection API** allows Java programs to **inspect and manipulate classes, methods, fields, and annotations at runtime**. It allows operations like **creating objects dynamically, invoking methods, and reading annotations** without hardcoding them. 🔹 Why do we use it? Reflection helps in: ✔ Dependency Injection – automatically injects beans ✔ Annotation Processing – reads `@Autowired`, `@Service`, `@Repository` ✔ Proxy Creation – supports AOP and transactional features For example: In Spring, it can detect a class annotated with `@Service`, create an instance, and inject it wherever required without manual wiring. 🔹 Example: `import java.lang.reflect.*; @Service public class DemoService { public void greet() { System.out.println("Hello from DemoService"); } } public class Main { public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("DemoService"); // load class dynamically Object obj = clazz.getDeclaredConstructor().newInstance(); // create instance Method method = clazz.getMethod("greet"); // get method method.invoke(obj); // invoke method dynamically } }` 🔹 Output: `Hello from DemoService` 💡 Key Takeaway: Reflection makes Spring **dynamic, flexible, and powerful**, enabling features like DI, AOP, and annotation-based configuration without manual coding. What do you think about this? 👇 #Java #ReflectionAPI #SpringBoot #JavaDeveloper #BackendDevelopment #TechLearning #CodingTips
To view or add a comment, sign in
-
-
🧠 It's Monday and is time for a new java post. Now we go back to basics and who it was handled through the versions. Let's consider the method: public static String decorate(String value) { return "prefix$"+value+"$suffix"; } From Java 1 to 4 the concatenation would be equivalent to new StringBuffer("prefix$").append(value).append($suffix).toString(). This was would create a synchronized object, which inside would allocate an array that if need be would double its size every time you need extra space. Java 5-8 would play the same game but StringBuffer was replace with the non-synchronized StringBuilder. From Java 9 though you don't have a direct Java equivalent, or not straight forward at least as they switch to an implementation based on invoke dynamic. Let's see what javap produces: 0: aload_0 1: invokedynamic #16, 0 // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String; 6: areturn .... BootstrapMethods: 0: #29 REF_invokeStatic java/lang/invoke/StringConcatFactory.makeConcatWithConstants:(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite; Method arguments: #30 prefix$\u0001$suffix In laymen terms, the first time a concatenation would happen, the code would call StringConcatFactory::makeConcatWithConstants to create a object with a single String parameter and returning the another String. This method would replace \u0001 in the prefix$\u0001$suffix recipe however it would seem to be the best. The object than is cached and the actual method is called. Every time the same object will be reused. Did you as Java developers know about this latest process?
To view or add a comment, sign in
-
🔹 Why are Strings immutable in Java? This is one of the most common questions asked in Java interviews. But the real value is not just knowing that Strings are immutable — it's understanding why Java was designed this way. Let’s break it down in a simple way. 👇 📌 First, what does immutable mean? In Java, once a String object is created, its value cannot be changed. For example: String s = "Hello"; s.concat(" World"); You might expect the value to become "Hello World", but it doesn't change the original String. Instead, Java creates a new String object. 🔐 1. Security Strings are used in many sensitive areas like: • File paths • Database connections • Class loading • Network URLs Example: Class.forName("com.company.PaymentService"); If Strings were mutable, someone could modify the class name after validation and load a malicious class. Immutability helps keep these operations secure and predictable. 🧠 2. String Pool (Memory Optimization) Java maintains a special memory area called the String Constant Pool. When we write: String a = "hello"; String b = "hello"; Both variables point to the same object in memory. Because Strings cannot change, Java can safely reuse objects, saving a lot of memory in large applications. ⚡ 3. Thread Safety Immutable objects are naturally thread-safe. Multiple threads can read the same String without needing synchronization. This is extremely useful in high-concurrency backend systems like Spring Boot microservices. 🚀 4. Better Performance in HashMap Strings are commonly used as keys in HashMap. Since the value of a String never changes, its hashCode can be cached, which makes lookups faster. If Strings were mutable, the hash value could change and the object might become unreachable inside the map. 💡 In short Making Strings immutable improves: 🔐 Security 🧠 Memory efficiency ⚡ Performance 🧵 Thread safety Sometimes the most powerful design decisions in a programming language are the ones that quietly make systems more stable and predictable. Java’s immutable String is one of those brilliant decisions. ☕ #Java #JavaDevelopers #BackendDevelopment #JVM #Programming #SoftwareEngineering
To view or add a comment, sign in
-
Day 9 of Java Series ☕💻 Today’s topic is BufferedReader — a powerful way to take fast input in Java 🚀 🧠 What is BufferedReader? BufferedReader is a class in Java used to read text efficiently from input streams (like keyboard or file). It reads data in chunks (buffer) instead of character-by-character → faster performance ⚡ ⚙️ Why Use BufferedReader? ✔ Faster than Scanner ✔ Efficient for large input ✔ Reduces I/O operations ✔ Used in competitive programming 🔗 How it Works? 👉 Works with InputStreamReader to convert bytes into characters System.in → InputStreamReader → BufferedReader 💻 Example Code: import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter your name: "); String name = br.readLine(); System.out.println("Hello " + name); } } ⚡ Important Methods: readLine() → Reads full line read() → Reads single character close() → Closes stream ⚠️ Important Notes: Does NOT parse input automatically Must handle exceptions (IOException) Needs conversion for numbers 👉 Example: Java id="br2" Copy code int num = Integer.parseInt(br.readLine()); 🎯 Why Important? ✔ Used in interviews & CP ✔ Improves performance ✔ Important for backend & file handling 🚀 Pro Tip: Use BufferedReader + StringTokenizer for ultra-fast input in competitive programming 🔥 📢 Hashtags: #Java #BufferedReader #JavaSeries #Coding #Programming #Developers #LearnJava #Tech
To view or add a comment, sign in
-
-
⏳ Day 13 – 1 Minute Java Clarity – String Immutability in Java Strings look simple… but there’s something powerful happening behind the scenes 📌 What is String Immutability? In Java, once a String object is created, it cannot be changed. 👉 Instead of modifying the existing string, Java creates a new object. 📌 Example: String str = "Hello"; str.concat(" World"); System.out.println(str); 👉 Output: Hello ❌ (not "Hello World") 💡 Why? Because concat() creates a new object, but we didn’t store it. ✔ Correct way: str = str.concat(" World"); System.out.println(str); // Hello World ✅ 💡 Real-time Example: Think of a username in a system: String username = "user123"; username.toUpperCase(); Even after calling toUpperCase(), the original value stays "user123" unless reassigned. 📌 Why Strings are Immutable? ✔ Security (used in passwords, URLs) ✔ Thread-safe (no synchronization issues) ✔ Performance optimization using String Pool ⚠️ Important: Too many string modifications? Use StringBuilder instead. 💡 Quick Summary ✔ Strings cannot be modified after creation ✔ Operations create new objects ✔ Always reassign if you want changes 🔹 Next Topic → Type casting in Java Have you ever faced issues because of String immutability? 👇 #Java #JavaProgramming #Strings #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
Day 33 – Types of Inheritance in Java Today let's go deeper into Inheritance in Java, focusing on why we use it and the different types it offers. ---------------------------------------------- 🔹 Why Inheritance? 👉 The primary goal is Code Reusability 👉 Helps in Software Enhancement & Scalability 👉 Supports concepts like Polymorphism & Abstraction ---------------------------------------------- 🔹 Types of Inheritance in Java 📌 Java supports the following: 1️⃣ Single Level Inheritance → One child class inherits from one parent class 2️⃣ Multilevel Inheritance → A chain of inheritance (A → B → C) 3️⃣ Hierarchical Inheritance → Multiple child classes inherit from one parent 4️⃣ Multiple Inheritance (❌ Not supported with classes) → One class inheriting from multiple parents 5️⃣ Hybrid Inheritance → Combination of multiple types (achieved using interfaces in Java,also with class but it's should not be in cyclic from- cause diamond problem) ---------------------------------------------- 🔹 Examples (Simple Understanding) ✔ Single → A → B ✔ Multilevel → A → B → C ✔ Hierarchical → A → B & A → C ---------------------------------------------- 🔹 Important Rule ❌ Java does NOT support Multiple Inheritance using classes 👉 Reason: Diamond Problem (Ambiguity Issue) If a class inherits from two parents having the same method, ➡️ Java won’t know which method to execute This leads to confusion, so Java avoids it. ---------------------------------------------- 🔹 Final Keyword in Inheritance 👉 If a class is declared as final ❌ It cannot be extended final class A {} // class B extends A ❌ Not allowed #Java #OOP #Inheritance #LearningInPublic #Programming #Developers #SoftwareEngineering #JavaFullStack
To view or add a comment, sign in
-
-
Day 1 of practicing core Java concepts Solved a classic problem: Transpose of a Matrix using Java Problems like these are frequently asked to test: ✔️ Understanding of 2D arrays ✔️ Logical thinking ✔️ Code clarity Back to basics, one concept at a time. #InterviewPreparation #Java #DSA #Coding ================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online class Main { public static void main(String[] args) { int[][] a = new int[3][2]; a[0][0] = 1; a[1][0] = 3; a[2][0] = 5; a[0][1] = 2; a[1][1] = 4; a[2][1] = 6; // Print original matrix for (int row = 0; row < a.length; row++) { for (int col = 0; col < a[0].length; col++) { System.out.print(a[row][col] + " "); } System.out.println(); } int[][] result = new int[2][3]; // Transpose logic for (int row = 0; row < a.length; row++) { for (int col = 0; col < a[0].length; col++) { result[col][row] = a[row][col]; } } System.out.println("=== Transposed Matrix ==="); // Print transposed matrix for (int row = 0; row < result.length; row++) { for (int col = 0; col < result[0].length; col++) { System.out.print(result[row][col] + " "); } System.out.println(); } } }
To view or add a comment, sign in
-
-
☕ Java Core Concepts – Interview Question 📌 How is String creation using new() different from a literal? In Java, Strings can be created in two ways, and they behave differently in memory: 🔹 String Literal ("abc") • Stored in the String Pool (inside Heap) • JVM checks if the value already exists • If yes → returns reference of existing object • If no → creates a new object in the pool ✅ Memory efficient (reuses objects) 🔹 Using new Keyword (new String("abc")) • Always creates a new object in Heap memory • Does NOT reuse objects from String Pool ❌ Less memory efficient (creates duplicate objects) 🔹 Example: String s1 = "hello"; String s2 = "hello"; // reuses same object String s3 = new String("hello"); // new object in heap 🔹 Key Difference: ✔ Literal → Reuses existing objects (String Pool) ✔ new → Always creates a new object 💡 In Short: String literals save memory using the String Pool, while new always creates a fresh object, even if the value already exists. 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #String #JavaInterview #Programming #Coding #TechSkills#Ashokit
To view or add a comment, sign in
-
-
𝑫𝒊𝒇𝒇𝒆𝒓𝒆𝒏𝒄𝒆 𝒃𝒆𝒕𝒘𝒆𝒆𝒏 "𝒕𝒉𝒓𝒐𝒘" 𝒂𝒏𝒅 "𝒕𝒉𝒓𝒐𝒘𝒔" 𝒊𝒏 𝑱𝒂𝒗𝒂 Before understanding "throw" and "throws", one important point ➡️ Throwable is the parent class of Exception ➡️ Exception is the parent class of all Exceptions in Java. 🔍what actually "𝐭𝐡𝐫𝐨𝐰𝐬" mean ➡️It is used in method declaration 📃 "throws" is used to delegate (pass) the exception from one method to the calling method (the one who calls it) and not actually handles the exception. 📃JVM also does not handle it at this stage. Calling method provides try catch blocks to handle this exception. 📃 If not handled Exception goes to JVM.JVM terminates the program ❌ 🔍 Definition of "throw" 📃 "throw" is used to explicitly throw an exception. It stops the normal execution flow. 📃It is used inside a method, The exception is then passed to caller method. 👨💻 Example 𝐢𝐦𝐩𝐨𝐫𝐭 𝐣𝐚𝐯𝐚.𝐢𝐨.*; 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞() 𝐭𝐡𝐫𝐨𝐰𝐬 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 { 𝐅𝐢𝐥𝐞 𝐟𝐢𝐥𝐞 = 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞("𝐃://𝐟𝐢𝐥𝐞𝟏.𝐭𝐱𝐭"); 𝐭𝐡𝐫𝐨𝐰 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧("𝐅𝐢𝐥𝐞 𝐧𝐨𝐭 𝐟𝐨𝐮𝐧𝐝"); } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐭𝐫𝐲 { 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞(); } 𝐜𝐚𝐭𝐜𝐡 (𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐞) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐈𝐧𝐯𝐚𝐥𝐢𝐝 𝐅𝐢𝐥𝐞 𝐍𝐚𝐦𝐞"); } } } 📝𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞() 𝐭𝐡𝐫𝐨𝐰𝐬 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 This method is declaring an exception using throws ⚖️“I will not handle this exception” ☎️“Whoever calls me should handle it” 📝 𝐭𝐡𝐫𝐨𝐰 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧("𝐅𝐢𝐥𝐞 𝐧𝐨𝐭 𝐟𝐨𝐮𝐧𝐝"); ▪️Here we are manually throwing exception using throw Important: Execution stops here immediately Control goes to calling method 📝𝐭𝐫𝐲 { 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞();} ▪️Calling the method which has throws Since it declared exception → ▪️We must handle it using try-catch 📝 𝐜𝐚𝐭𝐜𝐡 (𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐞) Catch block handles the exception ♣️ Key Difference "throws" → delegates exception (method level) ➡️ passing responsibility "throw" → actually throws exception (statement level) ➡️ creating the problem #Java #JavaDeveloper #JavaConcepts #ExceptionHandling #Programming #TechJourney #InterviewPrep
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