I revised one of the most important concepts in Java — String handling. At first glance, Strings look simple. But behind the scenes, Java manages them using: 🔹 Heap Memory 🔹 String Constant Pool (SCP) 🔹 Immutability concept Let’s break it down 👇 🧠 1️⃣ String Memory (Heap vs SCP) Java 👇 String s1 = "JAVA"; String s2 = "JAVA"; String s3 = new String("JAVA"); ✅ s1 and s2 point to the same object in String Constant Pool ❌ s3 creates a new object in Heap memory 👉 Important: == compares references (memory address) equals() compares values 🔍 2️⃣ String Comparison ✔ equals() Compares values (case-sensitive) Java 👇 s1.equals(s2); ✔ equalsIgnoreCase() Ignores uppercase/lowercase ✔ compareTo() Lexicographically compares two strings Returns 0 → Equal Negative → First string is smaller Positive → First string is greater Example: Java 👇 "SACHIN".compareTo("SAURAV"); 🔗 3️⃣ String Concatenation Java 👇 String s1 = "JAVA"; String s2 = "PYTHON"; String s3 = s1 + s2; String s4 = s1.concat(s2); ⚠ Important: Strings are immutable in Java. Every concatenation creates a new object in heap. 🛠 4️⃣ Important String Methods length() charAt() indexOf() substring() toLowerCase() toUpperCase() contains() startsWith() endsWith() split() toCharArray() 💡 Real-Time Example (User Login System) Imagine building a login system: Java 👇 String dbPassword = "Admin@123"; String userInput = "admin@123"; if (dbPassword.equals(userInput)) { System.out.println("Login Success"); } If we use == instead of equals() ❌ Login may fail even if values look same. 👉 This is why understanding String comparison is very important in real projects. 🎯 Key Takeaways ✔ Strings are immutable ✔ == checks reference, equals() checks value ✔ compareTo() is used for sorting ✔ Concatenation creates new objects ✔ SCP improves memory efficiency Mastering Strings helps in: Authentication systems Form validation Data processing APIs & backend development Competitive programming TAP Academy #Java #String #CoreJava #Programming #SoftwareDevelopment #CodingJourney #Learning
Mastering Java Strings: Heap Memory, SCP, and Comparison
More Relevant Posts
-
🔥 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
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
-
-
🚀 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
-
-
Hi, connections👋 📌 𝐞𝐪𝐮𝐚𝐥𝐬() & 𝐡𝐚𝐬𝐡𝐂𝐨𝐝𝐞() - A Must-Know Topic for Every Java Interview If you’re a Java developer, this is one topic you cannot afford to ignore. 🔥 Understanding == 𝐯𝐬 .𝐞𝐪𝐮𝐚𝐥𝐬() in Java so many developers struggle with unexpected bugs because they treated == and .equals() as the same thing. They aren't. ✅ 𝐂𝐚𝐬𝐞 𝟏: 𝐓𝐡𝐞 𝐈𝐧𝐭𝐞𝐠𝐞𝐫 𝐂𝐚𝐜𝐡𝐞 𝐓𝐫𝐚𝐩 Integer i1 = 120; Integer i2 = 120; System.out.println(i1 == i2); // true System.out.println(i1.equals(i2)); // true 🔎 𝐖𝐡𝐲? Java caches Integer objects from -128 to 127. Since 120 is within this range, both references point to the exact same object in memory. ⚠️ Warning: If you use 128, == will return false because a new object is created! ✅𝐂𝐚𝐬𝐞 𝟐: 𝐒𝐭𝐫𝐢𝐧𝐠 𝐋𝐢𝐭𝐞𝐫𝐚𝐥𝐬 & 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥. String str1 = "abc"; String str2 = "abc"; System.out.println(str1 == str2); // true System.out.println(str1.equals(str2)); // true 🔎 𝐖𝐡𝐲? Identical String literals are stored in the String Constant Pool. Java reuses the same memory address to optimize performance. Same address = true for ==. ✅ 𝐂𝐚𝐬𝐞 𝟑: 𝐓𝐡𝐞 𝐧𝐞𝐰 𝐊𝐞𝐲𝐰𝐨𝐫𝐝 𝐃𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐜𝐞(𝐧𝐞𝐰 𝐒𝐭𝐫𝐢𝐧𝐠()) String s1 = new String("abc"); String s2 = new String("abc"); System.out.println(s1 == s2); // false System.out.println(s1.equals(s2)); // true 🔎 𝐖𝐡𝐲? The new keyword forces Java to create a unique object in the Heap memory. == checks the Address (which is different). .equals() checks the Content (which is "abc"). 🔥 𝐈𝐦𝐩𝐨𝐫𝐭𝐚𝐧𝐭 Rule: String.equals() is overridden inside String class. Internally it invokes! -> First checks reference -> Then checks length -> Then compares each character one by one -> If all characters are equal -> returns true ✅ 𝐂𝐚𝐬𝐞 𝟒: 𝐂𝐮𝐬𝐭𝐨𝐦 𝐂𝐥𝐚𝐬𝐬𝐞𝐬 (𝐓𝐡𝐞 "𝐇𝐢𝐝𝐝𝐞𝐧" 𝐅𝐚𝐢𝐥) class Employee { int id; String name; public Employee(int id, String name){ this.id = id; this.name = name; } } 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞 𝐞𝟏 = 𝐧𝐞𝐰 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞(𝟏𝟎𝟏, "𝐃𝐞𝐯"); 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞 𝐞𝟐 = 𝐧𝐞𝐰 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞(𝟏𝟎𝟏, "𝐃𝐞𝐯"); 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧(𝐞𝟏 == 𝐞𝟐); // false 👈 🔎𝐖𝐡𝐲? Deferent memory location then returns false. 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧(𝐞𝟏.𝐞𝐪𝐮𝐚𝐥𝐬(𝐞𝟐)); // false 👈 🔎 𝐖𝐡𝐲? We did NOT override equals() inside Employee, it automatically invokes the equals () method from the Object class 👇Object class Contained equals Method! public boolean equals(Object obj) { return (this==obj); //e1==e2 so return false } 🚀 What's Next? Understanding equality is only half the battle. In my next post, I’ll explain: ✔ How to properly override equals() ✔ Why you must override hashCode() at the same time ✔ How HashMap breaks if you get this wrong 📌 Save this post if you're prepping for Java interviews! #Java #CoreJava #SoftwareDevelopment #Programming #TechTips #JavaDeveloper #CodingLife
To view or add a comment, sign in
-
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
-
-
💡 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
-
🚀 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 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 8 Features Day 4 What is Bi Functional Interfaces in Java? 1️⃣ BiPredicate<T, U> 👉 Takes two input arguments 👉 Returns a boolean value Example Code: import java.util.function.BiPredicate; class Main { public static void main(String[] args) { BiPredicate<Float, Float> isValidWeight = (height, weight) -> weight == height - 100; if (isValidWeight.test(174.5f, 74.5f)) { System.out.println("Congrats! You are in correct weight."); } else { System.out.println("Sorry! You are not in correct weight."); } } } 👉 Use case: Validations involving two values. 2️⃣ BiFunction<T, U, R> 👉 Takes two input arguments 👉 Returns any type (R) Example Code: import java.util.function.BiFunction; import java.util.Base64; class Main { public static void main(String[] args) { BiFunction<Long, String, String> tempPassword = (phoneNumber, email) -> Base64.getEncoder() .encodeToString((email + phoneNumber).getBytes()); System.out.println( tempPassword.apply(9080555678L, "hariv6@gmail") ); } } 👉 Use case: Transforming two inputs into one result ✅ 3️⃣ BiConsumer<T, U> 👉 Takes two input arguments 👉 Returns nothing (void) 👉 Only consumes data Example Code: import java.util.function.BiConsumer; class Main { public static void main(String[] args) { BiConsumer<Float, Double> bonusCalculation = (experience, salary) -> { if (experience < 5 && salary <= 100000.0) { System.out.println("Your bonus is 20%"); } else { System.out.println("Your bonus is 10%"); } }; bonusCalculation.accept(4.3f, 70000.0); } } 👉 Use case: Performing operations like logging, printing, updating records. ❓ Why is there no BiSupplier? Because: 👉 Supplier<T> does not take any input. 👉 It only supplies (returns) a value. 👉 So logically, BiSupplier is not required. ♻️Repost so others can learn and grow together. 🔔 Follow Hariprasath V for daily Java, DSA, and System Design,Springboot,Microservices,Devops,Full Stack resources. ================================================ #java8Features #java8 #LambdaExpressions #Java #SystemDesign #DataStructures #Algorithms #JavaDeveloper #DSA #CodingInterview #TechInterview #SystemDesignInterview #DSAChallenge #60DaysOfDSA #ProblemSolving #CodingJourney #Consistency #LearnByDoing #DataStructures #Algorithms #InterviewPrep #KeepCoding #Productivity #Focus #DreamBig #BackendDevelopment #SoftwareEngineering #JavaInterview #LeetCode #InterviewPrep #DataStructureAndAlgorithms #DesignPatterns #LowLevelDesign #Multithreading #SOLIDPrinciples #RESTAPI #BackendEngineer #CodeInterview #interviewtips #interviewexperience
To view or add a comment, sign in
-
-
Two threads. One shared resource. What could possibly go wrong? In Java, when multiple threads try to access or modify the same resource at the same time, the result can be data inconsistency. This situation is known as a race condition, and it is one of the most common problems in multithreaded systems. To control this behavior, Java provides the "synchronized" keyword. The synchronized keyword ensures that only one thread can execute a critical section of code at a time. It works using a mechanism called locks. Where can we apply synchronized? The synchronized keyword can be applied in two places: • Synchronized Method • Synchronized Block I. Synchronized Method When a method is declared as synchronized, the entire method becomes a critical section. Example concept: public synchronized void display() { // critical section } Before executing this method, a thread must acquire the lock of the object. If another thread already holds that lock, the remaining threads must wait until the lock is released. Once execution finishes, the JVM automatically releases the lock. However, synchronizing the entire method is not always efficient. Sometimes only a small portion of the method needs protection. Synchronizing the whole method can increase waiting time for other threads, which affects performance. II. Synchronized Block To avoid unnecessary waiting, Java allows us to synchronize only a specific part of the code. Example concept: synchronized(object) { // critical section } Here, only the code inside the block is synchronized. III. Advantages of synchronized blocks: • Improves performance • Reduces thread waiting time • Allows better control over critical sections Note: The lock mechanism in Java works only with objects and classes, not with primitive data types. This means we cannot pass primitive values like: int, float, double, boolean to a synchronized block. Locks must always be associated with an object reference. In Interview, we may asked questions on: 1. Race Condition When multiple threads operate simultaneously on the same object and cause data inconsistency, it is called a race condition. 2. Object-Level Lock Every object in Java has a unique lock. When a thread executes a synchronized instance method, it must acquire the lock of that object. Different objects → different locks → threads can run simultaneously. 3. Class-Level Lock Every class in Java also has a single class-level lock. This lock is used when a thread executes a static synchronized method. Before executing the method, the thread must acquire the class lock. 4. Can a thread acquire multiple locks simultaneously? Yes. A thread can hold multiple locks at the same time, as long as they belong to different objects. #Day10 #Java #Multithreading #SoftwareEngineering
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