One Java method. Zero extra objects. Massive memory saving. intern() is the most underused String method in Java. Here's how it saved memory in our fintech system. 👇 In Risk Shield, we process thousands of transaction records per second. Each record carries repeated Strings — currency codes, status flags, country codes like "INR", "USD", "ACTIVE", "PENDING". Without intern() — each was a separate heap object. With intern() — one shared object in the String Pool. Memory dropped by 30% overnight. Here's everything you need to know about intern(): → What it does Moves a String from heap into the String Pool If same value already exists in pool — returns that reference No duplicate String objects in memory → Without intern() String s1 = new String("INR") → new heap object String s2 = new String("INR") → another new heap object s1 == s2 → FALSE (two different references) 2 objects consuming memory for the same value → With intern() String s1 = new String("INR").intern() → goes to pool String s2 = new String("INR").intern() → reuses pool reference s1 == s2 → TRUE (same reference) 1 object shared across entire JVM → Where intern() actually saves memory Repeated currency codes — "INR" "USD" "EUR" Status flags — "ACTIVE" "PENDING" "FAILED" Country codes — "IN" "US" "UK" Any high-frequency repeated String value → When NOT to use intern() Unique Strings like customer IDs or UUIDs intern() on unique values = String Pool bloat More objects in pool = more GC pressure → Performance note intern() has a small CPU cost (pool lookup) Worth it only when same String repeats 100s of times Profile first — optimize second → Java 7+ advantage String Pool is now in Heap (not PermGen) Interned Strings are now garbage collectible Safe to use intern() without OOM risk in older Java versions My rule in fintech systems: If a String value repeats more than 50 times per second → intern() it. Have you ever used intern() in production? What was the use case? Drop it below 👇 Save this — you'll need it in your next Java interview. 🔖 #Java #CoreJava #JavaDeveloper #BackendEngineering #Fintech
Java intern() method for memory saving
More Relevant Posts
-
⏳Day 32 – 1 Minute Java Clarity – Comparable vs Comparator** Both sort. But who controls the sorting logic? ⚡ 📌 Core Difference: Comparable = object sorts itself (natural order). Comparator = external class defines custom sort logic. 📌 Code Comparison: import java.util.*; // Comparable – natural order (by age) class Student implements Comparable<Student> { String name; int age; Student(String name, int age) { this.name = name; this.age = age; } public int compareTo(Student other) { return this.age - other.age; // sort by age ascending } public String toString() { return name + "(" + age + ")"; } } // Comparator – custom order (by name) class NameComparator implements Comparator<Student> { public int compare(Student a, Student b) { return a.name.compareTo(b.name); // sort by name } } public class SortingDemo { public static void main(String[] args) { List<Student> students = Arrays.asList( new Student("Charlie", 22), new Student("Alice", 20), new Student("Bob", 21) ); Collections.sort(students); // Comparable → by age System.out.println(students); // [Alice(20), Bob(21), Charlie(22)] students.sort(new NameComparator()); // Comparator → by name System.out.println(students); // [Alice(20), Bob(21), Charlie(22)] // Java 8 Lambda Comparator students.sort((a, b) -> b.age - a.age); // sort by age descending System.out.println(students); } } 📌 Head-to-Head Comparison: | Feature | Comparable | Comparator | |---|---|---| | Package | java.lang | java.util | | Method | compareTo() | compare() | | Sort logic location | Inside the class | Outside the class | | Multiple sort orders | ❌ One only | ✅ Multiple | | Modifies class | ✅ Yes | ❌ No | 💡 Real-time Example: 👨🎓 Student Leaderboard : Comparable → Default sort by marks (fixed rule) Comparator → Sort by name, age, or rank depending on view ⚠️ Interview Trap: Can you use both Comparable and Comparator together? 👉 Yes! Comparable sets the default order. 👉 Comparator overrides it when passed explicitly. 📌 Pro Tip: // Java 8 Comparator chaining: students.sort( Comparator.comparing((Student s) -> s.age) .thenComparing(s -> s.name) ); // sort by age, then by name ✅ 💡 Quick Summary: ✔ Comparable → natural sort, modifies the class ✔ Comparator → custom sort, external, flexible ✔ Comparable uses compareTo(), Comparator uses compare() ✔ Use Comparator when you can't modify the class ✔ Java 8+ → prefer lambda Comparators ✅ 🔹 Next Topic → Java 8 Streams Introduction Did you know you can chain multiple Comparators in Java 8 with thenComparing()? Drop 🔥 if this was new to you! #Java #Comparable #Comparator #Sorting #JavaCollections #CoreJava #1MinuteJavaClarity #JavaDeveloper #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Java Wrapper Classes: Hidden Behaviors That Trip Up Even Senior Developers Most developers know wrapper classes. Very few understand what happens under the hood — and that’s exactly where top companies separate candidates. Here’s a deep dive into the concepts that actually matter 1. Integer Caching Integer a = 4010; Integer b = 4010; System.out.println(a == b); // false Integer c = 127; Integer d = 127; System.out.println(c == d); // true Q.Why? Java caches Integer values in the range -128 to 127. Inside range → same object (cached) Outside range → new object (heap) 💡 Pro Insight: You can even extend this range using: -XX:AutoBoxCacheMax=<size> 2. == vs .equals() — Silent Bug Generator System.out.println(a == b); // false → reference comparison System.out.println(a.equals(b)); // true → value comparison Using == with wrapper objects is one of the most common production bugs. Rule: == → checks memory reference .equals() → checks actual value 3. hashCode() vs identityHashCode() System.out.println(a.hashCode()); System.out.println(System.identityHashCode(a)); Two objects can have: Same value → same hashCode() Different memory → different identityHashCode() 4. Silent Overflow in Primitive Conversion Integer a = 4010; byte k = a.byteValue(); // -86 What actually happens: byte range = -128 to 127 4010 % 256 = 170 170 interpreted as signed → -86 No error. No warning. This is how real-world bugs sneak into systems. 5. Powerful Utility Methods (Underrated) Integer.toBinaryString(4010); Integer.toHexString(4010); Integer.bitCount(4010); Integer.numberOfLeadingZeros(4010); Useful in: Bit manipulation Competitive programming Low-level optimization 6. Character & Boolean — Also Cached Boolean b1 = true; Boolean b2 = true; System.out.println(b1 == b2); // true Boolean → fully cached Character → cached in ASCII range 7. Character Utilities = Clean Code Character.isLetter('a'); Character.isDigit('3'); Character.isWhitespace('\t'); Character.toUpperCase('a'); The Big Picture Wrapper classes are NOT just primitives with methods. They reveal how Java handles: Memory optimization Object identity Autoboxing behavior Performance trade-offs A big thanks to my mentors Syed Zabi Ulla, peers, and the amazing developer community Oracle for continuously pushing me to go beyond basics and truly understand concepts at a deeper level. #Java #JVM #CoreJava #CodingInterview #FAANG #SoftwareEngineering #BackendDevelopment #ProgrammingTips
To view or add a comment, sign in
-
-
Java Program: Write a program to check given strings are Anagrams or not. 1. The Core Logic: "Sort and Compare." The fundamental idea behind this approach is that if two strings are anagrams, they must contain the exact same characters with the exact same frequencies. By sorting the characters of both strings alphabetically, any differences in the original "arrangement" are removed. If the sorted results are identical, the strings are anagrams. 2. Step-by-Step Breakdown s1.toCharArray(): Strings in Java are immutable objects. To manipulate or sort the individual characters, we first convert the string into a primitive char[] array. "listen" becomes ['l', 'i', 's', 't', 'e', 'n'] Arrays.sort(char1): This method uses a Dual-Pivot Quicksort algorithm. It rearranges the characters in the array into ascending order based on their Unicode values. ['l', 'i', 's', 't', 'e', 'n'] becomes ['e', 'i', 'l', 'n', 's', 't'] ['s', 'i', 'l', 'e', 'n', 't'] also becomes ['e', 'i', 'l', 'n', 's', 't'] Arrays.equals(char1, char2): This is a utility method that checks two things: Do the arrays have the same length? Does every element at index i in the first array match the element at index i in the second array? If both conditions are met, it returns true. 3. Missing Requirements for Production While this snippet works for the hardcoded values, a robust version of this code should include two additional checks: Length Check: Before sorting, you should check if s1.length() == s2.length(). If the lengths are different, they cannot be anagrams, and you can return false immediately without wasting time sorting. Imports: To make this code compile, you must import the java.util.Arrays utility at the top of your file: import java.util.Arrays;
To view or add a comment, sign in
-
-
🚀 Java Revision Journey – Day 32 Today I revised LinkedHashMap in Java, an important Map implementation that maintains insertion order along with key-value storage. 📝 LinkedHashMap Overview LinkedHashMap is a class in java.util that implements the Map interface and extends HashMap. It stores data in key → value pairs while maintaining the order of insertion. Key Characteristics: • Stores unique keys and duplicate values allowed • Maintains insertion order • Allows one null key and multiple null values • Extends HashMap → inherits hashing benefits • Not thread-safe (use Collections.synchronizedMap() if needed) 💻 Declaration public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> • K → Key type • V → Value type ⚙️ Example LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); map.put("A", 1); map.put("B", 2); map.put("A", 3); // Updates value, order unchanged System.out.println(map); // Output: {A=3, B=2} ⚙️ Internal Working (Important) • Uses HashMap (hashing) for fast operations • Maintains a doubly linked list of entries • Each node contains: → Key → Value → Next (next node reference) → Previous (previous node reference) This is why it preserves insertion order 🏗️ Constructors Default LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); With Capacity + Load Factor LinkedHashMap<String, Integer> map = new LinkedHashMap<>(20, 0.75f); From Existing Map LinkedHashMap<String, Integer> map = new LinkedHashMap<>(existingMap); 🔑 Basic Operations Adding Elements: • put(key, value) → Adds while maintaining order Updating Elements: • put(key, newValue) → Replaces value (order unchanged) Removing Elements: • remove(key) → Deletes mapping 🔁 Iteration for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } 💡 Key Insight LinkedHashMap is widely used when you need: • Maintain insertion order + fast access (O(1)) • Predictable iteration order (unlike HashMap) • Implementing LRU cache (using access order mode) • Storing configurations or logs where order matters Understanding LinkedHashMap helps in scenarios where order + performance both are important, making it very useful in real-world backend systems. Day 32 done ✅ — consistency is becoming your strength 💪🔥 #Java #JavaLearning #LinkedHashMap #DataStructures #JavaDeveloper #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
Java Is Not As Simple As We Think. We’re taught that Java is predictable and straightforward. But does it always behave the way we expect? Here are 3 subtle behaviors that might surprise you. Q1: Which method gets called? You have a method overloaded with int and long. What happens when you pass a literal? public void print(int i) { System.out.println("int"); } public void print(long l) { System.out.println("long"); } print(10); It prints "int". But what if you comment out the int version? You might expect an error, but Java automatically "widens" the int to a long. However, if you change them to Integer and Long (objects), Java will not automatically widen them. The rules for primitives vs. objects are completely different. Q2: Is 0.1 + 0.2 really 0.3? In a financial application, you might try this: double a = 0.1; double b = 0.2; System.out.println(a + b == 0.3); // true or false? It prints false. In fact, it prints 0.30000000000000004. The Reason: Java (and most languages) uses IEEE 754 floating-point math, which cannot represent certain decimals precisely in binary. This is why for any precise calculation, BigDecimal is the only safe choice. Q3: Can a static variable "see" the future? Look at the order of initialization here: public class Mystery { public static int X = Y + 1; public static int Y = 10; public static void main(String[] args) { System.out.println(X); // 11 or 1? } } It prints 1. The Reason: Java initializes static variables in the order they appear. When X is calculated, Y hasn't been assigned 10 yet, so it uses its default value of 0. A simple reordering of lines changes your entire business logic. The takeaway: Java is not a simple language. Even professionals with years of experience get tripped up by its subtle behaviors and exceptions to the rules. The language rewards curiosity and continuous learning — no matter how senior you are. Keep revisiting the fundamentals. They have more depth than you remember. #Java #SoftwareEngineering #Coding #JVM #ProgrammingTips
To view or add a comment, sign in
-
Why Creating Too Many Threads in Java Degrades Performance (And How ExecutorService Solves It) While learning multithreading in Java, I initially assumed that increasing the number of threads would improve performance. However, practical analysis shows that excessive thread creation leads to the opposite effect. Here are the key insights with real-world numbers: CPU Parallelism is Limited Consider a typical system: 4 to 8 CPU cores Even if you create: 1000 threads Only: 4–8 threads can execute simultaneously The remaining threads are scheduled and kept waiting. Example: If each task takes 2 seconds: Sequential (1 thread, 1000 tasks) → ~2000 seconds With 8 cores → theoretical minimum ≈ 250 seconds Context Switching Overhead The operating system switches between threads rapidly. Each switch ≈ 1–10 microseconds With hundreds of threads → thousands of switches per second Result: CPU spends more time switching than doing useful work. Memory Consumption Per Thread Each thread has its own stack: ~512 KB to 1 MB per thread Example: 1000 threads → ~500 MB to 1 GB memory usage This can lead to: OutOfMemoryError: unable to create new native thread System Instability Under Load Too many threads can cause: High garbage collection pressure Scheduling delays Application slowdown or crash How Java Solves This: ExecutorService (Thread Pools) Instead of creating a new thread for every task, Java provides the Executor framework. What ExecutorService does: Fixed Number of Threads You define a limit (e.g., 10 threads), and only those threads are created. Task Queue Submitted tasks are placed in a queue. Example: 1000 tasks → 10 running, 990 waiting. Worker Threads Each thread picks a task, executes it, and then picks the next one. Threads are reused, not recreated. Reduced Context Switching Fewer threads → fewer switches → better CPU efficiency. Controlled Memory Usage Limited threads → stable memory usage. Example: ExecutorService executor = Executors.newFixedThreadPool(10); for (int i = 0; i < 1000; i++) { executor.submit(() -> fetchPrice()); } What happens: 10 threads run tasks Remaining tasks wait in queue Execution happens in batches Key Insight Threads are not free resources. They are: Memory-intensive CPU-scheduled Expensive to manage ExecutorService solves this by: Limiting threads Reusing them Managing tasks efficiently Conceptual Shift From: “How many threads can I create?” To: “How can I manage concurrency efficiently?” This understanding is fundamental for building scalable backend systems in Java. #Java #Multithreading #ExecutorService #Concurrency #BackendDevelopment #SystemDesign
To view or add a comment, sign in
-
Day 15 Java Practice: Find Product with Maximum Total Quantity While practicing Java, I worked on a small problem involving strings, arrays, and maps. 👉 Given product data with quantity like: {"xyz 19","abc 30","xyz 21","abc 23"} The goal was to: Sum the quantities for the same product Find which product has the maximum total quantity 🧠 Approach: Split each string to get product name and quantity Store and add quantities using a HashMap Traverse the map to find the maximum value ============================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main { public static void main(String[] args) { String a []={"xyz 19","abc 30","xyz 21","abc 23"}; Map<String,Integer>hmap=new HashMap<String,Integer>(); for(String s : a) { String data []=s.split(" "); String name=data[0]; int value=Integer.parseInt(data[1]); hmap.put(name,hmap.getOrDefault(name,0)+value); } int max=0; String result=""; for(Map.Entry<String,Integer>entry:hmap.entrySet()) { if(entry.getValue()>max) { max=entry.getValue(); result=entry.getKey(); } } System.out.println(result+" "+max); } } Output: abc 53 #JavaDeveloper #AutomationEngineer #CodingPractice #Collections #ProblemSolving #Learning
To view or add a comment, sign in
-
-
In Java, the transient keyword is a variable modifier used to exclude specific fields of an object from the serialization process. When an object is serialized (converted into a byte stream for storage or network transmission), any field marked as transient is ignored and not saved. Key Characteristics Purpose: It prevents sensitive or unnecessary data from being persisted. Deserialization Behavior: When the object is recreated (deserialized), transient fields are initialized with their default values (e.g., null for objects, 0 for integers, false for booleans) rather than their original values. Scope: It can only be applied to instance variables (fields). It cannot be used with methods, classes, or local variables. Common Use Cases Security: To protect sensitive information like passwords, PINs, or encryption keys that should not be stored in a file or sent over a network. Derived Data: For fields whose values can be easily recalculated from other data in the class (e.g., a fullName field derived from firstName and lastName). Non-Serializable Objects: To exclude fields that reference objects that do not implement the Serializable interface (e.g., database connections or file streams), which would otherwise cause a NotSerializableException. Performance: To reduce the size of the serialized byte stream by skipping temporary or large cache data. Behavior with Other Keywords static: Using transient with static is redundant. Static variables belong to the class, not the instance, and are naturally ignored by the default serialization process. final: The effect varies. If a final variable is initialized with a constant expression at declaration, the JVM may still serialize it despite the transient keyword. However, if it is initialized in a constructor, it will typically be treated as transient and reset to its default value upon deserialization. Related Annotations In modern Java frameworks, you may encounter similar functionality via annotations: @Transient (JPA/Hibernate): Tells the persistence provider not to store a field in the database. @JsonIgnore (Jackson): Prevents a field from being included when converting an object to JSON format.
To view or add a comment, sign in
-
🚀 Today I dived deep into Exception Handling in Java! Have you ever seen a "software not responding" popup or had an app suddenly crash?,. That is often because of an unhandled exception. What is an Exception? In Java, an exception is an unusual event that occurs during the runtime (execution) of a program,,. It is usually triggered by faulty user input—like trying to divide a number by zero or providing a string when a number is expected,,. If these aren't handled, they lead to abrupt termination, which ruins the user experience and can cause significant losses for a company,. How it works behind the scenes: When a problem occurs, the JVM automatically creates an Exception Object,. This object contains the "What" (type of error), "Where" (line number), and "Why" (the reason),. If we don't catch it, the Default Exception Handler prints the error and stops the program immediately,. The Solution: Try-Catch Blocks To ensure normal termination, we follow three simple steps: 1.Identify risky lines of code where a problem might occur,. 2.Place that code inside a try block,. 3.Write a catch block to intercept the exception object and handle it gracefully,. Pro Tip: The Order of Catch Blocks Matters! ⚠️ You can have multiple catch blocks for different errors (like ArithmeticException or ArrayIndexOutOfBoundsException),. However, you must always put specific exceptions first and the general Exception class last,. If you put the general one first, the specific ones become unreachable code because the general class has the capability to catch everything. Code Example: import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Connection established."); try { // Step 1 & 2: Identify and wrap risky code, System.out.print("Enter numerator: "); int a = scan.nextInt(); System.out.print("Enter denominator: "); int b = scan.nextInt(); int result = a / b; // Risky line: ArithmeticException if b=0 System.out.println("Result: " + result); } catch (ArithmeticException e) { // Step 3: Handle specific exception, System.out.println("Error: Please enter a non-zero denominator."); } catch (Exception e) { // General catch-all for other unexpected issues System.out.println("Some technical problem occurred."); } System.out.println("Connection terminated.");, } } Looking forward to exploring rethrowing and ducking exceptions tomorrow!. #Java #Coding #BackendDevelopment #ExceptionHandling #LearningJourney #SoftwareEngineering #TapAcademy
To view or add a comment, sign in
-
-
🚀 Java’s volatile Keyword — The Most Misunderstood Concept (Explained Like Real Life) If you’ve worked with multithreading, you’ve probably seen volatile… and thought: 👉 “It makes things thread-safe, right?” ❌ Not exactly. Let’s break it down in a way that actually sticks 👇 🏠 Real-Life Example: WhatsApp Status Problem Imagine: You update your WhatsApp status. But your friend still sees the old status for a while 😅 Why? 👉 Because their app is showing a cached version, not the latest one 🧠 Same Problem Happens in Java Threads Each thread has its own working memory (CPU cache) So if one thread updates a variable: 👉 Other threads may still see the old value 💥 This is called a visibility problem ⚡ What volatile Actually Does When you mark a variable as volatile: volatile boolean isRunning = true; 👉 You’re telling JVM: “Always read/write this variable directly from main memory” 📌 So What Problems Does It Solve? ✔️ Guarantees visibility ✔️ Prevents threads from using stale values ⚠️ But Here’s the Catch (Important for Interviews) 👉 volatile does NOT guarantee: ❌ Atomicity ❌ Thread safety for complex operations 💥 Classic Mistake Example java volatile int count = 0; count++; // Not safe ❌ Why? 👉 count++ is NOT a single operation It’s actually: 1️⃣ Read 2️⃣ Increment 3️⃣ Write Two threads can still mess this up 🧠 What Else Does volatile Do? (Deep Concept) 👉 It prevents instruction reordering Sounds complex? Let’s simplify 👇 🍳 Real-Life Analogy: Cooking Order Imagine making tea: 1️⃣ Boil water 2️⃣ Add tea leaves Now imagine someone reorders it: 👉 Add tea leaves first, then boil 😅 Program still runs… but result is wrong ⚙️ Same Happens in CPU Optimizations To improve performance, JVM/CPU may reorder instructions 👉 volatile prevents this for that variable 🔥 Most Important Use Case: Stop Thread Pattern volatile boolean running = true; while(running) { // do work } Another thread can safely do: java running = false; 👉 Without volatile, loop might NEVER stop 🧠 Interview Questions (Answered Simply) 👉 What problem does volatile solve? → Visibility + Ordering 👉 Is volatile thread-safe? → ❌ No (only for simple reads/writes) 👉 Difference between volatile & synchronized? | volatile | synchronized | |----------|-------------| | Visibility only | Visibility + Atomicity | | No locking | Uses locking | | Faster | Slower | 🎯 When Should You Use volatile? ✔️ Status flags (true/false) ✔️ Configuration updates ✔️ One writer, multiple readers ❌ Avoid for: - Counters - Banking logic - Complex shared state #Java #Multithreading #Volatile #Concurrency #BackendDevelopment #InterviewPrep #SoftwareEngineer
To view or add a comment, sign in
Explore related topics
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