[Go to site: main page, start]

0% found this document useful (0 votes)
2 views16 pages

Java Vs Python

This document provides a comprehensive comparison between Java and Python across 25 programming topics, including syntax, data types, control structures, and object-oriented programming. It highlights key differences and similarities in code structure, variable handling, and language features. The document serves as a reference guide for Java developers transitioning to Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Java Vs Python

This document provides a comprehensive comparison between Java and Python across 25 programming topics, including syntax, data types, control structures, and object-oriented programming. It highlights key differences and similarities in code structure, variable handling, and language features. The document serves as a reference guide for Java developers transitioning to Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A Complete Side-by-Side 25 topics • Syntax • OOP •

Reference for Java Developers Functional • Concurrency •


Java vs Learning Python Modern Features
Python
1. Hello World
■ Python needs no class wrapper or main method — the script IS the entry point.

Java Python
public class HelloWorld { print("Hello, World!")
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

2. Variables & Data Types


■ Python is dynamically typed — no declarations. Use type hints optionally for clarity.

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])

9. Classes & OOP


■ 'self' is Python's 'this'. Use @property for getters. _ prefix = convention for private.

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; }
}

11. Exception Handling


■ 'except' replaces 'catch'. Python exceptions are unchecked — no checked exception declarations.

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:

12. File I/O


■ 'with open(...)' auto-closes the file — equivalent to Java's try-with-resources.
Java Python
// Write # Write
try (FileWriter fw = new FileWriter("[Link]")) { with open('[Link]', 'w') as f:
[Link]("Hello\n"); [Link]('Hello\n')
} catch (IOException e) { [Link](); } # Read line by line
// Read line by line with open('[Link]', 'r') as f:
try (BufferedReader br = for line in f:
new BufferedReader(new FileReader("[Link]"))) { print([Link]())
String line; # Read all at once
while ((line = [Link]()) != null) { with open('[Link]') as f:
[Link](line); content = [Link]()
} # Read all lines to list
} catch (IOException e) { [Link](); } with open('[Link]') as f:
lines = [Link]()
# Append mode
with open('[Link]', 'a') as f:
[Link]('more\n')
13. Sets & Tuples
■ Tuples are immutable lists (great for coordinates, records). Sets support union/intersection natively.

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)

14. Generics / Type Hints


■ Python type hints are optional and not enforced at runtime — use mypy for static checking.

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]

15. Functional Programming


■ map(), filter(), reduce() mirror Java streams. List comprehensions are often more Pythonic.
Java Python
List<Integer> nums = [Link](1,2,3,4,5); nums = [1, 2, 3, 4, 5]
// map # map
List<Integer> sq = [Link]() sq = list(map(lambda x: x*x, nums))
.map(x -> x*x) sq = [x**2 for x in nums] # preferred
.collect([Link]()); # filter
// filter evens = list(filter(lambda x: x%2==0, nums))
List<Integer> evens = [Link]() evens = [x for x in nums if x%2==0]
.filter(x -> x%2 == 0) # reduce
.collect([Link]()); from functools import reduce
// reduce total = reduce(lambda a,b: a+b, nums)
int total = [Link]() total = sum(nums) # simpler
.reduce(0, Integer::sum); # sorted
// sorted srt = sorted(nums, reverse=True)
List<Integer> sorted = [Link]() # chained comprehension
.sorted([Link]()) flat = [x for row in matrix for x in row]
.collect([Link]());
16. Iterators & Generators
■ Python generators (yield) are lazy sequences — extremely memory-efficient for large data.

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])

17. Decorators / Annotations


■ Python decorators wrap functions — similar in concept to Java annotations + AOP, but much simpler.

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

18. Concurrency / Threading


