| 01 Language basicsValues, types, comparisons and common expressions. |
|---|
| Print a valueJava prints to System.out; Python uses the built-in print function. | System.out.println("Hello");
| print("Hello")
|
| Declare a variableJava local variables have static types; Python variables are names bound to objects. | int count = 3;
String name = "Ada";
| count = 3
name = "Ada"
|
| Single-line commentComments explain intent; good code still needs clear names. | // Explain why this is needed
| # Explain why this is needed
|
| Null / missing valueUse null / None for missing references, and explicit checks before dereferencing. | String value = null;
if (value == null) { /* ... */ }
| value = None
if value is None:
pass
|
| Boolean operators&& / || and and / or short-circuit evaluation. | a && b
a || b
!a
| a and b
a or b
not a
|
| Type inferenceJava var still has a fixed inferred type; Python names can be rebound to another type. | var n = 42; // inferred int
| n = 42
|
| Constant / conventionJava final restricts reassignment; Python uppercase is a naming convention. | static final int MAX = 100;
| MAX = 100
|
| Print without a newlineSystem.out.println / print() both add a newline by default. | System.out.print("Hello");
| print("Hello", end="")
|
| Read inputFor repeated Java input, reuse Scanner and manage its lifecycle. | var line = new Scanner(System.in).nextLine();
| line = input()
|
| Type at runtimeJava primitives are not objects; use class metadata for reference values. | obj.getClass().getName();
| type(obj).__name__
|
| Explicit type conversionInvalid input raises NumberFormatException or ValueError. | int n = Integer.parseInt("42");
| n = int("42")
|
| Logical equalityJava compares String values with equals(); == compares references. | "abc".equals(text)
| "abc" == text
|
| Non-empty checkPython considers empty sequences, sets and dictionaries false. | if (!items.isEmpty()) { /* ... */ }
| if items:
pass
|
| Standard entry pointJava fragment belongs inside a class; Python guard avoids running on import. | public static void main(String[] args) {
System.out.println("Ready");
}
| if __name__ == "__main__":
print("Ready")
|
| 02 Strings & numbersText processing, numeric conversion and regular expressions. |
|---|
| String formatting | String text = "Hi, %s".formatted(name);
| text = f"Hi, {name}"
|
| Read a string length | int size = name.length();
| size = len(name)
|
| Multiline textJava text blocks and Python triple-quoted literals have different indentation behavior. | String text = """
one
two
""";
| text = """one
two"""
|
| Trim surrounding spacesBoth remove leading and trailing whitespace. | String clean = text.strip();
| clean = text.strip()
|
| Split a stringJava String.split uses a regular expression; Python str.split uses a literal separator. | String[] parts = "a,b".split(",");
| parts = "a,b".split(",")
|
| Join a listElements must be strings. | String text = String.join(", ", names);
| text = ", ".join(names)
|
| Find a substringCase-sensitive by default. | boolean found = text.contains("cat");
| found = "cat" in text
|
| Replace textStrings are immutable in both languages. | String out = text.replace("a", "b");
| out = text.replace("a", "b")
|
| Substring / sliceEnd index is excluded in both examples. | String part = text.substring(1, 4);
| part = text[1:4]
|
| UppercaseLocale-sensitive casing differs; use the correct locale for user-facing text. | String upper = text.toUpperCase(Locale.ROOT);
| upper = text.upper()
|
| Round a numberTie-breaking rules differ: Python rounds ties to even. | long n = Math.round(3.6);
| n = round(3.6)
|
| Floor divisionJava / on ints truncates toward zero; Python // floors toward negative infinity. | int q = Math.floorDiv(-7, 2);
| q = -7 // 2
|
| Safe number parsingDecide explicitly how invalid input should be handled. | try { n = Integer.parseInt(value); }
catch (NumberFormatException e) { n = 0; }
| try:
n = int(value)
except ValueError:
n = 0
|
| Regular expression searchJava requires java.util.regex.Pattern; Python has the re module. | boolean ok = Pattern.compile("\\d+")
.matcher(text).find();
| import re
ok = re.search(r"\d+", text) is not None
|
| 03 CollectionsLists, sets, maps, streams and comprehensions. |
|---|
| Create a listAn ArrayList is mutable; a Python list is mutable as well. | List<String> names = new ArrayList<>();
| names = []
|
| Create a map / dictionaryHashMap and dict map keys to values; key requirements and iteration semantics differ. | Map<String, Integer> scores = new HashMap<>();
| scores = {}
|
| Create a setBoth keep distinct values, based on equality and hashing. | Set<String> tags = new HashSet<>();
| tags = set()
|
| Get a list elementBoth index from zero. | String first = names.get(0);
| first = names[0]
|
| Append to a listBoth modify the existing list. | names.add("Ada");
| names.append("Ada")
|
| Dictionary lookup with fallbackJava returns an int through unboxing; avoid unexpected null values. | int n = scores.getOrDefault("Ada", 0);
| n = scores.get("Ada", 0)
|
| Filter a listJava Stream.toList() returns an unmodifiable list; Python comprehension produces a mutable list. | var chosen = names.stream()
.filter(s -> s.startsWith("A"))
.toList();
| chosen = [s for s in names
if s.startswith("A")]
|
| Sort in placeChanges the original list. Both versions use natural ordering here. | names.sort(String::compareTo);
| names.sort()
|
| List sizeJava arrays use .length; collections use .size(). | int n = names.size();
| n = len(names)
|
| Last elementRequires a non-empty list. | String last = names.get(names.size() - 1);
| last = names[-1]
|
| Remove a list itemIn Java this removes the matching object; in Python it raises ValueError if absent. | names.remove("Ada");
| names.remove("Ada")
|
| List contains itemMembership is linear for ordinary lists. | boolean yes = names.contains("Ada");
| yes = "Ada" in names
|
| Copy a mutable listA shallow copy: nested objects are still shared. | List<String> copy = new ArrayList<>(names);
| copy = names.copy()
|
| Iterate map entriesJava entrySet gives key/value pairs; Python items() gives key/value tuples. | for (var entry : scores.entrySet()) {
System.out.println(entry.getKey());
}
| for key, value in scores.items():
print(key)
|
| Add to a setSet iteration order should not be relied on. | tags.add("java");
| tags.add("python")
|
| Sort into a new listJava Stream.toList returns an unmodifiable list; Python sorted returns a new list. | var sorted = names.stream().sorted().toList();
| ordered = sorted(names)
|
| Remove duplicates, keep orderAssumes items are hashable and comparable for equality. | var unique = new ArrayList<>(
new LinkedHashSet<>(names));
| unique = list(dict.fromkeys(names))
|
| Map valuesMaterializes a separate list. | var values = new ArrayList<>(scores.values());
| values = list(scores.values())
|
| Transform each itemJava uses Streams; Python commonly uses comprehensions. | var upper = names.stream()
.map(String::toUpperCase).toList();
| upper = [name.upper() for name in names]
|
| Sum numbersAssumes nums is a List<Integer> in Java. | int total = nums.stream()
.mapToInt(Integer::intValue).sum();
| total = sum(nums)
|
| Group by a propertyUses Collectors in Java and defaultdict in Python. | var grouped = names.stream().collect(
Collectors.groupingBy(String::length));
| from collections import defaultdict
grouped = defaultdict(list)
for name in names:
grouped[len(name)].append(name)
|
| 04 Control flowConditions, loops and short-circuit operations. |
|---|
| If / elseJava uses braces; Python uses indentation as syntax. | if (count > 0) {
System.out.println("yes");
} else {
System.out.println("no");
}
| if count > 0:
print("yes")
else:
print("no")
|
| For each itemJava enhanced for-loop and Python for-loop are both iterable-oriented. | for (String name : names) {
System.out.println(name);
}
| for name in names:
print(name)
|
| Repeat five timesBoth produce integers 0 through 4. | for (int i = 0; i < 5; i++) {
System.out.println(i);
}
| for i in range(5):
print(i)
|
| While loopUse a changing condition to avoid an accidental infinite loop. | while (count > 0) {
count--;
}
| while count > 0:
count -= 1
|
| Ternary expressionBoth choose between two expressions. | String label = count > 0 ? "yes" : "no";
| label = "yes" if count > 0 else "no"
|
| Break / continueBoth statements change the current loop flow. | for (int i = 0; i < 10; i++) {
if (i == 2) continue;
if (i == 5) break;
}
| for i in range(10):
if i == 2: continue
if i == 5: break
|
| Loop with indexEnumerate returns both index and element. | for (int i = 0; i < names.size(); i++) {
System.out.println(i + ": " + names.get(i));
}
| for i, name in enumerate(names):
print(i, name)
|
| Check two conditionsJava short-circuit operators use && and ||. | if (age >= 18 && active) {
allow();
}
| if age >= 18 and active:
allow()
|
| Switch / pattern matchPython match is structural pattern matching, not a general switch expression. | String label = switch (status) {
case 200 -> "ok";
case 404 -> "missing";
default -> "other";
};
| match status:
case 200: label = "ok"
case 404: label = "missing"
case _: label = "other"
|
| Iterate in reverseThe Java example uses indexes; Python reversed gives an iterator. | for (int i = names.size()-1; i >= 0; i--) {
System.out.println(names.get(i));
}
| for name in reversed(names):
print(name)
|
| Any item matchesStops once a match is found. | boolean any = names.stream()
.anyMatch(s -> s.startsWith("A"));
| any_match = any(s.startswith("A") for s in names)
|
| All items matchBoth return true on an empty input. | boolean all = names.stream()
.allMatch(s -> !s.isBlank());
| all_match = all(bool(s.strip()) for s in names)
|
| Iterate a numeric rangeUpper bound is excluded. | for (int i = 2; i < 10; i += 2) {
System.out.println(i);
}
| for i in range(2, 10, 2):
print(i)
|
| 05 Functions & typesDefinitions, lambdas, parameters and type annotations. |
|---|
| Define a functionJava method belongs inside a class; Python function can be module-level. | static int square(int x) {
return x * x;
}
| def square(x: int) -> int:
return x * x
|
| Anonymous functionBoth support short function-valued expressions; captures differ. | Function<Integer, Integer> twice =
x -> x * 2;
| twice = lambda x: x * 2
|
| Void / no return valuePython returns None implicitly when no return value is given. | static void greet(String name) {
System.out.println(name);
}
| def greet(name: str) -> None:
print(name)
|
| Optional parameter patternJava commonly uses overloads; Python supports default arguments. | static void greet(String name) {
greet(name, "Hi");
}
static void greet(String name, String prefix) {
System.out.println(prefix + name);
}
| def greet(name: str, prefix: str = "Hi"):
print(prefix + name)
|
| Variable number of argumentsJava varargs become an array; Python *args is a tuple. | static int add(int... values) {
return Arrays.stream(values).sum();
}
| def add(*values: int) -> int:
return sum(values)
|
| Function referencePython functions can be passed as objects; the loop is idiomatic for side effects. | names.forEach(System.out::println);
| for name in names:
print(name)
|
| Generic functionType hints in Python are not enforced at runtime by default. | static <T> T first(List<T> xs) {
return xs.get(0);
}
| from typing import TypeVar
T = TypeVar("T")
def first(xs: list[T]) -> T:
return xs[0]
|
| Nullable resultOptional is a Java wrapper; Python uses None and union annotations. | Optional<String> value = Optional.ofNullable(text);
| value: str | None = text
|
| Document a functionJavadoc vs Python docstrings. | /** Returns the square of x. */
static int square(int x) {
return x * x;
}
| def square(x: int) -> int:
"""Return the square of x."""
return x * x
|
| Higher-order functionJava often declares a functional interface type explicitly. | Function<String, Integer> length = String::length;
| length = len
|
| 06 Objects & classesRecords, properties, inheritance and object models. |
|---|
| Create an objectBoth create a Person instance with a constructor-like call. | Person person = new Person("Ada");
| person = Person("Ada")
|
| Simple classMinimal object model, not a full application. | class Person {
String name;
Person(String name) {
this.name = name;
}
}
| class Person:
def __init__(self, name):
self.name = name
|
| Immutable data carrierBoth are compact data models, but their generated methods and semantics differ. | record Point(int x, int y) {}
| from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
|
| Instance methodPython passes the instance as self; Java uses the implicit this. | class Person {
String name;
String greet() { return "Hi " + name; }
}
| class Person:
def greet(self):
return "Hi " + self.name
|
| InheritanceJava classes support single class inheritance; Python permits multiple bases. | class Dog extends Animal { }
| class Dog(Animal):
pass
|
| Interface / protocolPython Protocol describes structural typing for type checkers. | interface Named {
String name();
}
| from typing import Protocol
class Named(Protocol):
def name(self) -> str: ...
|
| Static methodA static method does not receive an instance. | class Tools {
static int twice(int x) { return 2 * x; }
}
| class Tools:
@staticmethod
def twice(x): return 2 * x
|
| Read-only propertyFragments assume an enclosing class and appropriate initialization. | private final String name;
public String getName() { return name; }
| @property
def name(self):
return self._name
|
| Check instance typeJava pattern binding needs a suitable language version; Python has dynamic checks. | if (obj instanceof String s) {
System.out.println(s.length());
}
| if isinstance(obj, str):
print(len(obj))
|
| EnumEnum members are strongly named; value handling differs. | enum Color { RED, GREEN }
| from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
|
| Equality for objectsIllustrative hooks only: implement meaningful equality and hash contracts. | @Override public boolean equals(Object other) {
return super.equals(other);
}
| def __eq__(self, other):
return NotImplemented
|
| String representationDiagnostic textual representations are language-specific. | @Override public String toString() {
return "Point(" + x + ", " + y + ")";
}
| def __repr__(self):
return f"Point({self.x}, {self.y})"
|
| 07 Errors & resourcesExceptions, cleanup, logging and safe resource handling. |
|---|
| Exception handlingCatch a specific error in production code when possible. | try {
riskyOperation();
} catch (Exception e) {
System.err.println(e.getMessage());
}
| try:
risky_operation()
except Exception as exc:
print(exc)
|
| Catch specific errorPrefer specific exception classes over broad catches. | try {
int n = Integer.parseInt(text);
} catch (NumberFormatException e) {
System.err.println("Invalid number");
}
| try:
n = int(text)
except ValueError:
print("Invalid number")
|
| Always run cleanupFinally runs even when an exception is thrown. | try {
work();
} finally {
cleanup();
}
| try:
work()
finally:
cleanup()
|
| Raise an exceptionChoose a suitable error type for the API contract. | throw new IllegalArgumentException("Bad input");
| raise ValueError("Bad input")
|
| Declare checked exceptionJava requires handling/declaring certain checked exceptions; Python does not. | static String load(Path p) throws IOException {
return Files.readString(p);
}
| def load(path):
return path.read_text(encoding="utf-8")
|
| Manage a resourceBoth close the resource when the block exits. | try (var reader = Files.newBufferedReader(path)) {
System.out.println(reader.readLine());
}
| with open(path, encoding="utf-8") as f:
print(f.readline())
|
| Assert an invariantAssertions can be disabled; do not use them for user-input validation. | assert count >= 0 : "Negative count";
| assert count >= 0, "Negative count"
|
| Log an errorConfigure a logging handler and level for real applications. | Logger.getLogger("app").warning("Check input");
| import logging
logging.warning("Check input")
|
| 08 Files & OSPaths, files, directories and system interfaces. |
|---|
| Read a UTF-8 text fileExample assumes a valid path and handles errors in surrounding code. | String text = Files.readString(
Path.of("notes.txt"));
| from pathlib import Path
text = Path("notes.txt").read_text(
encoding="utf-8")
|
| Write a UTF-8 text fileWill overwrite an existing file unless options are changed. | Files.writeString(
Path.of("notes.txt"), "Hello");
| from pathlib import Path
Path("notes.txt").write_text(
"Hello", encoding="utf-8")
|
| Program argumentsJava main args starts at index 0; Python sys.argv[0] is the script. | String firstArg = args[0]; // in main
| import sys
first_arg = sys.argv[1]
|
| Check file existsAssumes from pathlib import Path on the Python side. | boolean found = Files.exists(Path.of("a.txt"));
| found = Path("a.txt").exists()
|
| List directoryJava stream should be closed; both include files and directories. | try (var s = Files.list(Path.of("."))) {
s.forEach(System.out::println);
}
| from pathlib import Path
for path in Path(".").iterdir():
print(path)
|
| Create directoriesCreates missing parent directories. | Files.createDirectories(Path.of("data/logs"));
| Path("data/logs").mkdir(
parents=True, exist_ok=True)
|
| Read lines as a listBoth load the entire file into memory. | List<String> lines = Files.readAllLines(path);
| lines = path.read_text(
encoding="utf-8").splitlines()
|
| Read environment variableNever print secrets or commit them into source control. | String token = System.getenv("API_TOKEN");
| import os
token = os.getenv("API_TOKEN")
|
| Path constructionCross-platform paths avoid manual separators. | Path path = Path.of("data", "report.txt");
| from pathlib import Path
path = Path("data") / "report.txt"
|
| Run external commandUse argument arrays instead of shell string concatenation. | var p = new ProcessBuilder("git", "--version")
.inheritIO().start();
p.waitFor();
| import subprocess
subprocess.run(["git", "--version"], check=True)
|
| 09 Dates, JSON & HTTPStructured data and standard library utilities. |
|---|
| Current dateReads the current local date according to environment settings. | LocalDate today = LocalDate.now();
| from datetime import date
today = date.today()
|
| Current UTC timestampPrefer timezone-aware instants for logs and APIs. | Instant now = Instant.now();
| from datetime import datetime, timezone
now = datetime.now(timezone.utc)
|
| Parse ISO dateDate-only values have no timezone. | LocalDate day = LocalDate.parse("2026-11-13");
| from datetime import date
day = date.fromisoformat("2026-11-13")
|
| Format a dateIllustrates ISO 8601 date formatting. | String text = day.format(
DateTimeFormatter.ISO_LOCAL_DATE);
| text = day.isoformat()
|
| Sleep brieflyJava uses milliseconds; Python seconds. | Thread.sleep(1000);
| import time
time.sleep(1)
|
| Parse JSON textJava SE has no general built-in JSON object-mapper; Jackson is external. | // With Jackson dependency:
JsonNode data = mapper.readTree(json);
| import json
data = json.loads(text)
|
| Serialize JSONObject models and serializers differ. | // With Jackson dependency:
String json = mapper.writeValueAsString(obj);
| import json
text = json.dumps(obj)
|
| URL encode a parameterForms use different encoding conventions; choose based on URL component. | URLEncoder.encode(value, StandardCharsets.UTF_8);
| from urllib.parse import quote
encoded = quote(value, safe="")
|
| HTTP GET (text)Java imports java.net.http.*, java.net.URI; requests require internet when executed. | var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder(URI.create(url)).build();
var res = client.send(req, BodyHandlers.ofString());
| from urllib.request import urlopen
with urlopen(url, timeout=10) as resp:
text = resp.read().decode("utf-8")
|
| Create a UUIDRandom version-4 identifiers are not authentication secrets by themselves. | String id = UUID.randomUUID().toString();
| import uuid
id = str(uuid.uuid4())
|
| 10 ConcurrencyThreads, futures and asynchronous tasks. |
|---|
| Start background taskPython threads are useful for I/O; CPU parallelism is runtime-dependent. | new Thread(() -> work()).start();
| from threading import Thread
Thread(target=work).start()
|
| Create executorJava virtual threads are available in Java 21+; these are not equivalent concurrency models. | try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
pool.submit(() -> work());
}
| from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor() as pool:
future = pool.submit(work)
|
| Await a task resultBoth wait for completion and propagate exceptions. | int n = future.get();
| n = future.result()
|
| Create an async functionJava CompletableFuture differs from Python coroutine scheduling. | CompletableFuture<Integer> f =
CompletableFuture.supplyAsync(() -> 42);
| async def get_value():
return 42
|
| Await asynchronouslyPython await must be inside an async function; Java join blocks a thread. | int n = future.join();
| n = await get_value()
|
| Lock a critical sectionPython lock must be created first; Java uses any suitable lock object. | synchronized (lock) {
update();
}
| with lock:
update()
|
| 11 Build & toolingCommands for everyday development. |
|---|
| Display runtime versionTerminal commands, not source-language expressions. | java --version
| python3 --version
|
| Compile a source filePython normally executes source without a separate compilation step. | javac Main.java
| python3 -m py_compile main.py
|
| Run a programJava expects a compiled class or appropriate source launcher. | java Main
| python3 main.py
|
| Interactive shellInteractive REPLs for quick experiments. | jshell
| python3
|
| Create a new projectNot equivalent: Maven scaffolds a project; venv creates a Python environment. | mvn archetype:generate
| python3 -m venv .venv
|
| Install a packageJava dependencies are typically declared in Maven/Gradle files; example command inspects Maven tree. | mvn dependency:tree
| python3 -m pip install requests
|
| Run unit testsAssumes Maven test setup / Python unittest discovery. | mvn test
| python3 -m unittest
|
| Format codeBoth require installing the third-party formatters first. | google-java-format --replace Main.java
| python3 -m black main.py
|
| Generate API docsJavadoc generates docs; pydoc displays or serves module docs. | javadoc -d docs Main.java
| python3 -m pydoc math
|
| Check Java/Python versionsOn macOS multiple installations may coexist. | java --version
javac --version
| python3 --version
python3 -m pip --version
|