Ever wondered why this prints true 🤔 Integer x = 125; Integer y = 125; System.out.println(x == y); // true But this prints false 😮 Integer x = 250; Integer y = 250; System.out.println(x == y); // false Looks the same… but behaves differently? Let’s break it 👇 The Reason: Integer Caching Java internally caches Integer values in the range -128 to 127. So when you write: Integer x = 125; Integer y = 125; 👉 It actually uses: Integer.valueOf(125); ✔ Both variables point to the same cached object ✔ That’s why → x == y is true ⚠️ But outside the range… Integer x = 250; Integer y = 250; ❌ No caching here ❌ Separate objects are created 👉 So → x == y is false 🚨 Important Twist (Most people miss this!) Integer x = new Integer(125); Integer y = new Integer(125); System.out.println(x == y); // false ❌ new Integer() always creates a new object ❌ Caching is NOT used here 👉 Integer caching works only with: ✔ Integer.valueOf() ✔ Autoboxing (Integer x = 125) 💡 Golden Rule x.equals(y) // ✔ Always use this for value comparison Small concepts like these can make or break your interview. Did you already know this or learned something new today? 👇 #Java #Programming #JavaTips #Coding #Developers #InterviewPrep #BackendDevelopment Inspired by amazing learning content from CoderArmy, Rohit Negi and Aditya Tandon — highly recommend following their new JAVA series!
Java Integer Caching: Why == Fails
More Relevant Posts
-
💡 Can 2 + 1 = 4 in Java? Yes — and that should scare you At first glance, this sounds like a joke. But under the hood of the JVM, it’s a powerful reminder: 👉 Abstractions can be bent… if you understand them deeply enough. Java caches `Integer` objects in the range **-128 to 127**. This is done via an internal class called `IntegerCache`. Now here’s where things get interesting — using **Reflection**, you can modify that cache. Yes, you read that right. You can literally change what `2` means inside the JVM. ```java Class<?> cache = Class.forName("java.lang.Integer$IntegerCache"); Field field = cache.getDeclaredField("cache"); field.setAccessible(true); Integer[] array = (Integer[]) field.get(cache); // Make 2 behave like 3 array[130] = array[131]; System.out.println(2 + 1); // 4 ``` 🚨 After this: * `2` becomes `3` * `2 + 2` becomes `6` * Your JVM’s "reality" is now corrupted --- ### 🧠 What this actually teaches: ✔ Integer caching & autoboxing internals ✔ Reflection can break encapsulation ✔ “Immutable” doesn’t always mean “untouchable” ✔ JVM is powerful — but also dangerous in the wrong hands --- ### 🎯 Real Engineering Insight This is NOT about hacking math. This is about understanding: > *How deeply you understand the platform you work on.* At scale, such knowledge helps in: * Debugging impossible production bugs * Understanding memory behavior * Designing safe abstractions --- ### ⚠️ Final Thought Just because you *can* break the JVM… doesn’t mean you *should*. But if you *understand how* — you're no longer just a developer. You're thinking like a systems engineer. --- #Java #JVM #Reflection #SystemDesign #BackendEngineering #Performance #EngineeringMindset
To view or add a comment, sign in
-
Tackling the "Silent Overflow" in Java 🛑🔢 I recently worked through LeetCode #7: Reverse Integer, and it was a fantastic deep dive into how Java handles 32-bit integer limits and the dangers of "silent overflows." The Problem: Reverse the digits of a signed 32-bit integer. If the reversed number goes outside the 32-bit signed range of [-2^{31}, 2^{31} - 1], the function must return 0 The "Asymmetry" Challenge: In Java, Integer.MIN_VALUE is -2,147,483,648, while Integer.MAX_VALUE is 2,147,483,647. The negative range is one unit larger than the positive range due to Two's Complement arithmetic. This creates a massive trap: using Math.abs() on the minimum value will actually overflow and remain negative! My Optimized Solution Strategy: I implemented a two-pronged approach to handle these edge cases efficiently: 1️⃣ Pre-emptive Boundary Filtering: I added a specific optimization check at the very beginning: if(x >= Integer.MAX_VALUE - 4 || x <= Integer.MIN_VALUE + 6) return 0;. This catches values at the extreme ends of the 32-bit range immediately, neutralizing potential Math.abs overflow before the main logic even begins. 2️⃣ 64-bit Buffering: I used a long data type for the reversal calculation. This provides a 64-bit "safety net," allowing the math to complete so I can verify if the result fits back into a 32-bit int boundary. Complexity Analysis: 🚀 Time Complexity: O(log_10(n))— The loop runs once for every digit in the input (at most 10 iterations for any 32-bit integer). 💾 Space Complexity: O(1)— We use a constant amount of extra memory regardless of the input size. Small details like bit-range asymmetry can break an entire application if ignored. This was a great reminder that as developers, we must always think about the physical limits of our data types! #Java #LeetCode #SoftwareDevelopment #ProblemSolving #Algorithms #CleanCode #JavaProgramming #DataStructures #CodingLife
To view or add a comment, sign in
-
-
🚀 Mastering Prefix Sum & Suffix Sum in Java (DSA) Understanding Prefix Sum and Suffix Sum is a game-changer in Data Structures & Algorithms. These concepts help optimize problems that involve range sums and reduce time complexity significantly. 🔹 What is Prefix Sum? Prefix Sum is an array where each element at index `i` stores the sum of elements from index `0` to `i`. 👉 Formula: prefix[i] = prefix[i-1] + arr[i] 👉 Java Example: int[] arr = {1, 2, 3, 4, 5}; int n = arr.length; int[] prefix = new int[n]; prefix[0] = arr[0]; for(int i = 1; i < n; i++) { prefix[i] = prefix[i - 1] + arr[i]; } // Output: [1, 3, 6, 10, 15] 🔹 What is Suffix Sum ? Suffix Sum is an array where each element at index `i` stores the sum from index `i` to the end of the array. 👉 Formula: suffix[i] = suffix[i+1] + arr[i] 👉 Java Example: int[] arr = {1, 2, 3, 4, 5}; int n = arr.length; int[] suffix = new int[n]; suffix[n - 1] = arr[n - 1]; for(int i = n - 2; i >= 0; i--) { suffix[i] = suffix[i + 1] + arr[i]; } // Output: [15, 14, 12, 9, 5] 💡 Why is this important? ✔ Reduces time complexity from O(n²) → O(n) ✔ Used in range sum queries ✔ Helps in solving problems like equilibrium index, subarray sums, etc. Pro Tip: Once you understand prefix sums, try solving problems like: Subarray Sum Equals K Pivot Index Range Sum Query ✨ Consistency in DSA is the key. Small concepts like these build strong problem-solving foundations. #DSA #Java #Programming #Coding #SoftwareEngineering #SDET #Learning
To view or add a comment, sign in
-
Leetcode Practice - 8. String to Integer (atoi) The problem is solved using JAVA. Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: ✔ Whitespace: Ignore any leading whitespace (" "). ✔ Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present. ✔ Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. ✔ Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result. Example 1: Input: s = "42" Output: 42 Explanation: The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) #LeetCode #Java #StringHandling #CodingPractice #ProblemSolving #DSA #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
📌 Method References in Java — Cleaner Than Lambdas Method references provide a concise way to refer to existing methods using lambda-like syntax. They improve readability when a lambda simply calls an existing method. 1️⃣ What Is a Method Reference? Instead of writing a lambda: x -> System.out.println(x) We can write: System.out::println --- 2️⃣ Syntax ClassName::methodName Used when: • Lambda just calls an existing method • No additional logic is required --- 3️⃣ Types of Method References 🔹 Static Method Reference ClassName::staticMethod Example: Integer::parseInt --- 🔹 Instance Method Reference (of object) object::instanceMethod Example: System.out::println --- 🔹 Instance Method Reference (of class) ClassName::instanceMethod Example: String::length --- 🔹 Constructor Reference ClassName::new Example: ArrayList::new --- 4️⃣ Example Comparison Using Lambda: list.forEach(x -> System.out.println(x)); Using Method Reference: list.forEach(System.out::println); --- 5️⃣ Benefits ✔ More readable code ✔ Less boilerplate ✔ Cleaner functional style ✔ Works seamlessly with Streams --- 🧠 Key Takeaway Method references are a shorthand for lambda expressions that call existing methods. Use them when they improve clarity, not just to shorten code. #Java #Java8 #MethodReference #FunctionalProgramming #BackendDevelopment
To view or add a comment, sign in
-
Solved: Remove Duplicates from Sorted Array 🔍 Problem Summary: Given a sorted array, remove duplicates in-place such that each unique element appears only once and return the new length. 💡 Approach: ✔️ Used the Two Pointer technique ✔️ One pointer (index) tracks unique elements ✔️ Another pointer (j) scans the array ✔️ When a new element is found, move it forward 👨💻 Code (Java): public int removeDuplicates(int[] nums) { if (nums.length == 0) { return 0; } int index = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[index]) { index++; nums[index] = nums[j]; } } return index + 1; } ⚡ Key Learning: Understanding patterns is more important than memorizing solutions. Sorted array + duplicates → Two Pointer approach works efficiently. 📊 Complexity: ⏱ Time: O(n) 💾 Space: O(1) 📌 Improving step by step—consistency is the goal! #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Learning
To view or add a comment, sign in
-
-
Peglib 0.2.0 + 0.2.1 -- Major code generation reliability release Peglib is a PEG parser library for Java, inspired by cpp-peglib. It lets you define parsers using PEG grammar syntax, with support for both runtime interpretation and standalone source code generation. These two releases focused on one goal: making the generated standalone parser produce identical results to the interpreted parser. Every time. What changed: -- Rewrote the CST/AST code generator from the ground up to structurally mirror the interpreter's control flow. Identified and fixed 7 behavioral divergences in whitespace handling, predicate evaluation, cut failure propagation, and token boundary tracking. -- Fixed generated parsers crashing with StackOverflowError when the whitespace directive references named rules like LineComment or BlockComment. Added a reentrant guard matching the interpreter's approach. -- Fixed generated Token nodes losing their rule names. Tokens from < > captures now carry the parent rule name (e.g., "SelectKW", "NumericType") instead of a generic "token". -- Fixed CST tree structure. Container expressions (ZeroOrMore, OneOrMore, Optional) now wrap their children in proper NonTerminal nodes instead of flattening them into the parent -- matching how the interpreter builds the tree. -- Added 40 conformance tests that run the same grammars and inputs through both the interpreted and generated parsers, asserting identical success/failure outcomes. These fixes were discovered while building a PostgreSQL SQL parser with peglib. The interpreted parser handled the full grammar correctly, but the generated standalone parser had subtle failures. Now both produce matching results on all 350 tests. Test count: 308 -> 350 pragmatica-lite dependency: 0.9.10 -> 0.24.0 Available on Maven Central: <groupId>org.pragmatica-lite</groupId> <artifactId>peglib</artifactId> <version>0.2.1</version> GitHub: https://lnkd.in/dgdjZahV #java #parsing #peg #opensource #compilers
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽: 𝗜𝗻𝘁𝗲𝗴𝗲𝗿 𝗖𝗮𝗰𝗵𝗶𝗻𝗴 & 𝗪𝗿𝗮𝗽𝗽𝗲𝗿 𝗚𝗼𝘁𝗰𝗵𝗮𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱! Consider this simple code: class Main { public static void main(String[] args) { Integer a = 128; Integer b = 128; System.out.println(a == b); // ? System.out.println(a.equals(b)); // ? } } 🔍 Output: false true 🤔 Why does this happen? Java internally caches Integer objects in the range -128 to 127. ✅ Within range → same object → == is true ❌ Outside range → new objects → == is false 👉 == compares references (memory address) 👉 .equals() compares actual values 🔥 What about other wrapper classes? ✔ Cached Wrappers: Integer → -128 to 127 Byte → all values cached Short → -128 to 127 Long → -128 to 127 Character → 0 to 127 Boolean → only true & false (always cached) 👉 Example: Integer x = 100; Integer y = 100; System.out.println(x == y); // true ✅ ❗ NOT Cached: Float Double 👉 Example: Float f1 = 10.0f; Float f2 = 10.0f; System.out.println(f1 == f2); // false ❌ Double d1 = 10.0; Double d2 = 10.0; System.out.println(d1 == d2); // false ❌ 💥 Why no caching for Float/Double? Extremely large range of values Precision & representation complexity Not memory-efficient to cache 📌 Golden Rule: 👉 Never use == for wrapper comparison 👉 Always use .equals() or unbox to primitive 🚀 Pro Tip: You can extend Integer cache using JVM option: -XX:AutoBoxCacheMax=<value> 🎯 Interview Insight: This is a classic trap to test: Java memory concepts Autoboxing & unboxing Object vs primitive understanding 💡 Bonus Tip: Be careful with null values when unboxing: Integer i = null; int j = i; // Throws NullPointerException ⚠️ #Java #Programming #InterviewPrep #JavaTips #Coding #Developers #TechCareers
To view or add a comment, sign in
-
🔥 You write Arrays.sort() in Java all the time… but do you know what actually happens behind the scenes? Most developers don’t - and the truth is way more interesting than you’d expect 👇 ⚙️ 1. Sorting Primitive Types (int, double, char…) Java fires up Dual‑Pivot QuickSort ⚡ Faster than classic QuickSort ⚡ Highly optimized for real‑world data ⚠️ Not stable - but that’s irrelevant for primitives Hidden optimizations you might’ve never noticed: • Tiny arrays → switches to Insertion Sort • byte, short, char → may use Counting Sort for blazing speed 🧩 2. Sorting Objects (String, Integer, custom classes) Java switches to the legendary TIMSORT (yes, the same one Python uses) Why it’s brilliant: ✔ Hybrid of Merge Sort + Insertion Sort ✔ Detects natural order in your data ✔ Stable — crucial for objects ✔ Worst case: O(n log n) This is why object sorting feels surprisingly fast even on messy datasets. 🚀 3. Sorting Big Arrays? Java Goes Parallel Arrays.parallelSort() taps into the Fork/Join framework ✔ Splits the array ✔ Sorts chunks in parallel ✔ Merges everything efficiently A huge win for 10k+ elements on multi‑core systems. 🧠 The Cool Part Java doesn’t rely on one “universal” algorithm. It adapts intelligently based on: • Data type • Array size • Hardware • Real‑world patterns That’s why a single line of code can deliver such impressive performance. 🎯 Why This Matters Understanding this helps you: • Write more efficient, predictable code • Choose between sort() and parallelSort() • Stand out in interviews • Appreciate the engineering behind everyday APIs 💬 Did you already know Java uses multiple algorithms internally - or is this a new discovery for you? #Java #Algorithms #SoftwareEngineering #Backend #CodingInterview #ProgrammingInsights
To view or add a comment, sign in
-
🔥 Streams vs Loops in Java Short answer: Loops = control Streams = readability + functional style ⚙️ What are they? ➿ Loops Traditional way to iterate collections using for, while. 🎏 Streams (Java 8+) Functional approach to process data declaratively. 🚀 Why use Streams? 1. Less boilerplate code 2. Better readability 3. Easy chaining (map, filter, reduce) 4. Parallel processing support 🆚 Comparison Loops 1. Imperative (how to do) 2. More control 3. Verbose 4. Harder to parallelize Streams 1. Declarative (what to do) 2. Cleaner code 3. Easy transformations 4. Parallel-ready (parallelStream()) 💻 Example 👉 Problem: Get even numbers and square them Using Loop List<Integer> result = new ArrayList<>(); for (int num : nums) { if (num % 2 == 0) { result.add(num * num); } } Using Stream List<Integer> result = nums.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .toList(); ⚡ Flow (Streams) Collection → Open stream → Intermediate operations → Terminal operation → Use the result 🧠 Rule of Thumb Simple iteration / performance critical → Loop Data transformation / readability → Stream 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #Streams #Backend #CodingInterview #SpringBoot #Developers #InterviewPrep #CleanCode
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