Output & Running
Hello, World
class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
} print("Hello, World!") Python needs no class, no
main method, and no System.out — a top-level print() call is a complete program. Indentation replaces braces, and statements end at the newline rather than a semicolon.Formatted output
class Main {
public static void main(String[] args) {
String name = "Alice";
int age = 30;
System.out.printf("%s is %d%n", name, age);
}
} name = "Alice"
age = 30
print(f"{name} is {age}") Python f-strings interpolate values inline with
{...}, replacing Java's printf format specifiers (%s, %d). There is no separate format-versus-print distinction.Comments
class Main {
public static void main(String[] args) {
// a single-line comment
/* a block comment */
System.out.println("done");
}
} # a single-line comment
"""
A multi-line string, often used
as a block comment or docstring.
"""
print("done") Python uses
# for single-line comments. It has no dedicated block-comment syntax — a triple-quoted string fills that role and also serves as a documentation string.Variables & Types
Declaring variables
class Main {
public static void main(String[] args) {
String message = "hi";
int count = 3;
count = count + 1;
System.out.println(message + " " + count);
}
} message = "hi"
count = 3
count = count + 1
print(message, count) Python variables carry no type declaration — assignment alone creates them, and the same name can later hold a different type. The naming convention is
snake_case rather than Java's camelCase.Dynamic vs. static typing
class Main {
public static void main(String[] args) {
var value = 42;
System.out.println(value);
// value = "text"; // would not compile — type is fixed
System.out.println(((Object) value).getClass().getSimpleName());
}
} value = 42
print(value)
value = "now a string"
print(type(value).__name__) Java's
var still infers a single fixed type at compile time. Python is dynamically typed, so a variable can be rebound to any type at runtime; type(x).__name__ inspects the current type.null vs. None
class Main {
public static void main(String[] args) {
String result = null;
System.out.println(result == null);
}
} result = None
print(result is None) Python's equivalent of
null is the singleton None. The idiomatic test is is None (identity), not ==. Python has no primitive-versus-object split, so any variable can be None.Constants
class Main {
static final int MAX_RETRIES = 3;
public static void main(String[] args) {
System.out.println(MAX_RETRIES);
}
} MAX_RETRIES = 3
print(MAX_RETRIES) Python has no
final. An all-caps name signals intent only — nothing prevents reassignment, unlike Java's compiler-enforced final.Strings
Common string methods
class Main {
public static void main(String[] args) {
String text = "Hello World";
System.out.println(text.toUpperCase());
System.out.println(text.toLowerCase());
System.out.println(text.length());
}
} text = "Hello World"
print(text.upper())
print(text.lower())
print(len(text)) Python spells these
upper() and lower(), and length comes from the len() built-in rather than a .length() method.Interpolation
class Main {
public static void main(String[] args) {
String name = "World";
System.out.println(String.format("Hello, %s! Sum is %d", name, 2 + 2));
}
} name = "World"
print(f"Hello, {name}! Sum is {2 + 2}") Python f-strings embed any expression directly in
{...}, which is far more concise than Java's String.format() with positional specifiers.Split & join
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String csv = "a,b,c";
String[] parts = csv.split(",");
System.out.println(Arrays.toString(parts));
System.out.println(String.join("-", parts));
}
} csv = "a,b,c"
parts = csv.split(",")
print(parts)
print("-".join(parts)) Python's
split() returns a list directly. Note that join() is called on the separator string ("-".join(parts)), the reverse of Java's String.join(sep, parts).Substrings & slicing
class Main {
public static void main(String[] args) {
String word = "javascript";
System.out.println(word.substring(0, 4));
System.out.println(word.substring(word.length() - 6));
}
} word = "javascript"
print(word[0:4])
print(word[-6:]) Python slices with bracket syntax and supports negative indices, so the last six characters are
word[-6:] — no length() arithmetic as Java's substring() requires.Multi-line strings
class Main {
public static void main(String[] args) {
String poem = """
Roses are red
Violets are blue""";
System.out.println(poem);
}
} poem = """Roses are red
Violets are blue"""
print(poem) Both languages use triple-quoted text blocks for multi-line strings. Java strips incidental leading indentation relative to the closing delimiter; Python keeps the text exactly as written.
Numbers
Arithmetic & division
class Main {
public static void main(String[] args) {
System.out.println(7 + 2);
System.out.println(7 / 2); // integer division -> 3
System.out.println(7 / 2.0); // float division -> 3.5
System.out.println(7 % 2);
}
} print(7 + 2)
print(7 // 2) # floor division -> 3
print(7 / 2) # true division -> 3.5
print(7 % 2) In Java,
/ means integer division when both operands are integers. Python flips the defaults: / is always true division (a float), and // is the explicit floor-division operator.Numeric types & big integers
import java.math.BigInteger;
class Main {
public static void main(String[] args) {
long big = 1_000_000_000L;
System.out.println(big * big);
System.out.println(BigInteger.TWO.pow(100));
}
} big = 1_000_000_000
print(big * big)
print(2 ** 100) Python integers have unlimited precision built in, so
2 ** 100 is exact with no overflow and no BigInteger. There is no int-versus-long distinction — just one int type.Parsing strings to numbers
class Main {
public static void main(String[] args) {
int n = Integer.parseInt("42");
double d = Double.parseDouble("3.14");
System.out.println(n + " " + d);
}
} n = int("42")
d = float("3.14")
print(n, d) Python converts with the
int() and float() built-ins. Like Java's parse methods, they raise an error (a ValueError) on malformed input.Math functions
class Main {
public static void main(String[] args) {
System.out.println(Math.sqrt(16));
System.out.println(Math.max(3, 7));
System.out.println((int) Math.floor(3.7));
}
} import math
print(math.sqrt(16))
print(max(3, 7))
print(math.floor(3.7)) Python splits these between built-ins (
max, min, abs) and the math module (sqrt, floor), which must be imported — there is no always-available Math class.Lists & Collections
Creating & indexing lists
import java.util.List;
class Main {
public static void main(String[] args) {
List<String> fruits = List.of("apple", "banana", "cherry");
System.out.println(fruits.get(0));
System.out.println(fruits.get(fruits.size() - 1));
System.out.println(fruits.size());
}
} fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[-1])
print(len(fruits)) A Python list is a built-in literal with no generic type parameter. Indexing uses brackets (
fruits[0]) instead of .get(), supports negative indices, and length comes from len().Adding & removing
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3));
numbers.add(4);
numbers.remove(numbers.size() - 1);
System.out.println(numbers);
}
} numbers = [1, 2, 3]
numbers.append(4)
numbers.pop()
print(numbers) Python lists are always mutable and growable — there is no
ArrayList-versus-List.of distinction. You use append() to add and pop() to remove the last element.Iterating
import java.util.List;
class Main {
public static void main(String[] args) {
List<String> colors = List.of("red", "green", "blue");
for (String color : colors) {
System.out.println(color);
}
}
} colors = ["red", "green", "blue"]
for color in colors:
print(color) Python's
for color in colors is the direct equivalent of Java's enhanced for loop, iterating elements without an index.Transforming: streams vs. comprehensions
import java.util.List;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4);
List<Integer> doubled = numbers.stream()
.map(number -> number * 2)
.collect(Collectors.toList());
System.out.println(doubled);
}
} numbers = [1, 2, 3, 4]
doubled = [number * 2 for number in numbers]
print(doubled) A Python list comprehension replaces the whole
stream().map().collect() pipeline. It is both shorter and eager, returning a list directly rather than a lazy stream you must collect.Filtering
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
List<Integer> evens = IntStream.range(0, 10)
.filter(number -> number % 2 == 0)
.boxed()
.collect(Collectors.toList());
System.out.println(evens);
}
} evens = [number for number in range(10) if number % 2 == 0]
print(evens) The
if clause of a comprehension does the work of stream().filter(), and range(10) stands in for IntStream.range(0, 10) — no boxing step required.Summing & reducing
import java.util.List;
class Main {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4);
int total = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println(total);
}
} numbers = [1, 2, 3, 4]
print(sum(numbers)) Python's built-in
sum() works on any iterable of numbers, with none of Java's mapToInt ceremony. For general folds, functools.reduce() mirrors Stream.reduce().Sorting
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("banana", "apple", "cherry"));
words.sort(Comparator.naturalOrder());
System.out.println(words);
words.sort(Comparator.comparingInt(String::length));
System.out.println(words);
}
} words = ["banana", "apple", "cherry"]
print(sorted(words))
print(sorted(words, key=len)) Python's
sorted() returns a new list and takes a key function, far terser than Java's Comparator chains. The in-place variant is list.sort().Maps & Dicts
Creating & accessing
import java.util.Map;
class Main {
public static void main(String[] args) {
Map<String, Integer> person = Map.of("age", 30, "score", 95);
System.out.println(person.get("age"));
System.out.println(person.getOrDefault("missing", -1));
}
} person = {"age": 30, "score": 95}
print(person["age"])
print(person.get("missing", -1)) A Python dict is a built-in literal accessed with brackets (
person["age"]). The dict.get(key, default) method matches Java's getOrDefault, and bracket access raises KeyError on a missing key.Adding & updating
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("math", 95);
scores.merge("math", 1, Integer::sum);
System.out.println(scores);
}
} scores = {}
scores["math"] = 95
scores["math"] += 1
print(scores) Python assigns to a dict key with plain bracket syntax, and once a key exists you can use
+= directly — no put or merge needed.Iterating entries
import java.util.LinkedHashMap;
import java.util.Map;
class Main {
public static void main(String[] args) {
Map<String, Integer> person = new LinkedHashMap<>();
person.put("age", 30);
person.put("score", 95);
for (Map.Entry<String, Integer> entry : person.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
} person = {"age": 30, "score": 95}
for key, value in person.items():
print(key, value) Python's
dict.items() yields key/value pairs you unpack in the loop header, replacing Java's entrySet() with getKey()/getValue(). Regular dicts preserve insertion order, like a LinkedHashMap.Checking for a key
import java.util.Map;
class Main {
public static void main(String[] args) {
Map<String, Boolean> config = Map.of("debug", true);
System.out.println(config.containsKey("debug"));
System.out.println(config.containsKey("verbose"));
}
} config = {"debug": True}
print("debug" in config)
print("verbose" in config) Python uses the
in operator to test for a key, replacing Java's containsKey(). Note Python's booleans are capitalized: True and False.Control Flow
if / else if / else
class Main {
public static void main(String[] args) {
int score = 75;
if (score >= 90) {
System.out.println("A");
} else if (score >= 70) {
System.out.println("B");
} else {
System.out.println("C");
}
}
} score = 75
if score >= 90:
print("A")
elif score >= 70:
print("B")
else:
print("C") Python drops the parentheses and braces in favour of a colon and indentation, and contracts
else if to the keyword elif.Conditional expression
class Main {
public static void main(String[] args) {
int age = 20;
String status = age >= 18 ? "adult" : "minor";
System.out.println(status);
}
} age = 20
status = "adult" if age >= 18 else "minor"
print(status) Python's conditional expression reads in English order —
a if condition else b — rather than Java's C-style condition ? a : b.Boolean operators
class Main {
public static void main(String[] args) {
boolean ready = true;
boolean done = false;
System.out.println(ready && !done);
System.out.println(ready || done);
}
} ready = True
done = False
print(ready and not done)
print(ready or done) Python spells the boolean operators as the words
and, or, and not rather than Java's &&, ||, and !.switch vs. match
class Main {
public static void main(String[] args) {
String command = "start";
String result = switch (command) {
case "start" -> "starting";
case "stop" -> "stopping";
default -> "unknown";
};
System.out.println(result);
}
} command = "start"
match command:
case "start":
print("starting")
case "stop":
print("stopping")
case _:
print("unknown") Python's
match statement (3.10+) resembles Java's arrow-style switch: no fall-through and no break. The wildcard is case _, and Python's match can also destructure structures.Loops & Iteration
Counting loop
class Main {
public static void main(String[] args) {
for (int index = 0; index < 3; index++) {
System.out.println(index);
}
}
} for index in range(3):
print(index) Python has no C-style three-part loop. You iterate over
range(3), which yields 0, 1, 2. To count manually use index += 1 — there is no ++ operator.while loop
class Main {
public static void main(String[] args) {
int count = 3;
while (count > 0) {
System.out.println(count);
count -= 1;
}
}
} count = 3
while count > 0:
print(count)
count -= 1 The
while loop differs only in Python's colon and indentation. Python has no do...while construct.Index and value together
import java.util.List;
class Main {
public static void main(String[] args) {
List<String> colors = List.of("red", "green");
for (int index = 0; index < colors.size(); index++) {
System.out.println(index + " " + colors.get(index));
}
}
} colors = ["red", "green"]
for index, color in enumerate(colors):
print(index, color) Python's
enumerate() hands you the index and value together, eliminating the manual index-and-get() pattern Java requires for indexed iteration.break & continue
class Main {
public static void main(String[] args) {
for (int number = 0; number < 10; number++) {
if (number == 3) continue;
if (number == 6) break;
System.out.println(number);
}
}
} for number in range(10):
if number == 3:
continue
if number == 6:
break
print(number) Both
break and continue behave the same. Python adds a for...else clause that runs only if the loop completed without a break — something Java lacks.Methods & Functions
Defining a function
class Main {
static String greet(String name) {
return "Hi, " + name;
}
public static void main(String[] args) {
System.out.println(greet("Alice"));
}
} def greet(name):
return f"Hi, {name}"
print(greet("Alice")) Python functions are declared with
def at module level — no enclosing class, no static, and no return-type or parameter-type declarations.Default arguments vs. overloading
class Main {
static String greet(String name) {
return greet(name, "Hello");
}
static String greet(String name, String greeting) {
return greeting + ", " + name;
}
public static void main(String[] args) {
System.out.println(greet("Bob"));
System.out.println(greet("Bob", "Hi"));
}
} def greet(name, greeting="Hello"):
return f"{greeting}, {name}"
print(greet("Bob"))
print(greet("Bob", "Hi")) Python uses default parameter values instead of method overloading, so one function covers what Java needs several overloads for. Beware: a Python default is evaluated once at definition time, so never use a mutable default like
[].Variadic arguments
class Main {
static int total(int... numbers) {
int sum = 0;
for (int number : numbers) sum += number;
return sum;
}
public static void main(String[] args) {
System.out.println(total(1, 2, 3, 4));
}
} def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4)) Python's
*numbers collects extra positional arguments into a tuple, the counterpart to Java's int... numbers varargs. The built-in sum() then totals them directly.Keyword arguments
class Main {
static String makeUser(String name, String role) {
return name + "/" + role;
}
public static void main(String[] args) {
// Java has no keyword arguments; order and position are fixed.
System.out.println(makeUser("Alice", "admin"));
}
} def make_user(name, role="user"):
return f"{name}/{role}"
print(make_user("Alice", role="admin")) Python supports passing arguments by name (
role="admin"), which improves call-site clarity and pairs naturally with defaults. Java has no keyword arguments — parameters are always positional.Returning multiple values
class Main {
static int[] minMax(int[] numbers) {
int min = numbers[0], max = numbers[0];
for (int number : numbers) {
if (number < min) min = number;
if (number > max) max = number;
}
return new int[] { min, max };
}
public static void main(String[] args) {
int[] result = minMax(new int[] { 3, 1, 4, 1, 5 });
System.out.println(result[0] + " " + result[1]);
}
} def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 1, 5])
print(low, high) Python returns a tuple (the comma makes one) and unpacks it on assignment, so a function returns multiple values without an array, a wrapper class, or a record.
Lambdas & Streams
Lambdas
import java.util.function.Function;
class Main {
public static void main(String[] args) {
Function<Integer, Integer> square = value -> value * value;
System.out.println(square.apply(5));
}
} square = lambda value: value * value
print(square(5)) A Python
lambda is a plain callable assigned to a variable and invoked with normal call syntax (square(5)) — there is no functional-interface type or .apply(). It is limited to a single expression.Functions as arguments
import java.util.function.Function;
class Main {
static int applyTwice(Function<Integer, Integer> func, int value) {
return func.apply(func.apply(value));
}
public static void main(String[] args) {
System.out.println(applyTwice(x -> x + 3, 10));
}
} def apply_twice(func, value):
return func(func(value))
print(apply_twice(lambda x: x + 3, 10)) In Python functions are first-class values you pass and call directly, with no
Function<> interface to declare. Any callable can be passed wherever a function is expected.Pipelines: streams vs. comprehensions
import java.util.List;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
List<Integer> result = numbers.stream()
.filter(number -> number % 2 == 0)
.map(number -> number * 10)
.collect(Collectors.toList());
System.out.println(result);
}
} numbers = [1, 2, 3, 4, 5, 6]
result = [number * 10 for number in numbers if number % 2 == 0]
print(result) A single comprehension expresses both the filter and the transform that Java spreads across
stream().filter().map().collect(). For lazy pipelines, Python offers generator expressions and the itertools module.Classes & OOP
Class, fields & constructor
class Dog {
private final String name;
Dog(String name) { this.name = name; }
String speak() { return name + " says woof"; }
}
class Main {
public static void main(String[] args) {
System.out.println(new Dog("Rex").speak());
}
} class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof"
print(Dog("Rex").speak()) Python's constructor is
__init__, instances are created without new, and every method takes an explicit first parameter self. Fields are not declared separately — they spring into being when assigned on self.String representation
class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override public String toString() { return "(" + x + ", " + y + ")"; }
}
class Main {
public static void main(String[] args) {
System.out.println(new Point(1, 2));
}
} class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
print(Point(1, 2)) Python's
__str__ dunder method plays the role of Java's toString(), and print() calls it automatically. A separate __repr__ provides the unambiguous developer-facing form.Records vs. dataclasses
class Main {
record Point(int x, int y) {}
public static void main(String[] args) {
Point point = new Point(1, 2);
System.out.println(point);
System.out.println(point.x() + ", " + point.y());
}
} from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
point = Point(1, 2)
print(point)
print(point.x, point.y) Python's
@dataclass decorator is the counterpart to a Java record: it generates the constructor, a readable repr, and equality. Fields are accessed as plain attributes (point.x), not accessor methods.Static methods
class MathHelper {
static int add(int first, int second) { return first + second; }
}
class Main {
public static void main(String[] args) {
System.out.println(MathHelper.add(2, 3));
}
} class MathHelper:
@staticmethod
def add(first, second):
return first + second
print(MathHelper.add(2, 3)) Python marks class-level methods with the
@staticmethod decorator rather than a static keyword. It also offers @classmethod, which receives the class as its first argument.Inheritance & Interfaces
Inheritance & overriding
class Animal {
final String name;
Animal(String name) { this.name = name; }
String describe() { return name + " is an animal"; }
}
class Cat extends Animal {
Cat(String name) { super(name); }
@Override String describe() { return name + " is a cat"; }
}
class Main {
public static void main(String[] args) {
System.out.println(new Cat("Felix").describe());
}
} class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name} is an animal"
class Cat(Animal):
def describe(self):
return f"{self.name} is a cat"
print(Cat("Felix").describe()) Python declares the base class in parentheses (
class Cat(Animal)) instead of extends, and calls the parent constructor as super().__init__(name). There is no @Override annotation.Interfaces vs. duck typing
interface Speaker {
String speak();
}
class Robot implements Speaker {
public String speak() { return "beep boop"; }
}
class Main {
static void announce(Speaker speaker) {
System.out.println(speaker.speak());
}
public static void main(String[] args) {
announce(new Robot());
}
} class Robot:
def speak(self):
return "beep boop"
def announce(speaker):
print(speaker.speak())
announce(Robot()) Python relies on duck typing rather than declared interfaces: any object with a
speak() method works, with no implements clause. When you want an explicit contract, the abc module provides abstract base classes.Error Handling
try / catch vs. try / except
class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException error) {
System.out.println("caught: " + error.getMessage());
}
}
} try:
result = 10 / 0
except ZeroDivisionError as error:
print("caught:", error) Python catches with
except and binds the exception via as. The pattern mirrors Java closely; division by zero raises a catchable error in both.Throwing errors
class Main {
static int withdraw(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("amount must be positive");
}
return amount;
}
public static void main(String[] args) {
try {
withdraw(-5);
} catch (IllegalArgumentException error) {
System.out.println(error.getMessage());
}
}
} def withdraw(amount):
if amount < 0:
raise ValueError("amount must be positive")
return amount
try:
withdraw(-5)
except ValueError as error:
print(error) Python uses
raise where Java uses throw. A key difference: Python has no checked exceptions, so functions never declare what they might raise and the compiler never forces a try.finally
class Main {
public static void main(String[] args) {
try {
System.out.println("working");
} finally {
System.out.println("cleanup");
}
}
} try:
print("working")
finally:
print("cleanup") The
finally block runs whether or not an exception occurred, identically in both languages. For resource cleanup, Python's with statement is usually preferred over an explicit finally.Custom exceptions
class ValidationException extends RuntimeException {
ValidationException(String message) { super(message); }
}
class Main {
public static void main(String[] args) {
try {
throw new ValidationException("invalid input");
} catch (ValidationException error) {
System.out.println("validation: " + error.getMessage());
}
}
} class ValidationError(Exception):
pass
try:
raise ValidationError("invalid input")
except ValidationError as error:
print("validation:", error) A custom Python exception subclasses
Exception and often needs only pass, since the base class already stores the message. Python exceptions are all unchecked, like Java's RuntimeException family.Modules & Imports
Importing from the standard library
import java.util.UUID;
class Main {
public static void main(String[] args) {
UUID id = UUID.fromString("00000000-0000-0000-0000-000000000001");
System.out.println(id);
}
} import uuid
id = uuid.UUID("00000000-0000-0000-0000-000000000001")
print(id) Python imports a whole module (
import uuid) and accesses its members through the module name, rather than importing individual classes by fully-qualified package path as Java does.Importing across files
// Greetings.java
package util;
public class Greetings {
public static String hello(String name) { return "Hi, " + name; }
}
// Main.java
import util.Greetings;
class Main {
public static void main(String[] args) {
System.out.println(Greetings.hello("Alice"));
}
} # greetings.py
def hello(name):
return f"Hi, {name}"
# main.py
from greetings import hello
print(hello("Alice")) A Python module is just a
.py file — there is no package declaration, and every top-level name is importable with from greetings import hello. These examples span multiple files, so they cannot run in this single-file runner.