Why does Integer a = 100; Integer b = 100; are equal But Not for 128? 🤔 Let’s talk about a sneaky little JVM optimization called Integer Caching, one that silently saves memory and boosts performance in your Java apps. What’s Happening Behind the Scenes? When you write: Integer a = 100; Integer b = 100; System.out.println(a == b); // true Both a and b point to the same cached Integer object, no new object created! But if you do this: Integer x = 128; Integer y = 128; System.out.println(x == y); // false Now they’re different objects. Why? Because Java caches Integer objects only in the range -128 to +127 by default. These are the most frequently used numbers (loop counters, indexes, etc.), so reusing them saves a lot of memory and object creation overhead. Remember == compares object references, not values. So always use: a.equals(b) for value comparisons. #java #jvm #performance
Integer Caching in Java: Why 100 == 100 but 128 != 128
More Relevant Posts
-
Reversing the bits of a 32-bit integer in Java involves manipulating its binary representation. While Java's int type is signed, the problem often implies treating the bits as an unsigned sequence for reversal purposes. Common Approach: A common method for reversing bits involves iterating through the 32 bits of the input integer and constructing a new integer with the bits in reversed order. Initialize Result: Create an integer variable, for example, reversedNum, initialized to 0. This will store the bits as they are reversed. Iterate Through Bits: Loop 32 times, representing each bit position from 0 to 31. Shift reversedNum Left: In each iteration, left-shift reversedNum by 1 bit (reversedNum <<= 1). This creates space for the next bit to be added from the input number. Extract Least Significant Bit (LSB): Get the LSB of the input number n using a bitwise AND operation (n & 1). This isolates the rightmost bit. Set Bit in reversedNum: Use a bitwise OR operation (reversedNum |= (n & 1)) to set the LSB of reversedNum to the extracted LSB of n. Shift n Right: Right-shift n by 1 bit (n >>= 1) to move to the next bit for the subsequent iteration. Return reversedNum: After the loop completes, reversedNum will contain the original number's bits in reverse order.
To view or add a comment, sign in
-
-
Checked vs unchecked exceptions in Java:- The primary difference between checked and unchecked exceptions in Java lies in whether the compiler forces you to handle them. 🧐 Checked Exceptions Definition: These are exceptions that are checked at compile time. The Java compiler ensures that a program either handles them (using a try-catch block) or declares them (using the throws keyword in the method signature). Inheritance: They generally inherit from the java.lang.Exception class (excluding RuntimeException and its subclasses). Purpose: They represent situations that are typically recoverable and outside the direct control of the programmer, such as issues with I/O, database connections, or network access. The program is expected to anticipate and handle these errors. Examples: IOException, SQLException, FileNotFoundException. 🚫 Unchecked Exceptions Definition: These are exceptions that are not checked at compile time. The compiler does not force you to handle or declare them. Inheritance: They inherit from the java.lang.RuntimeException class or its subclasses, and also from java.lang.Error. Purpose: They usually represent programming errors or defects (logic errors) that often cannot be reasonably recovered from at runtime, such as passing a null argument or accessing an array index out of bounds. The expectation is that the code should be fixed to prevent these. Examples: NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException, ArithmeticException. #java #corejava #automationtesting #fullstackdevelopmment
To view or add a comment, sign in
-
💡 Understanding Java Garbage Collection (GC): Why You Shouldn’t Call It Manually In Java, Garbage Collection (GC) automatically manages memory by removing unused objects from the heap — one of the core reasons Java is called a “memory-safe” language. 🗑️ How It Works: The Memory Cycle The JVM runs the garbage collector in the background, freeing up memory when it detects objects that are no longer reachable. This process often involves checking different memory pools, like the Young and Old generations, to efficiently prioritize removing short-lived objects. ⚠️ Can We Call It Manually? Yes, we can request garbage collection by calling: System.gc(); or Runtime.getRuntime().gc(); However, this is just a request — the JVM may or may not execute GC immediately. 🛑 Why We Shouldn’t Call GC Manually 🚫 It can impact performance significantly, as GC is a heavy operation that typically involves a "Stop-The-World" pause for the application. 🚫 The JVM’s own memory manager is much smarter at deciding the best, least disruptive time to perform GC based on heap usage and object lifetime. 🚫 Frequent or forced GC calls can cause unnecessary CPU usage and latency spikes, especially in high-throughput production systems. 👉 In short: Let the JVM handle it! The automatic garbage collector is optimized for efficiency, and manual intervention often does more harm than good. #Java #GarbageCollection #JVM #Performance #CodingTips #MemoryManagement
To view or add a comment, sign in
-
"The hidden truth about Java Generics:-It's all about the reference type"👇👇 Java Generics: Who Really Enforces Type Safety? Here’s a concept that even seasoned Java devs sometimes miss: 👉 The compiler enforces type safety based only on the reference side, not on the object creation side. Example: List<String> list = new ArrayList<String>(); // Safe List<String> list = new ArrayList<>(); // Type inferred List list = new ArrayList<String>(); // Compiles but not type-safe Even though the right side (new ArrayList<String>()) has <String>, the compiler stops enforcing type checks if the reference (List) is raw. So this compiles: List list = new ArrayList<String>(); list.add(10); list.add("Hi"); …but explodes later at runtime: String s = (String) list.get(0); // ClassCastException Why? Because Java generics use type erasure — at runtime, the JVM only sees raw types (no <String>, <Integer>, etc.). Summary: Compile-time → Checked by compiler (reference type matters) Runtime → JVM sees only raw types ✅ Always declare generics on the reference side: List<String> names = new ArrayList<>(); Because type safety travels with the reference, not the object creation. #Java #Generics #ProgrammingTips #TypeSafety #CodeBetter #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
🚀 Map.of() vs Map.ofEntries(): The Java 9 Feature Every Developer Should Know 🔹 1. What They Are ? Map.of() and Map.ofEntries() are Java 9 factory methods to create immutable maps with clean, concise syntax. 🔹 2. Map.of() — Best for Small Maps Use when: You have up to 10 key-value pairs Highlights Most concise syntax Extremely readable Throws error on duplicate keys Immutable by design Example: Map.of("A", 1, "B", 2, "C", 3); 🔹 3. Map.ofEntries() — Best for Larger Maps Use when: You need more than 10 entries or prefer structured formatting Highlights No limit on number of entries Works with Map.entry(k, v) Cleaner for long or dynamic maps Immutable Example: Map.ofEntries( Map.entry("A", 1), Map.entry("B", 2), Map.entry("C", 3) ); 🔹 4. When to Use What? ✨ Use Map.of() For quick config maps, test constants, or small static data. ✨ Use Map.ofEntries() For big maps, cleaner formatting, or programmatically built entries. #java #interviewprep
To view or add a comment, sign in
-
-
🚨 Diamond Problem in Java — Explained Simply! If you’ve ever explored multiple inheritance, you might have come across the Diamond Problem. It happens when a class inherits from two classes that share a common parent. This creates a conflict about which parent’s method to use. 🔹 Java avoids this issue by not allowing multiple inheritance using classes. 🔹 But Java does allow multiple inheritance using interfaces. Here’s the interesting part👇 If two interfaces provide the same default method, Java forces the subclass to override it — making the design unambiguous. Diagram: A / \ B C \ / D 💡 Mini Example: interface A { default void show() { System.out.println("Show from A"); }} interface B extends A {} interface C extends A {} class D implements B, C { @Override public void show() { System.out.println("Show resolved in D"); } } #Java #JavaDeveloper #OOPs #Coding #SoftwareEngineering
To view or add a comment, sign in
-
Working with byte[] data is common in Java applications — for example, when reading input streams, files, or network responses. In many cases, you may need to convert this binary data into a URI (Uni https://lnkd.in/dTEdrdeF
To view or add a comment, sign in
-
🔍 Demystifying the volatile Keyword in Java (Made Simple!) Ever come across the volatile keyword in Java and wondered, “Do I really need this?” Here’s a clear and simple breakdown 👇 🧵 Single-Threaded Programs In single-threaded applications, using volatile doesn’t make any real difference. Only one thread is reading/writing the value — so there’s no chance of stale data, caching issues, or reordering problems. 🧵🧵 Multi-Threaded Programs This is where volatile truly matters! When multiple threads share a variable, marking it as volatile ensures: • ✔ Immediate Visibility Every thread instantly sees the updated value — no cached old values. • ✔ Ordering Guarantees Read/write operations involving a volatile variable are not reordered by the JVM or CPU, preventing subtle concurrency bugs. 🚫 But remember: volatile does NOT ensure atomicity. Operations like counter++ are still unsafe and can cause race conditions. For atomic operations, use: • synchronized • AtomicInteger, AtomicBoolean, etc. 💡 Common Use Cases Use volatile when you want to safely share simple status flags across threads, such as: • A shutdown/stop signal • A configuration flag • A readiness indicator ✨ The Bottom Line Use volatile when you need real-time visibility and proper ordering between threads — but don’t rely on it for complex atomic operations.
To view or add a comment, sign in
-
Method overloading in Java is when a class has multiple methods with the same name but different parameters (either in number or type). This allows you to perform similar but slightly different tasks using the same method name, improving code readability and reducing redundancy. java example : class Calculator { // Adds two integers public int add(int a, int b) { return a + b; } // Adds three integers public int add(int a, int b, int c) { return a + b + c; } // Adds two double values public double add(double a, double b) { return a + b; } } public class Test { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(5, 10)); // calls add(int, int) System.out.println(calc.add(5, 10, 15)); // calls add(int, int, int) System.out.println(calc.add(5.5, 3.2)); // calls add(double, double) } } Here, the add method name is overloaded with different parameter lists. The compiler decides which method to call based on arguments given. Summary: Method overloading means same method name, different parameters.Improves code clarity; no need for different method names for similar actions.Compiler selects correct method based on argument types/count. #Java #MethodOverloading #ProgrammingConcepts #CodingTips #JavaBasics #JavaDevelopment #100DaysOfCode #Day6ofcoding
To view or add a comment, sign in
-
Why Does Integer 200 Behave Differently in Java?🤔 Here’s a small but powerful Java concept that many developers overlook and it can even cause unexpected bugs. A Java byte has 8 bits: 1 sign bit → 0 = positive, 1 = negative 7 value bits → determine the magnitude. This gives the range of a byte as: The smallest value is: 10000000 → -128 The smallest value is: 01111111 → +127 code 1: Integer a = 200; Integer b = 200; System.out.println(a == b); //false code 2: Integer a = 100; Integer b = 100; System.out.println(a == b); //true Why This Happens, Java uses an Integer Cache for efficiency: Integer objects between -128 and 127 are cached for efficiency, meaning the same object is reused. Numbers outside this range (like 200) create new objects, so even if their values are the same, == returns false because it compares references, not values. Always use .equals() to compare the actual number.
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