Skip to content

Python → Java — Quick Reference

← Home

S7 Inf A3 — Java for Graphical and Mobile Programming
Stéphane Derrode — Centrale Lyon

A side-by-side reference for students coming from Python. This is not a tutorial — keep it open during the labs and use it to translate what you already know in Python into Java.


Mental model

Python Java
Typing Dynamic (checked at run time) Static (checked at compile time)
Execution Interpreted Compiled to bytecode, run on the JVM
Entry point any top-level code public static void main(String[] args)
File ↔ class free one public class per file, same name
Blocks indentation braces { } — indentation is cosmetic
End of statement newline semicolon ;
Naming snake_case camelCase (vars/methods), PascalCase (classes)

Hello world

print("Hello")
public class App {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

Variables & types

Python Java Notes
x = 5 int x = 5; type is declared
x = 5.0 double x = 5.0;
x = True boolean x = true; lowercase true / false
x = "hi" String x = "hi"; String is a class
x = 'c' char x = 'c'; single quotes = char, not a string
x = None String x = null; null only for objects, not primitives
(dynamic) var x = 5; Java 10+: type inferred — local variables only

int, double, boolean, char are primitives (no methods). Everything else is an object reference.


Numbers — the integer-division trap

Python Java Result
5 / 2 5 / 2 Python 2.5 · Java 2
5 / 2 5.0 / 2 2.5 in both
5 // 2 5 / 2 2
5 % 2 5 % 2 1
2 ** 10 Math.pow(2, 10) 1024.0

⚠ In Java, int / int is an integer division. Make one operand a double to get a real result.


Strings

Python Java
len(s) s.length()
s + t s + t (use StringBuilder inside loops)
s == t (compare value) s.equals(t) — ⚠ == compares references
s.upper() / s.lower() s.toUpperCase() / s.toLowerCase()
s.strip() s.strip() (or s.trim())
s.split(",") s.split(",") — argument is a regex
"x" in s s.contains("x")
f"{a}+{b}={c}" String.format("%d+%d=%d", a, b, c)
str(n) String.valueOf(n)
int("5") Integer.parseInt("5")

Control flow

if x > 0:
    ...
elif x == 0:
    ...
else:
    ...

for i in range(n):
    ...
for item in items:
    ...
while cond:
    ...
if (x > 0) {
    ...
} else if (x == 0) {
    ...
} else {
    ...
}

for (int i = 0; i < n; i++) {
    ...
}
for (Type item : items) {   // enhanced for
    ...
}
while (cond) {
    ...
}

There is no truthiness: a condition must be a real boolean. if (list) is illegal — write if (!list.isEmpty()).


Collections

Python Java (interface / implementation)
[] list List<T> / ArrayList<T>
{} dict Map<K,V> / HashMap<K,V>
set() Set<T> / HashSet<T>
(a, b) tuple no direct equivalent → a small class / record / array
xs.append(x) xs.add(x)
xs[i] xs.get(i)
d[k] = v d.put(k, v)
d[k] d.get(k) — returns null if absent
k in d d.containsKey(k)
len(xs) xs.size()
for k, v in d.items(): for (var e : d.entrySet())e.getKey(), e.getValue()

The <…> (generics) fixes the element type at compile time: List<String> can only hold strings.


Functions / methods

def add(a, b):
    return a + b
int add(int a, int b) {
    return a + b;
}
  • No default arguments → write several signatures (overloading).
  • A static method belongs to the class (no object needed) — like a module-level function.

Classes

Python Java
class C: public class C { … }
def __init__(self, x): public C(int x) { … } (constructor = class name)
self this
self.x = x this.x = x; (field declared separately)
def m(self): public void m() { … }
def __str__(self): public String toString()
def __eq__(self, o): public boolean equals(Object o)also override hashCode()
@property / getters explicit getX() / setX() methods
convention _private the private keyword (actually enforced)

Visibility: private (class only) · package (no keyword) · protected (subclasses) · public.


None / null

  • null is the absence of an object. Calling a method on null throws NullPointerException (the cousin of Python's AttributeError: 'NoneType').
  • Guard with if (x != null), or use Optional<T> for "maybe absent" return values.

Exceptions

Python Java
try: … except E as e: try { … } catch (E e) { … }
raise E("msg") throw new E("msg");
finally: finally { … }
class E(Exception): class E extends RuntimeException { … }
with open(p) as f: try (var f = …) { … } (try-with-resources)

Java also has checked exceptions (e.g. IOException): a method must either catch them or declare throws IOException.


File I/O

with open("f.txt") as f:
    for line in f:
        print(line.strip())
try (var br = Files.newBufferedReader(Path.of("f.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} // file closed automatically

Comprehensions → Streams (preview)

areas = [s.area() for s in shapes]
total = sum(s.area() for s in shapes)
big   = [s for s in shapes if s.area() > 10]
var total = shapes.stream().mapToDouble(Shape::area).sum();
var big   = shapes.stream().filter(s -> s.area() > 10).toList();

You will meet these as optional refinements in TD2 (switch expression) and TD3 (Streams).


Top beginner gotchas

  1. == vs .equals() — for objects and String, == compares identity, not content.
  2. Integer division5 / 2 == 2; use 5.0 / 2 for 2.5.
  3. ; ends every statement; { } delimit every block.
  4. nullNullPointerException. Check before you call.
  5. Arrays have a fixed size — use ArrayList when the size varies.
  6. split takes a regex (so split(".") matches everything — escape it).
  7. main must be exactly public static void main(String[] args).