𝗝𝗮𝘃𝗮 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽: 𝗜𝗻𝘁𝗲𝗴𝗲𝗿 𝗖𝗮𝗰𝗵𝗶𝗻𝗴 & 𝗪𝗿𝗮𝗽𝗽𝗲𝗿 𝗚𝗼𝘁𝗰𝗵𝗮𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱! 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
Java Integer Cache Gotcha
More Relevant Posts
-
🚀 Java Deep Dive: "try-with-resources" Closing Order (Real Example) 🔥 Most developers know it auto-closes resources… But the ORDER? That’s where interviews get tricky 😏 👉 Real-world example: import java.io.*; public class Main { public static void main(String[] args) throws Exception { try (FileInputStream fis = new FileInputStream("test.txt"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr)) { System.out.println("Reading file..."); } } } 💡 Output: Reading file... (then resources close automatically) 👉 Actual closing order: BufferedReader InputStreamReader FileInputStream Why reverse order? Because Java follows LIFO (Last In, First Out) 👉 Last opened → First closed 🔥 Understand the chain: Open order: FileInputStream → InputStreamReader → BufferedReader Close order: BufferedReader → InputStreamReader → FileInputStream ⚠️ Interview Tip: Always remember dependency: - Outer resource depends on inner ones - So it must close FIRST 💬 One-liner to remember: “Resources open in sequence… but close in reverse.” #Java #JavaInterview #Coding #ExceptionHandling #IO #Programming #Developers #TechTips
To view or add a comment, sign in
-
💡 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
-
🚀 ArrayDeque in Java 📌 How to use ArrayDeque ad = new ArrayDeque(); ad.add(10); ad.add(20); ad.add(30); System.out.println(ad); 📌 Points to Remember 1️⃣ Initial capacity = 16 2️⃣ Heterogeneous data → Yes, it will store 3️⃣ Preserves order of insertion 4️⃣ Duplicates are allowed 5️⃣ Null values are NOT allowed 📌 Constructors (3) 1. ArrayDeque() 2. ArrayDeque(int) 3. ArrayDeque(Collection) Example: LinkedList ll = new LinkedList(); ll.add(10); ll.add(20); ArrayDeque ad = new ArrayDeque(ll); 📌 Internal Structure 👉 Resizable array (Dynamic array) 📌 Hierarchy Iterable → Collection → Queue → Deque → ArrayDeque 📌 Accessing Elements ❌ No indexes in ArrayDeque ❌ Normal for loop will not work ✔️ Use for-each loop for(Object a : ad){ System.out.println(a); } 📌 Iterator (Forward) Iterator cursor = ad.iterator(); while(cursor.hasNext()){ System.out.println(cursor.next()); } 📌 Descending Iterator (Backward) Iterator cursor = ad.descendingIterator(); while(cursor.hasNext()){ System.out.println(cursor.next()); } 📌 When to use ArrayDeque ✔️ Heterogeneous data ✔️ Duplicate entries ✔️ No null values ✔️ Preserves order of insertion 🎯 Summary: ArrayDeque is a resizable array-based data structure that allows insertion and deletion from both ends, preserves order, allows duplicates, but does not allow null values and indexing. #Java #ArrayDeque #JavaCollections #Programming #Coding #Developers #Learning
To view or add a comment, sign in
-
🚀 Java Basic That Many Ignore: What is String[] args in main()? 🤔 We write this every day: public static void main(String[] args) { System.out.println("Hello"); } 👉 But what exactly is args? 💡 args = Command Line Arguments It is an array of Strings passed when running your program 👉 Example: public class Test { public static void main(String[] args) { System.out.println(args[0]); } } Run this: java Test Hello 👉 Output: Hello 🤯 Important Points: args is just a variable name (you can change it) It is always an array of String It can be empty (no arguments passed) 🔥 Fun Fact: public static void main(String[] xyz) 👉 This also works! 😄 ⚠️ Be careful: System.out.println(args[0]); ❌ If no argument → ArrayIndexOutOfBoundsException 💡 Safe way: if (args.length > 0) { System.out.println(args[0]); } Small concept… but important for interviews & real-world usage 💪 #Java #Programming #Coding #JavaDeveloper #InterviewPrep #Developers
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
-
-
🚀 Can you find the first non-repeating character in a string? Here’s a simple Java approach 👇 String str = "aabbcd"; for(int i = 0; i < str.length(); i++) { boolean unique = true; for(int j = 0; j < str.length(); j++) { if(i != j && str.charAt(i) == str.charAt(j)) { unique = false; break; } } if(unique) { System.out.println(str.charAt(i)); break; } } 💡 Output: c 🔍 How it works: For each character, we check if it appears anywhere else in the string If it appears → not unique ❌ If it does NOT appear → first non-repeating character ✅ 👉 Time Complexity: O(n²) 💭 Interview Insight: This question is commonly asked to test your understanding of: ✔ Strings ✔ Nested loops ✔ Logic building 📌 Bonus: Can you optimize this to O(n) using HashMap? 👀 Drop your approach in comments 👇 #Java #Coding #DSA #InterviewPrep #Developers #100DaysOfCode
To view or add a comment, sign in
-
🚀 𝐖𝐡𝐲 𝐀𝐫𝐞 𝐒𝐭𝐫𝐢𝐧𝐠𝐬 𝐈𝐦𝐦𝐮𝐭𝐚𝐛𝐥𝐞 𝐢𝐧 𝐉𝐚𝐯𝐚? If you’ve worked with Java, you’ve probably heard this often: 👉 “Strings are immutable.” But have you ever wondered why? Let’s break it down 👇 🔹 1. 𝐒𝐞𝐜𝐮𝐫𝐢𝐭𝐲 🔐 * Strings are heavily used in sensitive areas like file paths, URLs, database connections, and authentication. * Immutability ensures these values can’t be altered once created, preventing unexpected vulnerabilities. 🔹 2. 𝐒𝐭𝐫𝐢𝐧𝐠 𝐏𝐨𝐨𝐥 𝐎𝐩𝐭𝐢𝐦𝐢𝐳𝐚𝐭𝐢𝐨𝐧 💡 * Java uses a String Constant Pool to reuse memory. Example: String a = "hello"; String b = "hello"; Both a and b point to the same object — saving memory efficiently. 🔹 3. 𝐓𝐡𝐫𝐞𝐚𝐝 𝐒𝐚𝐟𝐞𝐭𝐲 🧵 * Since Strings can’t change, they are inherently thread-safe. * No need to worry about synchronization when sharing across threads. 🔹 4. 𝐂𝐚𝐜𝐡𝐢𝐧𝐠 𝐇𝐚𝐬𝐡𝐂𝐨𝐝𝐞 ⚡ * Strings are widely used as keys in HashMaps. * Immutability allows caching of hashcode, making lookups faster. 🔹 5. 𝐏𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐜𝐞 𝐓𝐫𝐚𝐝𝐞-𝐨𝐟𝐟 ⚖️ * While immutability may create more objects, it avoids side effects and leads to cleaner, predictable code. 💬 𝑷𝒓𝒐 𝑻𝒊𝒑: If you need mutable strings, use: ** StringBuilder (single-threaded) ** StringBuffer (multi-threaded) ✨ 𝐅𝐢𝐧𝐚𝐥 𝐓𝐡𝐨𝐮𝐠𝐡𝐭: 𝘐𝘮𝘮𝘶𝘵𝘢𝘣𝘪𝘭𝘪𝘵𝘺 𝘪𝘴𝘯’𝘵 𝘫𝘶𝘴𝘵 𝘢 𝘥𝘦𝘴𝘪𝘨𝘯 𝘤𝘩𝘰𝘪𝘤𝘦 — 𝘪𝘵’𝘴 𝘢 𝘱𝘰𝘸𝘦𝘳𝘧𝘶𝘭 𝘤𝘰𝘯𝘤𝘦𝘱𝘵 𝘵𝘩𝘢𝘵 𝘮𝘢𝘬𝘦𝘴 𝘑𝘢𝘷𝘢 𝘢𝘱𝘱𝘭𝘪𝘤𝘢𝘵𝘪𝘰𝘯𝘴 𝘮𝘰𝘳𝘦 𝘴𝘦𝘤𝘶𝘳𝘦, 𝘦𝘧𝘧𝘪𝘤𝘪𝘦𝘯𝘵, 𝘢𝘯𝘥 𝘳𝘦𝘭𝘪𝘢𝘣𝘭𝘦. #Java #BackendDevelopment #Programming #SoftwareEngineering #TechConcepts #JavaDeveloper
To view or add a comment, sign in
-
-
#Design a basic URL Shortener service in Java Try Self than check #Solution 1. Functional Requirements: 2. Convert a long URL → short URL 3. Convert a short URL → original long URL 4. Same long URL should always return the same short URL 5. Short URL should be unique and collision-free 6. Handle up to 1 million URLs efficiently Input: encode("https://lnkd.in/geHb6Qua") Output: "http://mahfooz.com/abc123" decode("http://mahfooz.com/abc123") Output: "https://lnkd.in/geHb6Qua" # Constraints 1. Time Complexity: O(1) for encode & decode 2. Space Complexity: Optimize for large data 3. Avoid collisions 4. No external DB (in-memory only) Theory Questions (Must Answer) 1. Why did you choose HashMap? Explain internal working of HashMap What is average & worst-case complexity? 2. How will you avoid collisions? What if two URLs generate same short code? 3. How will you scale this system? If millions of users hit your backend How to move from in-memory → distributed system? 4. Thread Safety Is your solution thread-safe? If not, how will you fix it? 5. Backend Concept If implemented in Spring Boot, how will APIs look? https://lnkd.in/grX_mVes #Java #JavaDeveloper #BackendDeveloper #SoftwareEngineer #CodingInterview #DSA #Programming #Tech #Developers #InterviewPreparation #JavaBackend
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
-
-
30 Days - 30 Questions Journey Completed! 💻🔥 💡 Question: What is the difference between volatile and Atomic variables in Java? 🔹 volatile volatile ensures visibility of changes across threads. It guarantees that a variable is always read from main memory, not from thread cache. Example: ```java id="p8k3l2" volatile int count = 0; ``` --- 🔹 Problem with volatile volatile does NOT guarantee atomicity. Example: ```java id="x7m2q1" count++; // Not thread-safe ``` Because this operation is: Read → Modify → Write Multiple threads can interfere here. --- 🔹 Atomic Variables Atomic variables provide both: • Visibility • Atomicity Example: ```java id="d3k9s1" AtomicInteger count = new AtomicInteger(0); count.incrementAndGet(); ``` --- 🔹 Key Differences volatile • Ensures visibility • Not thread-safe for operations • Lightweight Atomic • Ensures visibility + atomicity • Thread-safe operations • Uses CAS (Compare-And-Swap) --- ⚡ Quick Facts • volatile is good for flags (true/false) • Atomic is used for counters and updates • Atomic classes are part of java.util.concurrent --- 📌 Interview Tip Use volatile for simple state visibility Use Atomic when performing read-modify-write operations --- Follow this series for 30 Days of Java Interview Questions. #java #javadeveloper #codinginterview #backenddeveloper #softwareengineer #programming #developers #tech
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