■ Python's GIL limits CPU threading — use multiprocessing for CPU tasks, asyncio for I/O tasks.
Java Python
// Thread import threading, [Link]
Thread t = new Thread(() -> { # Thread
[Link]("Running"); def task():
}); print("Running")
[Link](); [Link](); t = [Link](target=task)
// ExecutorService [Link](); [Link]()
ExecutorService pool = # ThreadPoolExecutor
[Link](4); with [Link](4) as
Future<Integer> f = [Link](() -> 42); pool:
int result = [Link](); future = [Link](lambda: 42)
[Link](); result = [Link]()
# asyncio (I/O concurrency)
import asyncio
async def fetch():
await [Link](1)
return "done"
[Link](fetch())
19. Modules & Imports
■ Every .py file is a module. Use 'pip install' for third-party packages (like Maven/Gradle).

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()

20. Context Managers (try-with-resources)


■ 'with' statement is Python's try-with-resources. Implement __enter__/__exit__ for custom ones.

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()

21. JSON Handling


■ Python's built-in 'json' module handles most cases. No external library needed for basic JSON.
Java Python
// Requires Gson or Jackson library import json
import [Link]; # Dict to JSON string
// Object to JSON string data = {"name": "Alice", "age": 30}
Gson gson = new Gson(); json_str = [Link](data)
String json = [Link](myObject); # '{"name": "Alice", "age": 30}'
// JSON string to Object # Pretty print
MyClass obj = [Link](json, [Link]); print([Link](data, indent=2))
// Jackson # JSON string to dict
ObjectMapper mapper = new ObjectMapper(); parsed = [Link](json_str)
String json = [Link](obj); print(parsed["name"]) # Alice
MyClass obj = [Link](json, [Link]); # Read/write JSON file
with open('[Link]','w') as f:
[Link](data, f, indent=2)
with open('[Link]') as f:
loaded = [Link](f)
22. Regular Expressions
■ Python's 're' module API is simpler than Java's Pattern/Matcher pair.

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+')

23. Dataclasses / Records


■ @dataclass auto-generates __init__, __repr__, __eq__ — like Java records but more flexible.

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=[])

24. Unit Testing


■ pytest (third-party) is preferred over unittest in modern Python — simpler syntax, powerful fixtures.
Java Python
// JUnit 5 # pytest (pip install pytest)
import [Link].*; def add(a, b): return a + b
import static [Link].*; def test_add():
class CalculatorTest { assert add(2, 3) == 5
Calculator calc = new Calculator(); def test_add_negative():
@Test assert add(-1, 1) == 0
void testAdd() { # Test exception
assertEquals(5, [Link](2, 3)); import pytest
} def test_div_by_zero():
@Test with [Link](ZeroDivisionError):
void testDivByZero() { 1 / 0
assertThrows([Link], # unittest (built-in)
() -> [Link](1, 0)); import unittest
} class TestCalc([Link]):
} def test_add(self):
[Link](add(2,3), 5)
# Run: python -m pytest or pytest
25. Collections — Stack, Queue, Deque
■ Python's collections module provides deque, Counter, defaultdict — all faster than plain dict/list.

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

. Quick Cheat-Sheet — Syntax at a Glance


Concept Java Python

Print [Link](x) print(x)

String format [Link]("%d", n) f"{n}"

Null / None null None

Null check x == null x is None

Boolean true / false True / False

Logical AND/OR && / || and / or

Logical NOT !x not x

Array length [Link] len(arr)

Power of [Link](2, 8) 2 ** 8

Integer division 10 / 3 (int) = 3 10 // 3 = 3

Modulo 10 % 3 10 % 3

Type check x instanceof String isinstance(x, str)

String to int [Link](s) int(s)

Int to string [Link](n) str(n)

Max / Min [Link](a,b) / [Link] max(a,b) / min(a,b)

Abs value [Link](x) abs(x)

Floor/Ceil [Link] / [Link] [Link] / [Link]


Concept Java Python

Random [Link]() import random; [Link]()

Ternary x > 0 ? "yes" : "no" "yes" if x > 0 else "no"

For-each for (T x : list) for x in lst:

List to array [Link]() (list is already dynamic)

Multiline string "+\n+" """..."""

Main entry public static void main() if __name__ == '__main__':

Print type [Link]() type(x)

String contains [Link]("ab") "ab" in s

List contains [Link](x) x in lst

Throw/Raise throw new Exception() raise Exception()

Sleep [Link](1000) [Link](1)

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!

You might also like