🐍 Python vs ☕ Java — Ordered Beginner’s Guide with Keywords, and Examples
A single, ordered reference that covers core concepts, short plain-language explanations, highlighted keywords, and tiny code examples you can read at a glance.
1. 💬 Comments
Used to leave notes in code that the computer ignores.
Keywords: # (Python), // (Java)
Python
# this is a comment
Java
// this is a comment
2. 🔠 Indentation and Code Blocks
Indentation groups code in Python; curly braces {} do it in Java. Wrong indentation in Python changes behavior.
Keywords: indentation, { }
Python
def greet():
print("Hello") # indented block
Java
void greet() {
System.out.println("Hello"); // block inside { }
}
3. 🧾 Input Output and Taking Multiple Inputs
Get input from user and show output. Use .split() in Python for many values on one line; Java’s Scanner reads values one by one.
Keywords: input(), print(), Scanner, nextInt()
Python
x, y = input("Enter two values: ").split()
print(x, y)
Java
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
System.out.println(x + " " + y);
4. 🔁 Type Casting Conversions
Change data type (text → number, or double → int).
Keywords: int(), float(), Integer.parseInt(), Double.parseDouble(), (int)
Python
x = int("5") # "5" -> 5
d = float("3.14")
Java
int x = Integer.parseInt("5");
double d = Double.parseDouble("3.14");
int n = (int) 3.9; // cast
5. 📦 Variable Types and Basic Data Types
Where you store values. Python is dynamically typed; Java is statically typed.
Keywords: int, float, double, bool, boolean, str, String
Python
a = 5 # int
b = 3.14 # float
c = True # bool
s = "hi" # str
Java
int a = 5;
double b = 3.14;
boolean c = true;
String s = "hi";
6. ➕ Operators and Conditionals with Comparison Ops
Math and comparisons. Comparison operators: ==, !=, >, <, >=, <=. Logical: Python and/or/not, Java && / || / !.
Keywords: ==, !=, >, <, >=, <=, and, or, not, &&, ||, !
Python
if x == 5 and y != 0:
print("ok")
Java
if (x == 5 && y != 0) { System.out.println("ok"); }
7. 🗝️ Keywords Common Reserved Words
Short list to recognize everywhere.
Python examples: def, class, if, else, elif, import, return, pass, lambda, True, False, None.
Java examples: public, private, protected, static, void, class, if, else, return, new, final, abstract, extends, implements.
8. 🔍 Conditionals If Elif Else
Make decisions based on comparisons and logical operators.
Keywords: if, elif (Python), else if (Java), else
Python
if x > 0:
print("positive")
elif x == 0:
print("zero")
else:
print("negative")
Java
if (x > 0) {
System.out.println("positive");
} else if (x == 0) {
System.out.println("zero");
} else {
System.out.println("negative");
}
9. 🔂 Loops For While Nested Loops
Repeat actions. Use for for fixed iteration, while for condition loops. Nested loops are loops inside loops for grids or pairs.
Keywords: for, while, range, break, continue
Python
for i in range(3): print(i)
while x < 3: x += 1
# nested loop
for i in range(2):
for j in range(2):
print(i, j)
Java
for (int i=0;i<3;i++) System.out.println(i);
while (x<3) x++;
for (int i=0;i<2;i++) {
for (int j=0;j<2;j++) {
System.out.println(i + " " + j);
}
}
10. 🕳️ Pass Statement
Placeholder when code is syntactically required but you don’t want it to run yet.
Keywords: pass
def todo():
pass
(Java: use empty {} or comment)
11. 📦 Modules Packages Code Organization
Group code into files and folders for reuse.
Keywords: module, package, import, init.py
Python
# greet.py
def say_hi(): print("Hi")
import greet
greet.say_hi()
Java
package mypkg;
public class Greet { public static void sayHi(){ System.out.println("Hi"); } }
// use import mypkg.Greet;
12. 🧮 Functions Methods Arguments Multiple Arguments
Functions perform tasks; methods belong to classes. Python supports *args and **kwargs; Java supports varargs ....
Keywords: def, return, *args, **kwargs, void
Python
def greet(name): return "Hello " + name
def all_args(*args, **kwargs): print(args, kwargs)
Java
void greet(String name) { System.out.println("Hello " + name); }
void many(String... vals) { System.out.println(Arrays.toString(vals)); }
13. 🔁 Recursion Recursive Functions
A function calls itself to handle smaller parts of a problem; must have a base case.
Keywords: recursion, base case, return
Python
def fact(n):
return 1 if n == 0 else n * fact(n-1)
Java
int fact(int n) { return (n==0) ? 1 : n * fact(n-1); }
14. ⚡ Lambda Functions
Tiny anonymous functions for quick one-line operations.
Keywords: lambda, ->
Python
square = lambda x: x*x
print(square(3)) # 9
Java
Function<Integer,Integer> square = x -> x * x;
15. 🧭 map filter and Streams
Apply function to all items (map) or select items that pass a test (filter). Java Streams are similar.
Keywords: map, filter, stream, collect
Python
nums = [1,2,3]
print(list(map(lambda x:x*2, nums)))
print(list(filter(lambda x:x%2==0, nums)))
Java
List<Integer> doubled = nums.stream().map(x->x*2).collect(Collectors.toList());
16. 🧺 Data Structures
— Ways to store and organize collections of values
| Concept | Python (easy) | Java (similar) |
|---|---|---|
| List | list: [1,2,3] |
ArrayList |
| Tuple | tuple: (1,2,3) |
LinkedList (similar) |
| Dictionary | dict: {'a':1} |
HashMap |
| Set | set: {1,2,3} |
HashSet |
| Array |
array module |
int[], String[]
|
Examples:
Python
my_list = [1,2]
my_dict = {"a":1}
my_set = {1,2}
my_tuple = (1,2,3)
import array
arr = array.array('i', [1,2,3])
Java
List<Integer> list = Arrays.asList(1,2);
Map<String,Integer> map = new HashMap<>();
Set<Integer> set = new HashSet<>();
List<Integer> linked = new LinkedList<>(Arrays.asList(1,2,3));
int[] arr = new int[3];
String[] names = new String[] {"a","b"};
Keywords: list, tuple, dict, set, ArrayList, LinkedList, HashMap, HashSet, int[], String[].
17. 🐾 Classes, Objects, Constructor, Inheritance
🐾 Classes
Definition: A blueprint that describes the properties (data) and behaviors (methods) that objects created from the class will have.
Keywords: class, public/private/def (Python), class (Java)
Python (simple class):
class Animal:
species = "Unknown" # class variable
def __init__(self, name):
self.name = name # instance variable
def speak(self):
print(self.name + " makes a sound")
Java (simple class):
public class Animal {
public static String species = "Unknown"; // class variable
String name; // instance variable
public void speak() {
System.out.println(name + " makes a sound");
}
}
Notes:
- Classes group related data and functions.
- Class variables are shared by all instances; instance variables are per object.
🧱 Objects
Definition: A concrete instance created from a class. Objects hold their own data according to the class blueprint.
Keywords: instance, new (Java), object creation
Python (create object):
a = Animal("Buddy")
a.speak() # Buddy makes a sound
Java (create object):
Animal a = new Animal();
a.name = "Buddy";
a.speak(); // Buddy makes a sound
Notes:
- Multiple objects can be created from the same class; each has independent instance variables.
- Methods are called on objects to perform actions or access data.
🔧 Constructor
Definition: A special method that runs when an object is created; used to initialize instance variables.
Keywords: init (Python), constructor (Java, same name as class), new (Java object creation)
Python constructor:
class Animal:
def __init__(self, name, age=0): # __init__ is the constructor
self.name = name
self.age = age
Java constructor:
public class Animal {
String name;
int age;
public Animal(String name, int age) { // constructor
this.name = name;
this.age = age;
}
}
Notes:
- Constructors can be overloaded in Java (multiple constructors with different parameters).
- Python supports default parameter values instead of overloading.
🌱 Inheritance
Definition: A mechanism where a new class (child/subclass) derives properties and behaviors from an existing class (parent/superclass). This promotes code reuse and polymorphism.
Keywords: extends (Java), class Child(Parent): (Python), super(), @override (Java)
Python inheritance:
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal): # Dog inherits from Animal
def speak(self):
super().speak() # call parent method
print("Dog barks")
Java inheritance:
class Animal {
void speak() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
@Override
void speak() {
super.speak(); // call parent method
System.out.println("Dog barks");
}
}
Notes:
- Child classes get parent methods and fields by default.
- Use super() (Python/Java) to call the parent class constructor or methods.
- Java supports single inheritance for classes (interfaces allow multiple contracts); Python supports multiple inheritance.
18. 🔐 Encapsulation ✅ Access Modifiers
— Who can see or change class data
| Concept | Python (convention) | Java (keyword & meaning) |
|---|---|---|
| Public | No underscore; accessible everywhere | public — accessible from any class |
| Protected |
_name — single underscore (convention only) |
protected — accessible within package and subclasses |
| Private |
__name — double underscore (name mangling) |
private — accessible only inside the class |
| Package / Module | Module-level (no explicit keyword) — module encapsulation | (default, no keyword) — package-private when no modifier used |
| Final / Read-only | Use convention or property; no keyword to forbid reassignment | final — prevents reassignment (variable) or extension (class) |
Examples
Python
class Person:
name = "public" # public by convention
_secret = "protected" # protected by convention
__private = "private" # name-mangled (class-private)
@property
def private(self):
return self.__private
Java
public class Person {
public String name; // public
protected String secret; // protected
private String privateData; // private
String pkgData; // package-private (no modifier)
public final int ID = 1; // final (read-only)
}
Keywords: public, protected, private, final, (no modifier → package-private in Java; single _ and double __ are Python naming conventions).
19. 🧷 Static Methods and Class vs Instance Variables Examples
Static/class-level belongs to the class; instance-level belongs to each object.
Keywords: static, @staticmethod, class variable, instance variable
Python:
class Counter:
count = 0
def __init__(self): Counter.count += 1
@staticmethod
def info(): print("Counter class")
c1 = Counter(); c2 = Counter()
print(Counter.count) # 2
Counter.info()
Java:
class Counter {
static int count = 0;
Counter() { count++; }
static void info(){ System.out.println("Counter class"); }
}
new Counter(); new Counter();
System.out.println(Counter.count); // 2
Counter.info();
20. 🧱 Abstraction Abstract Classes Methods
Expose only what’s necessary and hide implementation. Python uses ABC, Java uses abstract.
Keywords: abstract, ABC, @abstractmethod
Python
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self): pass
Java
abstract class Animal { abstract void makeSound(); }
Abstract classes — simple explanation
- Python: use the abc module and make a class inherit ABC, mark required methods with @abstractmethod; subclasses must implement those methods or you get an error at runtime.
- Java: use the abstract keyword on a class or method; the compiler forces subclasses to implement abstract methods or be declared abstract themselves.
- Main practical difference: Python’s check happens at runtime and lets you mix multiple abstract bases; Java’s check happens at compile time and a class can extend only one other class (use interfaces for multiple contracts).
21. 🧩 Interfaces vs Protocols Examples
Define a required set of methods (contract). Java uses interface; Python can use Protocol or duck typing.
Keywords: interface, implements, Protocol, duck typing
Java:
interface Animal { void makeSound(); }
class Dog implements Animal { public void makeSound(){ System.out.println("Bark"); } }
Python:
from typing import Protocol
class Animal(Protocol):
def make_sound(self) -> None: ...
class Dog:
def make_sound(self) -> None: print("Bark")
None vs Ellipsis vs Return Nothing
| Concept | Python (meaning + short snippet) | Java (meaning + short snippet) | Keywords |
|---|---|---|---|
| None vs null | No value. Example: x = None; def f(): pass; print(f())
|
No reference. Example: String s = null; System.out.println(s);
|
None, null |
Ellipsis ...
|
Placeholder/stub. Example: def todo(): ...
|
No Ellipsis object; use empty body, exception, or abstract method: void todo() { } or abstract void call();
|
..., Ellipsis, abstract |
-> None vs void
|
Type hint: function returns nothing. Example: def greet() -> None: print("Hi")
|
Method returns nothing. Example: void greet() { System.out.println("Hi"); }
|
-> None, void |
None / null
Python — No value; functions without return return None
x = None
def f():
pass
print(x) # None
print(f()) # None
Java — No reference to an object; similar concept is null
String s = null;
void doNothing() { }
System.out.println(s); // prints "null"
Ellipsis ... (placeholder)
Python — Lightweight placeholder used in stubs or Protocols
def todo(): ...
class API:
def call(self) -> None: ...
Java — No Ellipsis object; common placeholder patterns
void todo() { } // empty method body
void notSupported() { throw new UnsupportedOperationException(); }
abstract class API { abstract void call(); } // contract without implementation
-> None (Python) vs void (Java)
Python — Type hint that the function returns nothing
def greet() -> None:
print("Hi")
def api_stub() -> None: ...
Java — Method signature that returns nothing
void greet() {
System.out.println("Hi");
}
abstract void apiStub(); // declaration with no implementation
Keywords recap: None, null, ..., Ellipsis, -> None, void, abstract.
22. 🦴 Polymorphism Overriding Overloading and super
Overloading: Same method name, different behavior. Use super() to call parent method. Java supports overloading; Python uses defaults or args.
Keywords: **override, **overload, *@override*, **super()*
Python Overriding:
class Parent:
def say(self): print("P")
class Child(Parent):
def say(self):
super().say()
print("C")
Child().say()
Java Overriding:
class Parent { void say(){ System.out.println("P"); } }
class Child extends Parent {
@Override void say(){ super.say(); System.out.println("C"); }
}
new Child().say();
Java overloading:
class Greet {
void greet() { System.out.println("Hi"); }
void greet(String name) { System.out.println("Hi " + name); }
}
23. 🔗 Pass by Value vs Reference
How arguments are passed to functions/methods. Mutability matters.
Keywords: mutable, immutable, primitive, reference
Python:
def change(l): l.append(4)
l=[1,2,3]; change(l); print(l) # [1,2,3,4]
Java:
void change(int x){ x = 10; } // caller unchanged
void add(List<Integer> l){ l.add(4); } // object modified
24. 📁 File Handling Read Write
Open, read, write files. Use with in Python to auto-close files. Java offers NIO Files.
Keywords: open, with, read, write, Files
Python:
with open("file.txt","w") as f:
f.write("Hello")
with open("file.txt","r") as f:
print(f.read())
Java:
Files.writeString(Path.of("file.txt"), "Hello");
String s = Files.readString(Path.of("file.txt"));
25. ❗ Exception Handling Try Except Finally
Catch and handle runtime errors so programs don’t crash.
Keywords: try, except, catch, finally, raise, throw
Python:
try:
x = int(input())
except ValueError:
print("Enter a number")
finally:
print("Done")
Java:
try {
int x = Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println("Not a number");
} finally {
System.out.println("Done");
}
Exceptions: raise (Python) vs throw / throws (Java)
| Concept | Python | Java | Keywords |
|---|---|---|---|
| Signal an error |
raise followed by an exception instance or class |
throw followed by an exception object |
raise, throw |
| Declare that a method may propagate exceptions | no declaration needed; any exception can be raised |
throws in method signature lists checked exceptions the method may pass on |
throws |
| Checked vs unchecked | no checked exceptions (runtime enforcement not required) | checked exceptions must be declared with throws or handled; unchecked (RuntimeException) need not be declared |
checked, unchecked |
Python — raise an exception and catch it
def f(x):
if x <= 0:
raise ValueError("x must be positive")
try:
f(0)
except ValueError as e:
print("Caught:", e)
Java — throw and declare checked exception with throws
void readFile(String path) throws IOException {
if (path == null) throw new IllegalArgumentException("path null");
// may throw IOException
}
try {
readFile(null);
} catch (IOException | IllegalArgumentException e) {
System.out.println("Caught: " + e);
}
Java — throwing an exception inside a method (checked vs unchecked)
void example() throws IOException { // declares possible checked exception
throw new IOException("disk error"); // must be declared or caught
}
void bad() {
throw new RuntimeException("oops"); // unchecked, no throws required
}
Keywords recap: raise, throw, throws, checked, unchecked.
26. 🔁 Iterators and Generators
| Concept | Python (meaning + short snippet) | Java (meaning + short snippet) | Keywords |
|---|---|---|---|
| Iterator | object you can get with iter() and advance with next(); example below |
implement Iterator<T> and use hasNext() / next(); example below |
iter, next, hasNext, Iterator |
| Generator | special iterator(subclass of iterator) created with yield, produces values lazily and saves memory
|
no direct language-level generator; use Iterator or Streams for lazy production |
yield, lazy, generator |
Python — Iterator
it = iter([1,2,3])
print(next(it)) # 1
print(next(it)) # 2
Python — Generator (lazy, memory-efficient)
def nums():
for i in range(3):
yield i
for n in nums():
print(n) # 0 1 2
Java — Iterator implementation and usage
import java.util.Iterator;
import java.util.NoSuchElementException;
class ArrayIterator<T> implements Iterator<T> {
private final T[] arr;
private int i = 0;
ArrayIterator(T[] arr) { this.arr = arr; }
public boolean hasNext() { return i < arr.length; }
public T next() {
if (!hasNext()) throw new NoSuchElementException();
return arr[i++];
}
}
// usage
Integer[] a = {1,2,3};
Iterator<Integer> it = new ArrayIterator<>(a);
while (it.hasNext()) System.out.println(it.next());
Java — lazy alternative using Stream
import java.util.stream.IntStream;
IntStream.range(0,3).forEach(System.out::println); // produces lazily
27. 🧠 Function Copy, Closures, Decorators
Functions are reusable blocks of code. Some languages treat functions as values you can store, pass, or return. Python makes this very easy; Java is more static but can achieve similar effects with objects, interfaces, and lambdas.
Function copying
- What it means: Making a reference to a function so you can call it later from another name or place.
- Python: Functions are values. Assigning a function to another name makes a copy of the reference, not a new function, and you can call it directly.
def greet(name):
return "Hi " + name
say = greet
print(say("Ana")) # Hi Ana
- Java: Before Java 8 you used objects implementing an interface. Since Java 8 you can use method references or lambdas stored in variables typed by functional interfaces.
import java.util.function.Function;
Function<String,String> greet = name -> "Hi " + name;
System.out.println(greet.apply("Ana")); // Hi Ana
Closures
- What a closure is: A function that "remembers" variables from the place where it was defined even after that place has finished running.
- Python: Closures are common and simple: an inner function captures outer variables.
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
c = make_counter()
print(c()) # 1
print(c()) # 2
Key idea: counter remembers count.
- Java: Lambdas and anonymous classes can capture effectively final variables from the surrounding scope. You cannot reassign captured local variables; to mimic mutable capture you use a holder object (array, AtomicInteger, or field).
import java.util.function.Supplier;
import java.util.concurrent.atomic.AtomicInteger;
Supplier<Integer> makeCounter() {
AtomicInteger count = new AtomicInteger(0);
return () -> count.incrementAndGet();
}
Supplier<Integer> c = makeCounter();
System.out.println(c.get()); // 1
System.out.println(c.get()); // 2
Decorators
- What a decorator is (simple): A wrapper that adds behavior to a function without changing its code.
-
Python (direct feature): Python has a built-in decorator syntax using
@. Decorators take a function and return a new function that adds behavior.
def shout(fn):
def wrapper(name):
return fn(name).upper()
return wrapper
@shout
def greet(name):
return "Hi " + name
print(greet("Ana")) # HI ANA
-
Java (no direct decorator syntax): Java uses patterns and language features to achieve the same goals:
- Use the Decorator design pattern: define an interface, concrete implementation, and decorator classes that wrap implementations.
- Use proxies (dynamic proxies) or annotations + AOP frameworks (Spring) to add behavior around method calls.
- Use higher-order functions (lambdas) and composition for simple function wrapping.
// Simple decorator pattern example
interface Greeter { String greet(String name); }
class BasicGreeter implements Greeter {
public String greet(String name) { return "Hi " + name; }
}
class ShoutDecorator implements Greeter {
private final Greeter inner;
ShoutDecorator(Greeter inner) { this.inner = inner; }
public String greet(String name) { return inner.greet(name).toUpperCase(); }
}
Greeter g = new ShoutDecorator(new BasicGreeter());
System.out.println(g.greet("Ana")); // HI ANA
Quick comparison table
| Concept | Python (how it feels) | Java (how to do it) |
|---|---|---|
| Function copying | Assign functions to variables; pass/return easily | Use functional interfaces, method references, or objects |
| Closures | Natural; inner functions capture outer vars and can mutate with nonlocal | Lambdas capture effectively final locals; use holder objects to mutate |
| Decorators | Native @decorator syntax; easy to wrap functions |
Use decorator pattern, proxies, or AOP; no built-in @ for functions |
28. 🧊 Final vs Immutable Examples
Prevent modification or reassignment.
Keywords: tuple, immutable, final
Python:
x = (1,2,3) # immutable tuple
Java:
final int x = 10; // cannot reassign
final class C {} // cannot extend
29. ❓ What does -> None Colon Ellipsis and void Mean
-
-> Noneindicates the function returns nothing (like Javavoid). -
...(ellipsis) is a placeholder used in Protocols or stubs for “no implementation here”. -
void(Java) means the method does not return a value. Keywords: -> None, ..., void
class Animal(Protocol):
def make_sound(self) -> None: ...
void greet() { System.out.println("Hi"); }
30. ✅ Quick Summary and Keywords to Remember
Python is concise and beginner-friendly; Java is explicit and structured. Practice small examples above and revisit keywords. Important keywords: def, class, return, if, else, for, while, try, except, lambda, @staticmethod, static, final, private, public, protected, interface, implements, extends, super(), with, yield, -> None, void.
31.🪄Magic methods
What they are: Python “magic” or dunder methods (names with double underscores) are built-in hooks that let objects behave like language primitives (construction, printing, arithmetic, iteration, context managers, callability, attribute interception). Java achieves the same behaviors with named methods, interfaces, wrapper classes, reflection, or language constructs.
| Concept | Python (magic) | Java equivalent / pattern | Quick note |
|---|---|---|---|
| Construction / allocation | new, init | Constructor; JVM allocation (no user new) | Python splits allocation and init; Java uses constructor only |
| Representation | repr, str | toString() | repr → developer; str → user-friendly |
| Equality / hashing | eq, hash | equals(Object), hashCode() | Implement both for collections/maps |
| Ordering | lt, gt, etc. | Comparable.compareTo(T) or Comparator | Python operator hooks vs Java interface |
| Arithmetic / operators | add, radd, sub, etc. | No operator overloading (except String +); provide add()/mul() methods | Python overloads operators; Java uses named methods |
| Length / size | len | size() / length | len(obj) → obj.len |
| Indexing / slicing | getitem, setitem | get(index) / set(index,val) on List or custom methods | Slicing needs custom methods in Java |
| Membership | contains | contains() on collections |
x in y → y.contains(x) |
| Iteration | iter, next (raise StopIteration) | Iterable and Iterator with hasNext()/next() | Python iterator protocol vs Java interfaces |
| Callable objects | call | Functional interfaces (Function, Supplier) or call()/apply() methods | Python instance()() vs Java lambda or method |
| Attribute access | getattr, setattr, delattr | Reflection, Map-backed fields, or Proxy (java.lang.reflect.Proxy) | Python dynamic attribute hooks; Java needs explicit mechanisms |
| Context management | enter, exit (with) | AutoCloseable + try-with-resources | with CM(): → try (CM cm = new CM()) { } |
| Decorator / wrapper | use wrapper functions and @decorator; wrappers often use call | Decorator design pattern: wrapper classes, proxies, or higher-order functions | Python has syntactic sugar (@); Java uses patterns |
Compact examples
- Representation / equality (Python)
class P:
def __init__(self,x): self.x = x
def __repr__(self): return f"P({self.x})"
def __eq__(self,other): return isinstance(other,P) and self.x == other.x
- Representation / equality (Java)
class P {
private final int x;
P(int x){ this.x = x; }
public String toString(){ return "P(" + x + ")"; }
public boolean equals(Object o){ return (o instanceof P) && ((P)o).x == this.x; }
public int hashCode(){ return Integer.hashCode(x); }
}
- Iteration (Python)
class Count:
def __init__(self,n): self.i=0; self.n=n
def __iter__(self): return self
def __next__(self):
if self.i>=self.n: raise StopIteration
v=self.i; self.i += 1; return v
for v in Count(3): print(v)
- Iteration (Java)
import java.util.Iterator;
class Count implements Iterator<Integer> {
private int i=0, n;
Count(int n){ this.n=n; }
public boolean hasNext(){ return i < n; }
public Integer next(){ return i++; }
}
- Context manager (Python)
class CM:
def __enter__(self): print("enter"); return self
def __exit__(self, exc_type, exc, tb): print("exit"); return False
with CM(): pass
- Try-with-resources (Java)
class CM implements AutoCloseable {
CM(){ System.out.println("enter"); }
public void close(){ System.out.println("exit"); }
}
try (CM cm = new CM()) { }
- Decorator / wrapper (Python)
def deco(fn):
def wrapper(*a,**k):
print("before"); r = fn(*a,**k); print("after"); return r
return wrapper
@deco
def say(): print("hi")
say()
- Decorator-like wrapping (Java)
import java.util.function.Supplier;
Supplier<Void> say = () -> { System.out.println("hi"); return null; };
Supplier<Void> wrapped = () -> {
System.out.println("before"); say.get(); System.out.println("after"); return null;
};
wrapped.get();
One-line takeaway
Python exposes uniform, language-level dunder hooks for operator and behavior customization; Java maps the same capabilities to named methods, interfaces, design patterns, reflection, or language constructs, but lacks general operator overloading and the uniform dunder dispatch.
Keywords: init, repr, str, add, eq, hash, len, getitem, iter, next, call, getattr, enter, exit, toString, equals, hashCode, Iterable, Iterator, AutoCloseable.
Top comments (0)