Strange Behaviors in Java: Integer Caching, String Comparison, Unary Plus, and Unicode Tricks
This article explains several counter‑intuitive Java behaviors—including integer caching with configurable range, string literal pool versus new objects, the unary plus being a sign rather than an operator, and Unicode escape processing that can make commented code execute—providing code examples and practical insights.
Java contains several surprising language features that often confuse developers. This article walks through four such quirks with clear explanations and runnable examples.
1. Integer caching – Java caches Integer objects in the range [-128, 127] by default, causing a == b to be true for values within the cache. The upper bound can be changed via the JVM property -Djava.lang.Integer.IntegerCache.high=300 , as shown in the following code:
public static void main(String[] args) {
Integer a = 120;
Integer b = 120;
Integer c = 130;
Integer d = 130;
System.out.println(a == b); // true
System.out.println(c == d); // false
}When the property is set to a higher value, both comparisons become true because the cache range expands.
2. String comparison – Literal strings are interned in the constant pool, so s1 == s2 yields true, while new String("hello") creates distinct objects, making s3 == s4 false. The intern() method can force a string into the pool.
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s1 == s2); // true
System.out.println(s3 == s4); // false
}3. Unary plus is not an operator – In the statement i =+ 2 , the + is a sign, not a binary addition operator, so the variable becomes 2 instead of 102 . Changing it to - would assign -2 .
public static void main(String[] args) {
int i = 100;
i =+ 2; // i becomes 2
System.out.println(i);
}4. Unicode escapes in comments – Unicode escape sequences are processed before compilation, even inside comments. The sequence \u000d turns a comment line into executable code, causing System.out.println("Hello World!"); to run despite appearing commented.
public static void main(String[] args) {
// \u000d System.out.println("Hello World!");
}These examples highlight the importance of understanding Java’s low‑level details to avoid unexpected behavior.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.