𝐖𝐡𝐲 𝐉𝐚𝐯𝐚 𝐝𝐨𝐞𝐬𝐧'𝐭 "𝐝𝐨𝐮𝐛𝐥𝐞-𝐬𝐩𝐞𝐧𝐝" 𝐲𝐨𝐮𝐫 𝐦𝐞𝐦𝐨𝐫𝐲 🧠 In my last post, we talked about String Immutability. Today, let’s look under the hood at the 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥 (SCP). When you create a String in Java, the JVM is very stingy with your RAM. It has two ways to handle things: 1. 𝐓𝐡𝐞 "𝐍𝐞𝐰" 𝐖𝐚𝐲 (𝐄𝐱𝐩𝐥𝐢𝐜𝐢𝐭 𝐎𝐛𝐣𝐞𝐜𝐭 𝐂𝐫𝐞𝐚𝐭𝐢𝐨𝐧) 👉 String name = new String("Arpit"); This creates a brand new object in the Heap Memory, even if "Arpit" already exists elsewhere. It’s like buying a new book when there’s already a copy on the shelf. 2. 𝐓𝐡𝐞 𝐋𝐢𝐭𝐞𝐫𝐚𝐥 𝐖𝐚𝐲 (𝐓𝐡𝐞 𝐒𝐦𝐚𝐫𝐭 𝐖𝐚𝐲) 👉 String platform = "LinkedIn"; This tells the JVM: "Check the 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥 first." If "LinkedIn" is already there, your variable just points to it. If it’s not, it creates it. Result: 100 variables can point to the same "LinkedIn" string, saving massive amounts of memory. 𝐓𝐡𝐞 "𝐈𝐧𝐭𝐞𝐫𝐧" 𝐏𝐫𝐨-𝐓𝐢𝐩 💡 What if you created a string with new but want to move it into the pool to save space? Enter the .intern() method. As you can see in the 𝐝𝐢𝐚𝐠𝐫𝐚𝐦 (Credit: Scaler): - str1 and str3 point to the same "Java" in the pool. - str4 sits alone in the Heap. - str6 uses .intern() to jump from the Heap into the Pool! 𝐖𝐚𝐢𝐭, 𝐰𝐡𝐚𝐭 𝐚𝐛𝐨𝐮𝐭 𝐜𝐨𝐧𝐜𝐚𝐭𝐞𝐧𝐚𝐭𝐢𝐨𝐧? When you add two strings, Java creates a new string in the pool rather than changing the old one. This keeps your data safe and predictable. Did you know about this before? Let me know in the comments! 👇💭 #java #SoftwareEngineering #jvm #LearningInPublic
Java String Interning: Memory Efficiency and Pooling
More Relevant Posts
-
🌙Shallow Copy (clone / Arrays.copyOf) of an array ☐☐☐ Outer array becomes new ✅ Inner arrays are still SAME references ❌ So if you change inside value → both change. ✅ original and shallow point to different outer arrays (different addresses) ❌ but original[i] and shallow[i] point to the same inner row arrays (same addresses) In one line:✅ “Two variables point to different outer arrays, but the rows inside are pointing to the same memory.” ✅ in shallow copy, outer array is new, but the rows are shared, so changing a cell changes both. ❌If you assign a new 1D row to the copied 2D array, only that row becomes different in the copy; the other rows still stay shared with original. A 2D array in Java is actually: ✅ “array of references to 1D arrays” So when you clone the outer array, Java copies: the list of references (outer) not the actual row arrays (inner) Cell change: shallow[0][0] = 5 ➡️ You edited the same shared row → both see it ✅ Row replacement: shallow[0] = new int[]{...} ➡️ You changed only which row reference shallow points to → original remains same ✅ ✅ toString() prints only the memory address of inner arrays (useless). ✅ Arrays.deepToString() prints the actual values inside all rows (proper output). GitHub Link: https://lnkd.in/g2j8X_-z 🔖Frontlines EduTech (FLM) #Java #Arrays #DeepCopy #2DArray #JavaProgramming #Coding #DSA #ProgrammingBasics #LearnJava #CodeSnippet
To view or add a comment, sign in
-
-
#Day 63: LeetCode 1984 - Minimum Difference Between Highest and Lowest of K Scores Code:- import java.util.Arrays; class Solution { public int minimumDifference(int[] nums, int k) { // Step 1: Handle the edge case where only one score is picked if (k == 1) return 0; // Step 2: Sort the scores to bring close values together Arrays.sort(nums); int minDiff = Integer.MAX_VALUE; // Step 3: Slide a window of size k through the array // The window starts at 'i' and ends at 'i + k - 1' for (int i = 0; i <= nums.length - k; i++) { int currentDiff = nums[i + k - 1] - nums[i]; // Step 4: Update the global minimum difference if (currentDiff < minDiff) { minDiff = currentDiff; } } return minDiff; } } #The Strategy: ->Sort the scores to align them by magnitude. ->Apply a Sliding Window of size $k$ to look at every possible 'cluster' of scores. ->Calculate the spread (Max - Min) for each cluster and capture the minimum. #100DaysOfCode #Java #SoftwareEngineering #Algorithms #LeetCode #SDE #ProblemSolving #SlidingWindow"
To view or add a comment, sign in
-
-
Why did Java just skip my input? (The sc.nextLine() Trap) I was building a simple CLI tool today and hit a weird bug. I asked the user for their Age, then their Name. But as soon as I typed the age and hit Enter, the program finished. 𝐈𝐭 𝐝𝐢𝐝𝐧'𝐭 𝐞𝐯𝐞𝐧 𝐰𝐚𝐢𝐭 𝐟𝐨𝐫 𝐦𝐞 𝐭𝐨 𝐭𝐲𝐩𝐞 𝐦𝐲 𝐧𝐚𝐦𝐞! 𝐓𝐡𝐞 𝐌𝐲𝐬𝐭𝐞𝐫𝐲: I was using sc.nextInt() followed by sc.nextLine(). ▶️sc is the Scanner class object. 𝐓𝐡𝐞 𝐒𝐜𝐢𝐞𝐧𝐜𝐞: When you type 25 and hit Enter, nextInt() only reads the 25. It leaves the "𝐄𝐧𝐭𝐞𝐫" (𝐭𝐡𝐞 \𝐧 𝐧𝐞𝐰𝐥𝐢𝐧𝐞 𝐜𝐡𝐚𝐫𝐚𝐜𝐭𝐞𝐫) sitting there in the buffer. When the code hits the next nextLine(), it sees that leftover "Enter" and thinks: "Oh, the user just pressed Enter without typing anything!" So it returns an empty string and moves on. 𝐓𝐡𝐞 𝐅𝐢𝐱: We have to "consume" the ghost! I learned you need to call an extra 𝐬𝐜.𝐧𝐞𝐱𝐭𝐋𝐢𝐧𝐞() just to clear that leftover newline before taking the actual input. 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠 𝐢𝐧 𝐏𝐮𝐛𝐥𝐢𝐜: Coming from C++, I'm used to cin.ignore(), but seeing it happen in Java was a great reminder of how input buffers work under the hood. Have you ever been haunted by the nextLine() ghost? How did you first solve it? #Java #CodingBeginner #SoftwareEngineering #Scanner #LearningInPublic
To view or add a comment, sign in
-
-
Just solved **LeetCode 219: Contains Duplicate II** (Easy) using a clean **sliding window + HashSet** approach in Java! 🚀 The key insight: Maintain a set of at most (k+1) recent elements. If you encounter a duplicate before sliding out older ones, the indices are guaranteed to be ≤ k apart. java class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Set<Integer> set = new HashSet<>(); for (int i = 0; i < nums.length; i++) { // If we've already seen this number in the current window, it's a duplicate! if (set.contains(nums[i])) { return true; } // Add the current number to the set (window) set.add(nums[i]); // If the window is too big (more than k+1 elements), remove the oldest one if (set.size() > k) { set.remove(nums[i - k]); } } return false; // No nearby duplicates found } } - Time: O(n) - Space: O(k) What's your favorite sliding window problem? Drop it below! 👇 #LeetCode #Coding #DataStructures #Algorithms #Java #SystemDesign #Tech #InterviewPrep
To view or add a comment, sign in
-
-
📘 Day 74 – Decode String Solved the Decode String problem — a classic stack-based challenge that focuses on string parsing and handling nested patterns. 🧩 Problem Overview Given an encoded string with repetition counts and brackets, decode it to produce the final expanded string. 🎯 Goal Correctly handle nested brackets, multi-digit numbers, and maintain order while decoding. 💡 Key Insight Using stacks helps track repetition counts and previously built strings, making nested decoding manageable. 🛠️ Approach Use stacks for counts and strings Build substrings incrementally Decode on closing brackets and merge results 🧠 Concepts Practiced Stack String manipulation Nested structure handling ⏱️ Time Complexity: O(N) 📦 Space Complexity: O(N) Showing up every day compounds learning 🌱 #Day74 #DSA #Stack #Java #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Day 21 of my DSA Journey (LeetCode + Java) Today’s practice focused on Array Manipulation + Counting Frequency problems. All three questions looked simple at first, but each required a deeper thought process to get the most optimized solution. ✅ Problems Solved Today LC 66 – Plus One LC 88 – Merge Sorted Array LC 1189 – Maximum Number of Balloons 🧠 My Experience Solving These: 🔸 66. Plus One This problem was trickier than I expected. Initially, I solved it in a non-optimized way. Then I realized the key insight: Traverse from the end If digit < 9, just increment and return If digit is 9 → make it 0 and continue If all digits are 9 → create new array with leading 1 Once I understood this, I solved it in one single loop—clean and efficient. 🔸 88. Merge Sorted Array My first approach used two loops and sorting, but it was: Extra time Not optimal Then I optimized it by using three pointers: i at the end of arr1 j at the end of arr2 k at the final position Compare & place larger element → move pointers. Finally append remaining elements from arr2. This method was fully optimized (O(n)) without any extra space. 🔸 1189. Maximum Number of Balloons This one was fun! I used a HashMap to count frequency of characters. The tricky part was: How to divide counts correctly for repeated characters like 'l' and 'o' After several dry runs, the logic became clear: Count freq of each char in text Count required freq for word “balloon” Divide actual/required → minimum of all divisions = answer A clean and optimal solution. 📌 Key Takeaway Today Even simple array problems can become tricky if we miss the pattern. Today I reinforced: ✔ Think from the end for digit problems ✔ Use three pointers for merging arrays ✔ Frequency-based problems → always check min(actual/required) ✔ Dry run is your best friend Step-by-step progress every day is building my confidence and logical thinking. 💪 On to Day 22! 🚀 #DSA #LeetCode #Java #Arrays #HashMap #ProblemSolving #CodingJourney #Consistency #LearningDaily
To view or add a comment, sign in
-
🌱 My Spring Journey : @Value Annotation in Spring This annotation is basically used to inject values into simple-type Spring bean properties. 🔹 There are different ways of injecting simple values into Spring bean properties : -> To inject direct values into Spring bean properties. -> To inject values gathered from a properties file. -> To inject system property values like os.name, os.version, etc. -> To inject environment variable values into Spring bean properties. 🔹 We can provide direct values to the @Value annotation, or we can specify a key using a placeholder @Value("${...}"). Difference between @Autowired and @Value : -> @Autowired is used to inject one Spring bean class object into a property (HAS-A relationship) of another Spring bean class. -> @Value is used to inject simple values into the properties of a Spring bean class. 🔹 Internal working : -> The moment the IOC container is created, it internally creates a built-in object called the Environment object, which dynamically collects : -> Key-value pairs defined in the configured properties file. -> Key-value pairs of fixed system properties. -> Environment variable names and their values. Later, these values are injected into Spring bean properties based on the @Value annotation. #SpringFramework #SpringBoot #Java #BackendDevelopment #DependencyInjection #LearningInPublic #MySpringJourney
To view or add a comment, sign in
-
Problem of the Day: Minimum Absolute Difference (LeetCode) Today I tackled the classic Minimum Absolute Difference problem. The goal is simple yet elegant: . Given an array of integers, find all pairs with the smallest absolute difference. Here’s my clean and efficient Java solution: ...................................................................................................................................................... class Solution { public List<List<Integer>> minimumAbsDifference(int[] arr) { Arrays.sort(arr); int min=Integer.MAX_VALUE; for(int i=1;i<arr.length;i++){ min=Math.min(min,(arr[i]-arr[i-1])); } List<List<Integer>> l=new ArrayList<>(); for(int i=1;i<arr.length;i++){ if((arr[i]-arr[i-1])==min){ l.add(Arrays.asList(arr[i - 1], arr[i])); } } return l; } } ........................................................................................................................................................ Key Takeaways: Sorting simplifies the problem by ensuring differences are checked only between consecutive elements. A two-pass approach (first to find the minimum difference, second to collect pairs) keeps the logic clear and modular. Time complexity: O(n log n) due to sorting, which is optimal here. ✨ Solving problems like these sharpens algorithmic thinking and prepares us for real-world scenarios where efficiency matters. #Java #LeetCode #ProblemSolving #CodingChallenge #DataStructuresAndAlgorithms
To view or add a comment, sign in
-
Here is a clear, detailed explanation of the String Constant Pool, written exactly with respect to the picture 👇 📌 String Constant Pool (with reference to the diagram) In the given picture, Str1 and Str2 are reference variables stored in the Stack memory. Both variables point to the same String value "Hello", which is stored in the String Constant Pool inside the Heap memory. When the String literal "Hello" is created, Java first checks whether this value already exists in the String Constant Pool. Since the value is already present, Java does not create a new object. Instead, both Str1 and Str2 reference the same memory location. This sharing of the same String object helps Java save memory and improve performance. Even though there are two different references in the stack, only one String object exists in the heap. This behavior is specific to String literals and is one of the key reasons why Strings are immutable in Java. 👉 Key observation from the picture: Multiple stack references → One String object in String Constant Pool. #Java #StringConstantPool #StringLiteral #HeapMemory #StackMemory #JavaBasics #LearningJava
To view or add a comment, sign in
-
-
Polymorphism isn't magic. It's a Lookup Table. I wrote Java for 3 years before I actually understood how the JVM handles Overriding. I relied on the standard university rule: "Method calls are determined by the actual Object type, not the Reference type." While this explains what happens, it doesn't explain how. I imagined the JVM frantically "searching" up the inheritance tree at runtime—scanning the Child class, then the Parent—until it found the method. Architecturally, that would be a disaster. If the JVM had to search the hierarchy (O(N)) for every method call, Java would be too slow for high-performance systems. The JVM avoids this search entirely using vTables (Virtual Method Tables). The Scenario: Imagine we have class B extends A. A has a method print() B overrides show() but inherits print() The Mechanics (Visualized below): Load Time: When Class B is loaded, the JVM builds a hidden array of function pointers. The "Cheat": Since B inherits print(), the JVM simply copies the memory address from A's table into B's table. Runtime: When you run A obj = new B() and call obj.show(), the JVM follows the object in Heap, jumps to the fixed index in the vTable, and runs the code. As the diagram shows: Solid Arrow: The overridden method points to the new B.show() code. Dashed Arrow: The inherited method points back to the existing A.print() code. The Lesson: Efficient systems rarely rely on runtime decisions if they can pre-calculate the answer at load time. (PS: I share more System Design deep dives like this on X. Link in comments 👇) #Java #JVM #SystemDesign #SoftwareArchitecture
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
diagram is wrong inside SCP area no duplicate their (java / java )