Side by side
Python ↔ Java
Curated pairs where the two languages solve the same underlying problem in genuinely comparable ways — not a forced mapping between unrelated features. More pairs get added as new topics land.
Identity vs. equality, and reference caching
Python
`is` vs `==`, the small-int cache, and string interning
==compares value (calls__eq__).iscompares identity (same object in memory, sameid()).
python
# Python 3.8+ warns on `is` against an int/str literal, since it's almost always a mistake.
# We're deliberately doing it on purpose here to demonstrate identity semantics, so silence that warning.
import warnings
warnings.filterwarnings("ignore", category=SyntaxWarning)
a = 256
b = 256
print("256 is 256:", a is b, "|", a == b)
e = -5
f = -5
print("-5 is -5: ", e is f, " <- both in the cached range, always True, script or notebook")
Output
256 is 256: True | True -5 is -5: True <- both in the cached range, always True, script or notebook
Java
`==` vs `.equals()`, and the String constant pool
== on objects compares reference identity. .equals() compares logical equality (as defined by
the class). String literals are special: the JVM interns them in a shared constant pool, so two identical
literals ARE the same reference — but new String(...) deliberately creates a distinct heap object even
if the contents match. .intern() looks a string up in (or adds it to) the pool.
java
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
System.out.println("s1 == s2 (both literals, pooled): " + (s1 == s2));
System.out.println("s1 == s3 (s3 is `new String(...)`): " + (s1 == s3));
System.out.println("s1.equals(s3): " + s1.equals(s3));
System.out.println("s1 == s3.intern(): " + (s1 == s3.intern()));
Output
s1 == s2 (both literals, pooled): true
Output
s1 == s3 (s3 is `new String(...)`): false
Output
s1.equals(s3): true
Output
s1 == s3.intern(): true