Java Vs Python
Java Vs Python
Java Python
public class HelloWorld { print("Hello, World!")
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Java Python
int age = 25; age = 25
double price = 9.99; price = 9.99
String name = "Alice"; name = "Alice"
boolean active = true; active = True
long big = 123456789L; big = 123456789 # no suffix needed
char ch = 'A'; ch = 'A' # just a str of len 1
// Type casting # Conversion
int x = (int) 3.7; x = int(3.7) # 3
String s = [Link](42); s = str(42)
# Optional type hint
age: int = 25
3. String Operations
■ f-strings (Python 3.6+) are the modern replacement for [Link](). Use them always.
Java Python
String a = "Hello"; a = "Hello"
String b = "World"; b = "World"
String c = a + " " + b; c = a + " " + b
String fmt = [Link]("Hi %s, age %d", a, 30); fmt = f"Hi {a}, age {30}"
[Link](); len(a)
[Link](); [Link]()
[Link](1, 3); a[1:3]
[Link]("ell"); "ell" in a
[Link]('l', 'r'); [Link]('l', 'r')
" hi ".trim(); " hi ".strip()
[Link](", ", "a","b","c"); ", ".join(["a","b","c"])
# Multi-line string
txt = """line 1
line 2"""
4. Conditionals
■ Indentation (4 spaces) replaces curly braces. 'elif' replaces 'else if'. No switch — use match (3.10+).
Java Python
int score = 85; score = 85
if (score >= 90) { if score >= 90:
[Link]("A"); print("A")
} else if (score >= 80) { elif score >= 80:
[Link]("B"); print("B")
} else { else:
[Link]("C"); print("C")
} # Ternary (conditional expression)
// Ternary r = "Pass" if score > 50 else "Fail"
String r = score > 50 ? "Pass" : "Fail"; # match-case (Python 3.10+)
// Switch (Java 14+) match score // 10:
String grade = switch(score/10) { case 10 | 9: print('A')
case 10,9 -> "A"; case 8: print('B')
case 8 -> "B"; case _: print('C')
default -> "C";
};
5. Loops
■ 'for x in iterable' covers most cases. enumerate() gives index+value. zip() pairs two lists.
Java Python
for (int i = 0; i < 5; i++) { for i in range(5):
[Link](i); print(i)
} nums = [10, 20, 30]
int[] nums = {10, 20, 30}; for n in nums:
for (int n : nums) { print(n)
[Link](n); # Index + value
} for i, n in enumerate(nums):
// Index + value print(f'{i}:{n}')
for (int i=0; i<[Link]; i++) { # Zip two lists
[Link](i+":"+nums[i]); names = ['a','b','c']
} for n, v in zip(names, nums):
// While print(n, v)
int i = 0; # While
while (i < 5) { i++; } i = 0
while i < 5:
i += 1
6. Arrays / Lists
■ Python lists are dynamic, mixed-type, and sliceable. List comprehensions replace stream().map().collect().
Java Python
int[] arr = {1,2,3,4,5}; lst = [1, 2, 3, 4, 5]
arr[0] = 10; lst[0] = 10
[Link]; len(lst)
ArrayList<Integer> list = new ArrayList<>(); [Link](6)
[Link](1); [Link](2); [Link](2) # removes value 2
[Link]([Link](2)); [Link](0) # removes by index
[Link](); [Link]()
[Link](list); [Link]()
[Link](list); # Slicing
// Streams (Java 8+) lst[1:3] # [2, 3]
List<Integer> sq = [Link]() lst[::-1] # reversed copy
.map(x -> x*x) lst[::2] # every 2nd element
.collect([Link]()); # List comprehension
sq = [x**2 for x in lst]
evens = [x for x in lst if x%2==0]
7. HashMap / Dictionary
■ Python dict preserves insertion order (3.7+). Dict comprehensions replace verbose Java stream collectors.
Java Python
HashMap<String,Integer> map = new HashMap<>(); scores = {"alice": 90, "bob": 85}
[Link]("alice", 90); scores["carol"] = 95
[Link]("bob", 85); s = scores["alice"]
int s = [Link]("alice"); [Link]("carl", 0) # safe default
[Link]("carl", 0); "bob" in scores
[Link]("bob"); del scores["bob"]
[Link]("bob"); len(scores)
[Link](); for key, val in [Link]():
for ([Link]<String,Integer> e : [Link]()) { print(f"{key}:{val}")
[Link]([Link]()+":"+[Link]()); # Dict comprehension
} doubled = {k:v*2 for k,v in [Link]()}
# Merge dicts (Python 3.9+)
merged = dict1 | dict2
8. Functions / Methods
■ Python supports default args, keyword args, *args, **kwargs — no overloading needed.
Java Python
public static int add(int a, int b) { def add(a, b):
return a + b; return a + b
} # Default arguments
// Overload for default def greet(name, msg="Hello"):
public static void greet(String name) { print(f"{msg}, {name}")
greet(name, "Hello"); # Keyword arguments
} greet(msg="Hi", name="Bob")
public static void greet(String n, String m) { # *args **kwargs
[Link](m+", "+n); def total(*nums):
} return sum(nums)
// Varargs def config(**opts):
public static int sum(int... nums) { print(opts) # {"k": "v"}
return [Link](nums).sum(); # Lambda
} sq = lambda x: x * x
// Lambda # Multiple return values
Function<Integer,Integer> sq = x -> x*x; def minmax(lst):
return min(lst), max(lst)
lo, hi = minmax([3,1,4,1,5])
Java Python
public class Animal { class Animal:
private String name; def __init__(self, name):
public Animal(String name) { self._name = name
[Link] = name; @property
} def name(self): return self._name
public String getName() { return name; } def speak(self):
public void speak() { print(f"{self._name} speaks")
[Link](name+" speaks");
class Dog(Animal):
}
def __init__(self, name):
}
super().__init__(name)
public class Dog extends Animal {
def speak(self): # override
public Dog(String name) { super(name); }
print("Woof!")
@Override
d = Dog("Rex")
public void speak() {
[Link]() # Woof!
[Link]("Woof!");
isinstance(d, Animal) # True
}
}
Dog d = new Dog("Rex");
[Link](); // Woof!
10. Interfaces / Abstract Classes
■ Python uses ABC (Abstract Base Class) to enforce interfaces. Duck typing also works without formal interfaces.
Java Python
// Interface from abc import ABC, abstractmethod
public interface Shape { # Abstract base class (like interface)
double area(); class Shape(ABC):
default String describe() { @abstractmethod
return "I am a shape"; def area(self): pass
} def describe(self):
} return "I am a shape"
// Abstract class # Concrete implementation
public abstract class Vehicle { class Circle(Shape):
protected int speed; def __init__(self, r):
public abstract void move(); self.r = r
public void stop() { def area(self):
[Link]("Stopped"); import math
} return [Link] * self.r ** 2
}
c = Circle(5)
public class Circle implements Shape { print([Link]())
double r;
public Circle(double r) { this.r = r; }
public double area() { return [Link]*r*r; }
}
Java Python
try { try:
int r = 10 / 0; r = 10 / 0
} catch (ArithmeticException e) { except ZeroDivisionError as e:
[Link]("Div error: "+[Link]()); print(f"Div error: {e}")
} catch (Exception e) { except Exception as e:
[Link]("Error: "+[Link]()); print(f"Error: {e}")
} finally { else:
[Link]("Done"); print("No error occurred")
} finally:
// Custom exception print("Done")
class MyException extends RuntimeException { # Custom exception
public MyException(String msg) { class MyError(Exception):
super(msg); def __init__(self, msg):
} super().__init__(msg)
} raise MyError("oops")
throw new MyException("oops"); # Catch multiple
except (TypeError, ValueError) as e:
Java Python
// HashSet # Set
Set<Integer> s = new s = {1, 2, 3}
HashSet<>([Link](1,2,3)); [Link](4); 2 in s; [Link](1)
[Link](4); [Link](2); [Link](1); # Set operations
// Set operations (manual) a = {1, 2, 3}; b = {2, 3, 4}
Set<Integer> a = new a | b # union {1,2,3,4}
HashSet<>([Link](1,2,3)); a & b # intersect {2,3}
Set<Integer> b = new a - b # difference {1}
HashSet<>([Link](2,3,4)); a ^ b # symmetric diff {1,4}
[Link](b); // intersection
# Tuple — immutable
// No built-in tuple point = (10, 20)
// Use record (Java 16+) x, y = point # unpack
record Point(int x, int y) {} print(point[0]) # 10
Point p = new Point(10, 20); # point[0] = 5 -> TypeError
# Named tuple
from collections import namedtuple
Point = namedtuple('Point', ['x','y'])
p = Point(10, 20); print(p.x)
Java Python
// Generic class from typing import TypeVar, Generic, List
public class Box<T> { T = TypeVar('T')
private T value; class Box(Generic[T]):
public Box(T value) { [Link] = value; } def __init__(self, value: T):
public T get() { return value; } [Link] = value
} def get(self) -> T:
Box<String> b = new Box<>("hello"); return [Link]
String v = [Link](); b: Box[str] = Box('hello')
// Generic method v: str = [Link]()
public <T> List<T> repeat(T item, int n) { # Type hints on functions
List<T> result = new ArrayList<>(); def repeat(item: T, n: int) -> List[T]:
for (int i=0; i<n; i++) [Link](item); return [item] * n
return result;
# Python 3.9+ built-in generics
}
def first(lst: list[int]) -> int:
return lst[0]
Java Python
// Iterable — implement Iterator interface # Generator function — uses yield
class Range implements Iterable<Integer> { def my_range(end):
private int end; cur = 0
public Range(int end) { [Link] = end; } while cur < end:
public Iterator<Integer> iterator() { yield cur
return new Iterator<>() { cur += 1
int cur = 0; for i in my_range(5):
public boolean hasNext() { print(i)
return cur < end; # Generator expression (lazy list comp)
} gen = (x**2 for x in range(1000000))
public Integer next() { return cur++; } next(gen) # 0 (computed on demand)
}; # itertools
} from itertools import islice, chain
} first5 = list(islice(gen, 5))
for (int i : new Range(5)) { ... } combined = chain([1,2], [3,4])
Java Python
// Java annotation import functools, time
@Override # Simple decorator
public void speak() { ... } def logger(func):
@Deprecated @[Link](func)
public void oldMethod() { ... } def wrapper(*args, **kwargs):
// Annotations don't add logic by default print(f'Calling {func.__name__}')
// Need frameworks (Spring, etc.) for behavior return func(*args, **kwargs)
@Autowired return wrapper
private MyService svc; @logger
@GetMapping("/hello") def greet(name):
public String hello() { print(f"Hello, {name}")
return "Hello"; # Built-in decorators
} class MyClass:
@staticmethod
def static_method(): ...
@classmethod
def class_method(cls): ...
@property
def name(self): return self._name
Java Python
import [Link]; # Standard library imports
import [Link]; import math
import [Link]; import os, sys
import [Link].*; from datetime import datetime
import [Link]; from collections import defaultdict, Counter
// Use in code from pathlib import Path
[Link](16); [Link](16)
// Maven dependency ([Link]) # Install third-party (like Maven)
<dependency> # pip install requests numpy pandas
<groupId>[Link]</groupId> import requests
<artifactId>gson</artifactId> import numpy as np
<version>2.10</version> import pandas as pd
</dependency> # Your own module ([Link])
from utils import my_function
# Conditional import
if __name__ == '__main__':
main()
Java Python
// try-with-resources (Java 7+) # with statement — auto cleanup
try (Connection conn = with open('[Link]') as f:
[Link](url); data = [Link]()
PreparedStatement stmt = [Link](sql)) # file closed here automatically
{ # Multiple context managers
ResultSet rs = [Link](); with open('[Link]') as fin, \
while ([Link]()) { ... } open('[Link]','w') as fout:
} // auto-closed [Link]([Link]())
// Implement AutoCloseable # Custom context manager
class MyResource implements AutoCloseable { class Timer:
public void close() { def __enter__(self):
[Link]("Closed"); import time
} [Link] = [Link]()
} return self
try (MyResource r = new MyResource()) { def __exit__(self, *args):
// use r print(f'{[Link]()-[Link]:.2f}s')
}
with Timer():
do_something()
Java Python
import [Link].*; import re
String text = "Phone: 123-456-7890"; text = "Phone: 123-456-7890"
Pattern p = [Link]("\\d{3}-\\d{3}-\\d{4}"); pattern = r'\d{3}-\d{3}-\d{4}'
Matcher m = [Link](text); # Search (first match)
// Find m = [Link](pattern, text)
if ([Link]()) { if m:
[Link]([Link]()); // 123-456-7890 print([Link]()) # 123-456-7890
} # Find all matches
// Replace all_nums = [Link](r'\d+', text)
String result = [Link]("\\d", "*"); # Replace
// Split result = [Link](r"\d", "*", text)
String[] parts = [Link]("\\s+"); # Split
parts = [Link](r"\s+", text)
# Compile for reuse
pat = [Link](r'\d+')
Java Python
// Java 16+ record (immutable) from dataclasses import dataclass, field
record Person(String name, int age) {} @dataclass
Person p = new Person("Alice", 30); class Person:
[Link]([Link]()); // Alice name: str
[Link](p); // Person[name=Alice, age=30] age: int
// Traditional class with boilerplate p = Person("Alice", 30)
public class Point { print([Link]) # Alice
private final int x, y; print(p) # Person(name='Alice', age=30)
public Point(int x, int y) { # With defaults & immutability
this.x = x; this.y = y; @dataclass(frozen=True) # immutable
} class Point:
// getters, equals, hashCode, toString... x: float
} y: float
tags: list = field(default_factory=list)
pt = Point(1.0, 2.0)
print(pt) # Point(x=1.0, y=2.0, tags=[])
Java Python
// Stack (use Deque) from collections import deque, Counter, defaultdict
Deque<Integer> stack = new ArrayDeque<>(); import heapq
[Link](1); [Link](2); # Stack — use a list
int top = [Link](); // 2 stack = []
int peek = [Link](); // 1 [Link](1); [Link](2)
// Queue top = [Link]() # 2
Queue<Integer> queue = new LinkedList<>(); # Queue — use deque
[Link](1); [Link](2); queue = deque()
int head = [Link](); // 1 [Link](1); [Link](2)
// Deque head = [Link]() # 1
Deque<Integer> dq = new ArrayDeque<>(); # Deque (both ends)
[Link](1); [Link](2); dq = deque([1,2,3])
[Link](); [Link](); [Link](0); [Link](4)
// PriorityQueue (Min-heap) # Counter (like frequency map)
PriorityQueue<Integer> pq = new PriorityQueue<>(); c = Counter("banana")
[Link](3); [Link](1); [Link](2); # Counter({'a':3,'n':2,'b':1})
[Link](); // 1 c.most_common(2)
# defaultdict
d = defaultdict(list)
d['key'].append(1) # no KeyError
# Min-heap
heap = [3,1,2]; [Link](heap)
[Link](heap, 0)
smallest = [Link](heap) # 0
Power of [Link](2, 8) 2 ** 8
Modulo 10 % 3 10 % 3
Tip: Drop semicolons, braces, and type declarations. Embrace list comprehensions, f-strings, and the 'with' statement.
Run python3 in your terminal to experiment interactively — the REPL is your best friend when learning Python!