3 Subtle Java Behaviors That Might Surprise You

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

Explore content categories