🔥 Understanding StringBuffer, StringBuilder & StringTokenizer in Java When working with strings in Java, choosing the right class can significantly impact performance and memory usage. Most beginners use String everywhere — but in real-world applications, mutable strings are often the better choice. Let’s break it down 👇 🔹 1️⃣ StringBuffer – Thread-Safe & Mutable StringBuffer is a mutable sequence of characters. ✔ Default capacity = 16 ✔ Automatically increases capacity when needed ✔ Synchronized (Thread-safe) ✔ Slower than StringBuilder (because of synchronization) 📌 Capacity formula when full: (current capacity × 2) + 2 Example: Java 👇 StringBuffer sb = new StringBuffer(); sb.append("JAVA"); sb.append("JAVASCRIPT"); System.out.println(sb.capacity()); 🔹 2️⃣ StringBuilder – Faster Alternative StringBuilder is almost the same as StringBuffer but: ✔ Not synchronized ✔ Faster ✔ Best for single-threaded applications Use this when performance matters and multiple threads are NOT modifying the same object. 🔹 3️⃣ StringTokenizer – Breaking Strings into Tokens StringTokenizer is used to split a string into smaller parts (tokens). Example: Java 👇 StringTokenizer st = new StringTokenizer("JAVA PYTHON SQL"); while(st.hasMoreTokens()){ System.out.println(st.nextToken()); } 🚀 Important Points to Remember ✔ String is immutable ✔ StringBuffer & StringBuilder are mutable ✔ StringBuffer is thread-safe ✔ StringBuilder is faster ✔ Capacity grows automatically ✔ Use trimToSize() to reduce unused memory ✔ StringTokenizer acts like a cursor to fetch tokens 💼 Best Real-Time Example 🔥 Example: Building Dynamic SQL Queries In enterprise applications: Instead of: Java 👇 String query = ""; query += "SELECT * FROM users "; query += "WHERE status = 'ACTIVE'". This creates multiple unnecessary string objects ❌ Better way: Java 👇 StringBuilder query = new StringBuilder(); query.append("SELECT * FROM users "); query.append("WHERE status = 'ACTIVE'"); ✔ More memory efficient ✔ Better performance ✔ Used in backend systems daily 🎯 When to Use What? Scenario Recommended Single-threaded app StringBuilder Multi-threaded app StringBuffer Simple fixed text String Token parsing StringTokenizer / split() 💡 Choosing the right string class improves performance, reduces memory overhead, and makes your application scalable. TAP Academy #Java #Programming #BackendDevelopment #StringBuilder #StringBuffer #SoftwareEngineering #Coding
Java String Classes: StringBuffer, StringBuilder & StringTokenizer Explained
More Relevant Posts
-
Day 28: Exploring Strings in Java Today I practiced some important concepts related to Strings in Java and how they behave in memory. One of the key characteristics of Java Strings is that they are "immutable". This means once a String object is created, its value cannot be changed. Any operation like replace() or concat() creates a new String object instead of modifying the existing one. For scenarios where frequent modifications are required, using StringBuilder or StringBuffer is recommended because they are mutable. 🔹 Ways to create Strings in Java String str1 = "java"; // String literal String str2 = new String("java"); // Using new operator When Strings are created using literals, they are stored in the String Constant Pool (SCP) inside the heap memory. The SCP avoids duplicate objects to save memory. Because of this: String str1 = "java"; String str3 = "java"; System.out.println(str1 == str3); // true "==" returns true because both references point to the same object in the String Constant Pool. But when we create a String using the new operator: String str3 = new String("java"); System.out.println(str1 == str3); // false System.out.println(str1.equals(str3)); // true == compares memory addresses, while .equals() compares actual values. 🔹 Immutability Example String str7 = "Hello "; str7.concat("Everyone"); System.out.println(str7); // Output: Hello The String is not modified because Strings are immutable. 🔹 Mutable Alternative StringBuilder sb = new StringBuilder("Hello "); sb.append("Everyone"); System.out.println(sb); //Output: Hello Everyone StringBuilder and StringBuffer allow modification without creating multiple objects, making them better for frequent string manipulations in problem solving. 📌 Key Takeaways • Strings are immutable in Java • == compares references, .equals() compares values • String literals use the String Constant Pool • Use StringBuilder/StringBuffer when frequent modifications are required Learning these concepts helped me better understand how Java manages memory and string operations internally. #Java #Programming #JavaDeveloper #CodingJourney #SoftwareDevelopment #LearningInPublic Raviteja T Mohammed Abdul Rahman 10000 Coders
To view or add a comment, sign in
-
-
🚀 Day 6/100 — Methods in Java 🔧 As programs grow bigger, repeating the same code again and again becomes messy. This is where methods help. A method is a reusable block of code that performs a specific task. Instead of rewriting logic multiple times, you write it once and call it whenever needed. This follows the DRY principle — Don't Repeat Yourself. 🔹 Basic Method Syntax returnType methodName(parameters){ // method body } Example: public static void greet(){ System.out.println("Hello Java!"); } Calling the method: greet(); Output: Hello Java! 🔹 Method with Parameters Parameters allow methods to work with different inputs. Example: public static void add(int a, int b){ int sum = a + b; System.out.println(sum); } add(5, 3); Output: 8 🔹 Method with Return Value Sometimes a method needs to return a result. Example: public static int square(int num){ return num * num; } int result = square(4); System.out.println(result); Output: 16 🔹 Method Overloading Java allows multiple methods with the same name but different parameters. This is called method overloading. Java automatically chooses the correct method based on the arguments. Example: public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } Usage: System.out.println(add(5,3)); // calls first method System.out.println(add(5,3,2)); // calls second method 🔴 Live Example — Max of 3 Numbers public static int max(int a, int b, int c){ if(a >= b && a >= c){ return a; } else if(b >= a && b >= c){ return b; } else{ return c; } } public static void main(String[] args){ int result = max(10, 25, 15); System.out.println("Maximum number is: " + result); } Output: Maximum number is: 25 🎯 Challenge: Write a method to find the maximum of 3 numbers and test it with different inputs. Drop your solution in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaMethods #ProgrammingJourney
To view or add a comment, sign in
-
-
𝗗𝗔𝗬 𝟯 – 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲 𝗼𝗳 𝗮 𝗝𝗮𝘃𝗮 𝗣𝗿𝗼𝗴𝗿𝗮𝗺 + 𝗝𝗮𝘃𝗮 𝗧𝗼𝗸𝗲𝗻𝘀 𝗜𝗻 𝘁𝗵𝗲 𝗹𝗮𝘀𝘁 𝘁𝘄𝗼 𝗽𝗼𝘀𝘁𝘀 𝘄𝗲 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗼𝗼𝗱: • Why Java is Platform Independent • How JDK, JRE, and JVM work together to run a Java program Now it's time to move from 𝘁𝗵𝗲𝗼𝗿𝘆 → 𝗮𝗰𝘁𝘂𝗮𝗹 𝗰𝗼𝗱𝗲. 𝗟𝗲𝘁’𝘀 𝘄𝗿𝗶𝘁𝗲 𝗮 𝘀𝗶𝗺𝗽𝗹𝗲 𝗝𝗮𝘃𝗮 𝗽𝗿𝗼𝗴𝗿𝗮𝗺. ``` 𝚙𝚞𝚋𝚕𝚒𝚌 𝚌𝚕𝚊𝚜𝚜 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍 { 𝚙𝚞𝚋𝚕𝚒𝚌 𝚜𝚝𝚊𝚝𝚒𝚌 𝚟𝚘𝚒𝚍 𝚖𝚊𝚒𝚗(𝚂𝚝𝚛𝚒𝚗𝚐[] 𝚊𝚛𝚐𝚜) { 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗("𝙷𝚎𝚕𝚕𝚘 𝚆𝚘𝚛𝚕𝚍"); } } ``` At first glance this may look confusing. But if we break it down, the structure becomes very simple. 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲 𝗼𝗳 𝗮 𝗝𝗮𝘃𝗮 𝗣𝗿𝗼𝗴𝗿𝗮𝗺 Every Java program generally contains: 1️⃣ 𝗖𝗹𝗮𝘀𝘀 𝗗𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻 𝚙𝚞𝚋𝚕𝚒𝚌 𝚌𝚕𝚊𝚜𝚜 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍 In Java, everything starts with a class. The filename must match the class name. Example: 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍.𝚓𝚊𝚟𝚊 2️⃣ 𝗠𝗮𝗶𝗻 𝗠𝗲𝘁𝗵𝗼𝗱 𝚙𝚞𝚋𝚕𝚒𝚌 𝚜𝚝𝚊𝚝𝚒𝚌 𝚟𝚘𝚒𝚍 𝚖𝚊𝚒𝚗(𝚂𝚝𝚛𝚒𝚗𝚐[] 𝚊𝚛𝚐𝚜) This is the entry point of every Java program. When we run a program, the JVM starts execution from the 𝗺𝗮𝗶𝗻() 𝗺𝗲𝘁𝗵𝗼𝗱. 3️⃣ 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁𝘀 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗("𝙷𝚎𝚕𝚕𝚘 𝚆𝚘𝚛𝚕𝚍"); This statement simply prints output on the console. 𝗡𝗼𝘄 𝗹𝗲𝘁’𝘀 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝘀𝗼𝗺𝗲𝘁𝗵𝗶𝗻𝗴 𝘃𝗲𝗿𝘆 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗶𝗻 𝗝𝗮𝘃𝗮. 𝗝𝗮𝘃𝗮 𝗧𝗼𝗸𝗲𝗻𝘀 Tokens are the smallest building blocks of a Java program. Java programs are basically made up of tokens. 𝗧𝗵𝗲𝗿𝗲 𝗮𝗿𝗲 𝗺𝗮𝗶𝗻𝗹𝘆 𝟱 𝘁𝘆𝗽𝗲𝘀: • 𝗞𝗲𝘆𝘄𝗼𝗿𝗱𝘀 → public, class, static, void • 𝗜𝗱𝗲𝗻𝘁𝗶𝗳𝗶𝗲𝗿𝘀 → names of variables, classes, methods • 𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝘀 → actual values (10, "Hello", true) • 𝗦𝗲𝗽𝗮𝗿𝗮𝘁𝗼𝗿𝘀 → { } ( ) [ ] ; , • 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 → + - * / = == Example identifier rules: ✔ Cannot start with a number ✔ Cannot use Java keywords ✔ No spaces allowed ✔ Can use letters, numbers, _ and $ Once you understand structure + tokens, reading Java code becomes much easier. If you look at the Java program again, you’ll now notice: It is simply a combination of tokens working together. Once you understand tokens and structure, reading Java code becomes much easier. 𝗧𝗼𝗺𝗼𝗿𝗿𝗼𝘄 (𝗗𝗮𝘆 𝟰) 𝗪𝗲’𝗹𝗹 𝗴𝗼 𝗱𝗲𝗲𝗽𝗲𝗿 𝗶𝗻𝘁𝗼 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝘁𝗼𝗽𝗶𝗰𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮: • Data Types • Variables • Primitive vs Non-Primitive types • Memory basics behind variables Because before writing real programs, understanding how Java stores data is critical. 𝗦𝗲𝗲 𝘆𝗼𝘂 𝗶𝗻 𝗗𝗮𝘆 𝟰. #Java #BackendDevelopment #Programming #LearnInPublic #Day3
To view or add a comment, sign in
-
🚀 Day 24 – Java Concepts for Interviews Method Overriding | Final Keyword | Method Hiding 🔹 1️⃣ Class Terminology In Java inheritance: Parent class → Superclass / Base class Child class → Subclass / Derived class The relationship is called an “is-a” relationship and is created using the extends keyword. 🔹 2️⃣ Method Overriding – 4 Important Rules Method overriding means a child class inherits a method and changes its implementation. Always use @Override for better readability and compile-time checking. Rule 1 – Access Modifier The child method must have same or higher visibility. Visibility order: private → default → protected → public Example: If parent method is protected, child can use: ✔ protected ✔ public ❌ default ❌ private Rule 2 – Return Type Return type must normally be same as parent method. Rule 3 – Covariant Return Type (JDK 5+) Child method can return a subclass type. Example: class Animal {} class Lion extends Animal {} class Base { Animal display() { return new Animal(); } } class Derived extends Base { @Override Lion display() { return new Lion(); } // Valid } ⚠ Works only for objects, not primitives like int, double. Rule 4 – Parameters Parameters must be exactly the same: same number same type same order Only method body changes, not the signature. 🔹 3️⃣ Overriding vs Overloading (Interview Trap) If parent has: display() and child has: display(int a, int b, int c) This is NOT overriding ❌ This is method overloading ✔ Because parameters are different. Using @Override here will give a compile-time error. 🔹 4️⃣ Final Keyword in Java final can be used with variables, methods, and classes. Final Variable Becomes a constant. final float PI = 3.142f; PI = 3.14f; // Error Convention: UPPERCASE_SNAKE_CASE Example: MAX_VALUE, MIN_VALUE Final Method Can be inherited Cannot be overridden Used when behavior must not change in child classes. Final Class A final class cannot be extended. Example: final class Calculator {} class Child extends Calculator {} // Compilation error Examples in Java: String, StringBuilder, StringBuffer, wrapper classes like Integer. 🔹 5️⃣ Static Members and Inheritance Static Variables If child declares the same variable → Variable Hiding Static Methods Static methods cannot be overridden. If same method exists in child → Method Hiding Example: class Parent { static void display() { System.out.println("Parent"); } } class Child extends Parent { static void display() { System.out.println("Child"); // Method hiding } } Using @Override here → ❌ Compilation error #Java #JavaProgramming #OOP #MethodOverriding #MethodOverloading #FinalKeyword #JavaInterviewQuestions #CodingInterview #SoftwareEngineering #LearnJava #100DaysOfCode #Day24
To view or add a comment, sign in
-
-
🚀 Java Collections Framework – Explained Simply Today I want to explain one of the most important concepts in Java: Collections. When working with Java applications, we often need to store and manage groups of objects. Instead of using arrays with fixed sizes, Java provides the Collections Framework, which allows us to store, manage, and manipulate data dynamically. 🔹 What is a Collection in Java? A Collection is a framework that provides an architecture to store and manipulate a group of objects. With collections we can easily: • Add elements • Remove elements • Search elements • Sort data • Traverse through elements All collection classes are available in the java.util package. ⸻ 📌 Main Interfaces in the Collection Framework The Java Collections Framework mainly includes: 1️⃣ List 2️⃣ Set 3️⃣ Queue 4️⃣ Map (part of the framework but not a subtype of Collection) ⸻ 📍 List Interface A List is an ordered collection that allows duplicate elements. Key features: • Maintains insertion order • Allows duplicates • Supports index-based access Common implementations: ArrayList, LinkedList, Vector, Stack Example: List list = new ArrayList<>(); list.add(“Java”); list.add(“Python”); list.add(“Java”); ⸻ 📍 Set Interface A Set is a collection that does not allow duplicate elements. Key features: • Stores unique elements • Useful when duplicates are not allowed Common implementations: HashSet, LinkedHashSet, TreeSet Example: Set set = new HashSet<>(); set.add(10); set.add(20); set.add(10); ⸻ 📍 Queue Interface A Queue follows the FIFO principle (First In First Out). The first element inserted will be the first element removed. Common implementations: PriorityQueue, ArrayDeque, LinkedList Example: Queue queue = new LinkedList<>(); queue.add(1); queue.add(2); queue.poll(); ⸻ 📍 Map Interface A Map stores data in key-value pairs. Key features: • Keys must be unique • Values can be duplicated • Provides fast data retrieval Common implementations: HashMap, LinkedHashMap, TreeMap, Hashtable Example: Map<Integer, String> map = new HashMap<>(); map.put(1, “Java”); map.put(2, “Python”); ⸻ 💡 Why Collections are Important Collections help developers to: ✔ Handle dynamic data ✔ Reduce code complexity ✔ Improve performance ✔ Use built-in algorithms like sorting and searching ⸻ ✨ Final Thought Mastering the Java Collections Framework is essential for every Java developer because it is widely used in real-world applications and technical interviews. 💬 What Java collection do you use most in your projects? #Java #JavaCollections #Programming #SoftwareDevelopment #Coding #JavaDeveloper
To view or add a comment, sign in
-
💡 Java Internals: How HashMap Actually Works Many developers use HashMap every day, but very few understand what actually happens internally. Here is the complete flow in 5 core concepts: 0️⃣ Implementation of HashMap HashMap is one of the main implementations of the Map interface. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable Key facts: • Stores key–value pairs • Allows 1 null key and multiple null values • Not thread-safe 1️⃣ Internal Structure (Nodes & Buckets) Internally HashMap stores entries as Nodes. Each Node contains four components: • Key → identifier used to retrieve value • Value → actual stored data • Hash → hash value derived from key • Next pointer → link to the next node in case of collision All nodes are stored in an array called the bucket table Node<K,V>[] table Each index in this array is called a bucket 2️⃣ How Data is Stored in HashMap Insertion happens in three steps: Step 1 - Hashing the key hash = key.hashCode() Java improves distribution internally: hash = h^(h>>>16) Step 2 — Calculating the index index = (n - 1)&hash where n = array size. HashMap keeps capacity as a power of 2 to make this fast. Step 3 — Store in bucket If bucket is empty → entry stored directly. If not → collision occurs 3️⃣ Collision Handling A collision happens when multiple keys map to the same bucket index. Example: map.put("apple",50) map.put("orange",80) Both may land in the same bucket. Handling differs by Java version. Before Java 8 Bucket → Linked List Worst-case search: O(n) After Java 8,If bucket size exceeds 8 entries: Linked List → Red Black Tree New complexity:O(log n) This process is called Treeification,happens only when table size ≥ 64 4️⃣ HashMap Resizing (Rehashing) HashMap automatically resizes to maintain efficiency. Default values: Initial Capacity = 16 Load Factor = 0.75 Resize condition: size > capacity × loadFactor Example: 16×0.75 = 12 The 13th insertion triggers resizing 5️⃣ What Happens During Resizing 🌟 Array size doubles 16 → 32 → 64 → 128 🌟 All existing entries are rehash redistributed 🌟 Each entry moves to its new bucket position Performance Summary Average case: get() → O(1) put() → O(1) Worst case: Before Java 8 → O(n) After Java 8 → O(log n) Interesting HashMap Facts 🔹 HashMap capacity is always a power of 2 so (n - 1) & hash can replace slower modulo operations. 🔹 Treeification occurs only when bucket size ≥ 8 AND table size ≥ 64 🔹 During resizing, entries do not require full rehash computation Because the capacity doubles, each entry either: stays in the same index or moves to index + oldCapacity This clever optimization makes resizing much faster than expected. HashMap is a great example of how arrays, hashing, linked lists, and trees combine to build a highly efficient data structure. #Java #HashMap #JavaCollections #SoftwareEngineering #BackendDevelopment #JavaInterview #InterviewPreparation
To view or add a comment, sign in
-
🚀 Day 40 of #100DaysOfCode – Understanding LinkedList in Java Today I learned about LinkedList, another important class in the Java Collection Framework. While ArrayList stores elements in a dynamic array, LinkedList stores elements as nodes connected by links. This makes LinkedList very powerful for operations like frequent insertions and deletions. Here’s a quick LinkedList guide you can learn in 60 seconds 👇 🔹 What is LinkedList? LinkedList is a collection that stores elements in nodes where each node contains: [ Previous | Data | Next ] This structure is called a Doubly Linked List. Each node keeps: • Reference to the previous node • The actual data • Reference to the next node 🔹 Package LinkedList belongs to the package: java.util Import example: import java.util.LinkedList; 🔹 Creating a LinkedList import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { LinkedList<String> fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Mango"); System.out.println(fruits); } } Output [Apple, Banana, Mango] 🔹 Basic Operations in LinkedList 1️⃣ Insertion fruits.add("Orange"); fruits.addFirst("Grapes"); fruits.addLast("Pineapple"); Output [Grapes, Apple, Banana, Mango, Orange, Pineapple] 2️⃣ Access Element System.out.println(fruits.get(2)); Output Banana 3️⃣ Update Element fruits.set(1, "Kiwi"); 4️⃣ Deletion fruits.remove("Apple"); fruits.removeFirst(); fruits.removeLast(); 5️⃣ Size of LinkedList System.out.println(fruits.size()); 🔹 Time Complexity OperationTime ComplexityAdd First / LastO(1)Insert MiddleO(n)Access ElementO(n)Update ElementO(n)Delete FirstO(1)Delete MiddleO(n)🔹 Key Features of LinkedList ✔ Dynamic size ✔ Maintains insertion order ✔ Allows duplicate elements ✔ Allows null values ✔ Efficient insertion and deletion ✔ Implements List and Deque interfaces 🔹 Internal Structure Visualization null <- [Apple] <-> [Banana] <-> [Mango] <-> [Orange] -> null Each element is connected using references instead of indexes. 🔹 When Should We Use LinkedList? LinkedList is useful when: ✔ Frequent insertions ✔ Frequent deletions ✔ Less random access For fast element access, ArrayList is usually better. 💡 Key Takeaway ArrayList is better for fast access, while LinkedList is better for frequent insertions and deletions. Understanding when to use each data structure is an important skill for Java Backend Development and Technical Interviews. 🙏 Grateful to my mentor Suresh Bishnoi from Kodewala Academy for guiding me step by step in my Java Backend Developer journey. #Java #LinkedList #JavaCollections #BackendDevelopment #JavaDeveloper #100DaysOfCode #LearningInPublic
To view or add a comment, sign in
-
-
💡 A Small Java Feature That Can Make Your APIs Much Cleaner: Varargs (...) While working on a file upload utility recently, I wanted a clean way to build file paths dynamically. Something like this: uploads/category/file.png uploads/company/apple/logo.png uploads/company/apple/products/iphone.png At first, I considered writing multiple overloaded methods for each case. But that quickly felt messy. Then I remembered a small Java feature that often goes unnoticed: varargs (...). The Idea Instead of forcing callers to pass arrays or creating multiple methods, Java allows a method to accept a variable number of arguments. Example: public String buildPath(String... segments) { return String.join("/", segments); } Now the method becomes very flexible. buildPath("category", "electronics"); buildPath("company", "apple", "logo.png"); buildPath("company", "apple", "products", "iphone.png"); Under the hood, Java simply converts the arguments into an array. String... segments → String[] segments So inside the method, you can treat segments exactly like a normal array. Why This Feature Is So Useful Using varargs can make APIs cleaner because it removes the need for rigid parameter lists. Instead of something like: buildPath(String folder, String subFolder, String fileName) You can support any depth of path structure with a single method. Where You’ve Already Seen This Many core Java APIs rely on this feature: Arrays.asList("A", "B", "C"); System.out.printf("Name: %s Age: %d", name, age); Both use varargs internally. A Few Rules About Varargs There are some constraints to remember: • The varargs parameter must be the last parameter in the method • Only one varargs parameter is allowed • Java creates an array internally every time the method is called Example: public void log(int level, String... messages) This is valid because the varargs parameter comes last. Final Thought Varargs is a small feature in Java, but it can make utility methods and APIs significantly more flexible and expressive. Sometimes the best improvements in code don’t come from new frameworks or libraries, but from using the language features we already have more effectively. #Java #BackendDevelopment #SoftwareEngineering #CleanCode #Programming
To view or add a comment, sign in
-
-
🚀 Java Collections: Why your "Set" might be broken (and how it's actually a Map) ➡️ If you’ve ever had a "Unique List" that somehow ended up with duplicate data, this post is for you. In Java, the Set Interface is your best friend for handling uniqueness—but only if you know which "flavor" to pick. 🏠 The Analogy: The Guest List ➡️ Imagine you are hosting a high-end tech gala. ✔️HashSet: You have a guest list, but people are standing anywhere they want in the room. It’s messy, but you can find anyone instantly. ✔️LinkedHashSet: Guests are standing in a line based on when they arrived. You know exactly who came first. ✔️TreeSet: You’ve asked everyone to stand in alphabetical order by their last name. It takes a moment to organize, but it’s perfectly sorted. 🛠️ The Developer’s Toolbox (Top Methods) ➡️ To master Sets, you only need these core commands: ✅ add(element): Tries to add an item. Returns false if it’s already there (No duplicates allowed!). 🔎 contains(element): The fastest way to check if someone is "on the list." ❌ remove(element): Kicks an item out of the Set. 📏 size(): Tells you exactly how many unique items you have. 🧠 The "Secret" Internal Mechanism ❓Did you know a Set is actually a Map in disguise? ➡️ Inside a HashSet, Java actually creates a HashMap. When you "add" a value to a Set, Java puts that value as a Key in the Map and attaches a useless "dummy" object as the Value. ➡️ Since a Map cannot have duplicate keys, your Set stays unique. It’s one of the cleverest "hacks" in the Java source code! ⚠️ The hashCode() & equals() Trap ➡️ This is the #1 reason for bugs. If you create a custom User object: 🔸Without overriding these methods: Java looks at the memory address. Two users with the same ID will stay in the Set as duplicates. 🔸 With these methods: Java looks at the data (like ID or Email) to decide if the person is already there. 💡The Golden Rule: If you change how you compare two objects (equals), you must change how Java calculates their "ID" (hashCode). 💡 My Takeaway ✔️ Don't just default to HashSet. 🔸Need a Leaderboard? Use TreeSet. 🔸 Need a Recent Search History? Use LinkedHashSet. 🔸Need Raw Performance? Stick with HashSet. #Java #BackendDevelopment #CodingTips #SoftwareEngineering #JavaCollections #TechSimplified
To view or add a comment, sign in
-
Day 49 – Java 2026: Smart, Stable & Still the Future Difference Between Static and Non-Static Initializers in Java In Java, initializer blocks are used to initialize variables during the class loading or object creation phase. There are two types: Static Initializer Non-Static (Instance) Initializer Understanding their difference helps in learning how JVM memory management and class loading work. 1. Static Initializer A static initializer block is used to initialize static variables of a class. It executes only once when the class is loaded into memory by the ClassLoader. class Example { static int a; static { a = 10; System.out.println("Static initializer executed"); } public static void main(String[] args) { System.out.println(a); } } Key idea: It runs once during class loading. 2. Non-Static Initializer A non-static initializer block is used to initialize instance variables. It executes every time an object is created. class Example { int b; { b = 20; System.out.println("Non-static initializer executed"); } Example() { System.out.println("Constructor executed"); } public static void main(String[] args) { new Example(); new Example(); } } Key idea: It runs every time an object is created. 3. Key Differences FeatureStatic InitializerNon-Static InitializerKeywordUses staticNo keywordExecution timeWhen class loadsWhen object is createdRuns how many timesOnce per classEvery object creationVariables initializedStatic variablesInstance variablesMemory areaMethod AreaHeapExecution orderBefore main()Before constructor4. Execution Flow in JVM When a Java program runs: ClassLoader loads the class Static initializer executes main() method starts Object is created Non-static initializer executes Constructor executes Flow: Program Start ↓ Class Loaded ↓ Static Initializer ↓ Main Method ↓ Object Creation ↓ Non-Static Initializer ↓ Constructor Key Insight Static initializer → class-level initialization (runs once) Non-static initializer → object-level initialization (runs every object creation) Understanding these concepts helps developers clearly see how JVM manages class loading, memory, and object initialization. #Java #JavaDeveloper #JVM #OOP #Programming #BackendDevelopment
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