Vietnamese version

What is Python?

Python is an object-oriented programming language created by Guido van Rossum in 1989 (first public release in 1991). It is hugely popular and runs on many operating systems, including Windows, Linux, Ubuntu and macOS. Python is an interpreted language, so anyone can open a terminal and type Python commands directly. It is widely used in AI & Machine Learning, live streaming data processing, Big Data, mathematics, physics and many other scientific fields. Python complements Java; it cannot fully replace Java in the global IT market.

Learning Python quickly as a Java developer

Java developers can pick up Python fast by comparing it directly with Java and noting the similarities and differences. A cheat sheet is therefore the most efficient way to learn the basics. All examples below use Python 3 (3.10 or newer for match/case).

1. Setup & Running Code

TopicJavaPython
Run codejavac Main.java + java Mainpython3 main.py (interpreted, no compile step)
Interactive shelljshellpython3 (REPL)
Build / dependency toolMaven / Gradlepip + venv
Dependency filepom.xml / build.gradlerequirements.txt / pyproject.toml
Package repositoryMaven CentralPyPI

Create an isolated environment per project (similar to a per-project Maven .m2 setup):

python3 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install requests           # install a library
pip freeze > requirements.txt  # save the dependency list
pip install -r requirements.txt

2. Basic Syntax

2.1 End of statements

  • Java: every statement ends with a semicolon ;.
  • Python: no ; needed (a newline ends the statement). You may still use ; to put several statements on one line.

Printing:

LanguageExample
Java
System.out.println("Hello Blogger!");
Python
print("Hello Blogger!")

2.2 Program entry point

Python has no required main class. Code runs top to bottom; the __main__ guard makes a file usable both as a script and as an importable module.

LanguageExample
Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello Blogger!");
    }
}
Python
def main():
    print("Hello Blogger!")

if __name__ == "__main__":
    main()

2.3 Comments

LanguageExample
Java
// single-line comment
/* multi-line
   comment */
/** Javadoc comment */
Python
# single-line comment
"""
Docstring: documentation for a module, function or class
(Python's equivalent of Javadoc)
"""

2.4 Code blocks and indentation

  • Java: curly braces {} delimit blocks.
  • Python: indentation (4 spaces) defines blocks. Never mix tabs and spaces.
LanguageExample
Java
if (5 == value) {
    System.out.println("Value is five");
} else {
    System.out.println("Value is not five.");
}
Python
if 5 == value:
    print('Value is five')
else:
    print('Value is not five.')

2.5 Reading input

LanguageExample
Java
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int age = sc.nextInt();
Python
name = input("Name: ")        # always returns a string
age = int(input("Age: "))     # convert to int

3. Variables & Data Types

Python is dynamically typed: you do not declare a variable's type; the type belongs to the value, not the variable.

3.1 Declaring and assigning

LanguageExample
Java
int count = 27;
String name = "Anna";
final double PI = 3.14159;
Python
count = 27
name = "Anna"
PI = 3.14159   # constant by convention (UPPER_CASE); Python has no final
# Multiple assignment
a, b = False, True
a = b = c = 7
a, b, c = 3, 4, "mary"
a, b = b, a            # swap two variables

3.2 Checking and converting types

x = 10
print(type(x))             # <class 'int'>
x = "now a string"         # allowed: the same name can hold another type
print(isinstance(x, str))  # True  (Java: x instanceof String)

n = int("42")              # Integer.parseInt("42")
f = float("3.5")           # Double.parseDouble("3.5")
s = str(99)                # String.valueOf(99)

3.3 Numeric types

Python converts between numeric types automatically when needed.

TypeJavaPythonNotes
Integerint a = 27;a = 27Signed integer
Longlong a = 90210L;a = 90210Python 3 handles big integers automatically (no overflow)
Floatdouble a = 7.25;a = 7.25Floating point (64-bit, like Java double)
ComplexNot built ina = 2.5JComplex number

Division is different: in Java, 7 / 2 with two ints is 3. In Python 3, / always returns a float; use // for integer (floor) division.

print(7 / 2)      # 3.5
print(7 // 2)     # 3
print(-7 // 2)    # -4   (rounds down, not toward zero)
print(7 % 2)      # 1
print(2 ** 10)    # 1024
print(2 ** 100)   # 1267650600228229401496703205376

4. Strings

Strings can use single quotes '...', double quotes "...", or triple quotes """...""" for multi-line text. Like in Java, strings are immutable.

OperationJavaPython
Find positionstr.indexOf() / str.charAt()str.find() / str.index()
Lengthstr.length()len(str)
Replacestr.replace()str.replace()
Convert to stringString.valueOf() / toString()str()
Trim whitespacestr.trim()str.strip(), str.lstrip(), str.rstrip()
Comparestr1.equals(str2)str1 == str2
Substringstr.substring(0, 3)str[0:3]
Split / joinstr.split(",") / String.join("-", list)str.split(",") / "-".join(list)
Containsstr.contains("py")"py" in str
Upper / lowertoUpperCase() / toLowerCase()upper() / lower()
FormatString.format("%s is %d", n, a)f"{n} is {a}" (f-string)
name = "Python"
print(name[0])       # P
print(name[-1])      # n          (negative index counts from the end)
print(name[0:3])     # Pyt
print(name[::-1])    # nohtyP     (reverse)

age = 30
print(f"Hello {name}, next year you are {age + 1}")   # f-string: expressions inside {}

words = "a,b,c".split(",")     # ['a', 'b', 'c']
print("-".join(words))         # a-b-c
print("py" in "python")        # True
print(name.upper(), name.startswith("Py"))   # PYTHON True

text = """Line one
Line two"""                   # multi-line string (like Java text blocks)

5. Boolean, None & Falsy Values

Every object in Python has a Boolean value. The following evaluate to False:

  • None (equivalent to null in Java)
  • False
  • The number 0 (and 0.0)
  • Empty collections: "", (), [], {}, set()
Note: in Java null != false, but in Python None behaves as falsy in a Boolean context. Booleans are written True/False with a capital letter.
for v in [None, False, 0, "", [], {}, "0", [0]]:
    print(repr(v), bool(v))
# None False / False False / 0 False / '' False / [] False / {} False
# '0' True  / [0] True      (non-empty = True, even if it contains 0)

items = []
if not items:                  # idiomatic empty check
    print("Empty list")

result = None
if result is None:             # use "is" for None (Java: result == null)
    print("No result")

name = None
display = name or "Guest"      # default value, similar to Optional.orElse

6. Data Structures (Collections)

6.1 List (like Java's ArrayList)

A list is mutable and can hold elements of different types (heterogeneous).

A = []                      # empty list
B = [3, 14, 59, 26]         # list of 4 numbers
C = [8, 6, 'mary']          # mixed types
D = ["Z", B, C]             # list containing other lists

ArrayList (Java) vs List (Python):

OperationJava (ArrayList)Python (List)
CreateList<Object> list = new ArrayList<>();list = []
Addlist.add(obj);list.append(obj)
Insert at indexlist.add(i, obj);list.insert(i, obj)
Accesslist.get(i);list[i]
Removelist.remove(obj); / list.remove(i);list.remove(obj) / list.pop(i)
Lengthlist.size();len(list)
Containslist.contains(obj);obj in list
SortCollections.sort(list);list.sort() / sorted(list)
Copylist2 = list.clone();list2 = list[:] or list.copy()
nums = [3, 14, 59, 26]
nums.append(5)              # [3, 14, 59, 26, 5]
nums.insert(0, 1)           # [1, 3, 14, 59, 26, 5]
nums.remove(59)             # [1, 3, 14, 26, 5]
last = nums.pop()           # last = 5, nums = [1, 3, 14, 26]
print(nums[1:3])            # [3, 14]       (slice: index 1 up to, not including, 3)
nums.sort()                 # sorts in place
print(sorted(nums, reverse=True))   # [26, 14, 3, 1]   (returns a new list)
a, b, *rest = [1, 2, 3, 4]  # a=1, b=2, rest=[3, 4]  (unpacking)

6.2 Tuple (fixed / immutable list)

A tuple looks like a list but is immutable. It is used in place of a static array for better performance, to return several values, or as a dictionary key.

A = ()                      # empty tuple
B = (2, 71, 82, 8)          # tuple of 4 numbers
C = (9, 5, 'peter')         # heterogeneous tuple
D = ("Z", B, C)             # nested tuple
single = (42,)              # one element needs a trailing comma

x, y = (10, 20)             # unpacking
# B[0] = 99                 # TypeError: 'tuple' object does not support item assignment

6.3 Dictionary (like Java's HashMap)

A dictionary stores key: value pairs. Keys are unique and may be of different types. Since Python 3.7 a dict keeps insertion order (like Java's LinkedHashMap).

# Create
hotel_rooms = {'anna': 215, 'bob': 118}

# Add / update
hotel_rooms['anna'] = 507
hotel_rooms['linh'] = 402

# Get all keys
print(hotel_rooms.keys())

# Check whether a key exists
if 'linh' in hotel_rooms:
    print("Exists!")

print(hotel_rooms.get('zoe', 0))      # 0   (default instead of KeyError)
for name, room in hotel_rooms.items():  # iterate key + value
    print(name, room)

HashMap (Java) vs Dictionary (Python):

OperationJava (HashMap)Python (Dict)
CreateMap<K, V> map = new HashMap<>();my_dict = {}
Clearmap.clear();my_dict.clear()
Copymap.clone();my_dict.copy()
Check keymap.containsKey(key);key in my_dict
Get valuemap.get(key);my_dict.get(key) or my_dict[key]
Get keysmap.keySet();my_dict.keys()
Get valuesmap.values();my_dict.values()
Add / updatemap.put(key, value);my_dict[key] = value
Default if absentmap.getOrDefault(key, d);my_dict.get(key, d)
Removemap.remove(key);my_dict.pop(key)
Sizemap.size();len(my_dict)

6.4 Set (like Java's HashSet)

A set holds unique, unordered elements. Note that {} creates an empty dict; use set() for an empty set.

s = {1, 2, 3, 3, 2}         # {1, 2, 3}   (duplicates removed)
s.add(4)                    # HashSet.add
s.discard(1)                # HashSet.remove (no error if absent)
print(2 in s)               # True
a, b = {1, 2, 3}, {3, 4}
print(a | b)                # {1, 2, 3, 4}   union
print(a & b)                # {3}            intersection
print(a - b)                # {1, 2}         difference
unique = list(set([5, 1, 5, 2, 1]))   # remove duplicates from a list

6.5 Choosing the right collection

NeedJavaPython
Ordered, changeable sequenceArrayListlist
Fixed sequencearray / List.of()tuple
Key → value lookupHashMapdict
Unique elementsHashSetset
Queue / dequeArrayDequecollections.deque

7. Operators & Precedence

7.1 Arithmetic

JavaPythonDescription
None**Exponentiation
--Unary negation
**Multiplication
//Division (Python: always float)
None (int division by /)//Floor (integer) division
%%Modulus
+ / -+ / -Addition / subtraction
i++, i--i += 1, i -= 1Increment / decrement (++/-- do not exist in Python)

7.2 Logical & bitwise

JavaPythonDescription
!notLogical NOT
&&Bitwise AND
||Bitwise OR
^^Bitwise XOR
&&andLogical AND
||orLogical OR

7.3 Comparison

JavaPythonDescription
< / >< / >Less than / greater than
<= / >=<= / >=Less or equal / greater or equal
====Value equality (like Java's .equals())
!=!=Not equal
== (ref)isIdentity (same object in memory)
x = 5
print(1 < x < 10)                     # True   (chained comparison, not possible in Java)

a = [1, 2]
b = [1, 2]
print(a == b, a is b)                 # True False   (equal values, different objects)

age = 20
status = "adult" if age >= 18 else "minor"   # ternary: Java age >= 18 ? "adult" : "minor"

8. Conditionals

8.1 if - elif - else

Python writes else if as elif, and the condition needs no parentheses.

var1 = 20

if var1 <= 10:
    print("Case A: " + str(var1))
elif var1 == 20:
    print("Case B: " + str(var1))
elif var1 >= 30:
    print("Case C: " + str(var1))
else:
    print("Out of range!")
# Output: Case B: 20

8.2 Combining conditions

skill1 = "spring"
skill2 = "django"

# Both conditions are true
if skill1 == "spring" and skill2 == "django":
    print("Both conditions are met")

# At least one condition is true
if skill1 == "spring" or skill2 == "django":
    print("At least one condition is met")

if not (skill1 == "java"):
    print("Not java")

8.3 switch vs match (Python 3.10+)

LanguageExample
Java
switch (command) {
    case "start":
        System.out.println("Starting");
        break;
    case "stop":
    case "halt":
        System.out.println("Stopping");
        break;
    default:
        System.out.println("Unknown");
}
Python
match command:
    case "start":
        print("Starting")
    case "stop" | "halt":
        print("Stopping")
    case _:                 # default
        print("Unknown")

Python's match has no fall-through, so no break is needed.

9. Looping

9.1 for loop with range()

In Python, for is usually combined with range(start, stop, step) to iterate over indices. stop is exclusive.

# 2 to 7 (same as for(int x=2; x<8; x++) in Java)
for x in range(2, 8):
    print("Loop count: " + str(x))

# Custom step: from 20 down to 5, step -5
for x in range(20, 0, -5):
    print(x)            # 20 15 10 5

9.2 For-each over a collection

LanguageExample
Java
for (String s : names) {
    System.out.println(s);
}
Python
for s in names:
    print(s)
names = ["Anna", "Bob", "Linh"]
for i, name in enumerate(names):          # index + value
    print(i, name)                        # 0 Anna / 1 Bob / 2 Linh

ages = [30, 25, 28]
for name, age in zip(names, ages):        # iterate two lists together
    print(name, age)

9.3 while, break, continue, else

n = 0
while n < 5:
    n += 1
    if n == 2:
        continue          # skip this iteration
    if n == 4:
        break             # leave the loop
    print(n)              # 1 3

for x in range(3):
    pass
else:
    print("no break happened")   # loop-else: runs only if the loop was not broken

while True:                      # Python has no do-while: emulate it
    answer = input("Continue? ")
    if answer == "no":
        break

9.4 List comprehension vs Streams

A comprehension builds a new collection in one readable line, replacing many stream().filter().map().collect() chains.

LanguageExample
Java
List<Integer> squares = nums.stream()
    .filter(n -> n % 2 == 0)
    .map(n -> n * n)
    .collect(Collectors.toList());
Python
squares = [n * n for n in nums if n % 2 == 0]
nums = [1, 2, 3, 4, 5, 6]
print([n * n for n in nums if n % 2 == 0])        # [4, 16, 36]
print({n: n * n for n in nums})                   # {1: 1, 2: 4, 3: 9, ...}   (dict comprehension)
print({n % 3 for n in nums})                      # {0, 1, 2}                 (set comprehension)
print(sum(nums), max(nums), min(nums))            # 21 6 1
print(sorted(["bb", "a", "ccc"], key=len))        # ['a', 'bb', 'ccc']

10. Functions

Functions are defined with def. They do not need a return type, and they live outside classes. Python has no method overloading; use default and keyword arguments instead.

LanguageExample
Java
public static int add(int a, int b) {
    return a + b;
}
Python
def add(a, b):
    return a + b
def greet(name, greeting="Hello"):         # default argument
    return f"{greeting}, {name}!"

print(greet("Anna"))                       # Hello, Anna!
print(greet("Bob", greeting="Hi"))         # Hi, Bob!   (keyword argument)

def stats(values):
    return min(values), max(values), sum(values) / len(values)   # returns a tuple

lo, hi, avg = stats([3, 5, 10])            # lo=3, hi=10, avg=6.0

def total(*args, **kwargs):                # varargs (Java: int... args)
    print(args)                            # (1, 2, 3)
    print(kwargs)                          # {'unit': 'kg'}
    return sum(args)

total(1, 2, 3, unit="kg")

square = lambda x: x * x                   # lambda (Java: x -> x * x)
print(list(map(square, [1, 2, 3])))        # [1, 4, 9]

11. Classes & Object-Oriented Programming

11.1 Defining a class and inheritance

class Animal:
    species_count = 0                   # class attribute (Java: static field)

    def __init__(self, name):           # constructor
        self.name = name                # instance attribute
        Animal.species_count += 1

    def speak(self):
        return "..."

    def __str__(self):                  # Java: toString()
        return f"Animal({self.name})"

class Dog(Animal):                      # Java: class Dog extends Animal
    def __init__(self, name, breed):
        super().__init__(name)          # call the parent constructor
        self.breed = breed

    def speak(self):                    # override
        return "Woof!"

d = Dog("Rex", "Husky")                 # no "new" keyword
print(d)                                # Animal(Rex)
print(d.speak())                        # Woof!
print(isinstance(d, Animal))            # True

11.2 self vs this

  • In Java, an object refers to itself with this, which can be omitted implicitly when accessing fields.
  • In Python, self plays the same role, but it is mandatory: it must be the first parameter of every instance method and must be used to create or access instance attributes.
LanguageExample
Java
public void setColor(String color) {
    this.color = color;
}
Python
def set_color(self, color):
    self.color = color

11.3 Attributes, @property and access control

You can define attributes in __init__() and use the @property decorator to control access (the equivalent of a Java getter/setter):

class Car:
    def __init__(self, color, model, year):
        self.color = color
        self.model = model
        self.year = year
        self._voltage = 12

    @property
    def voltage(self):                  # getter
        return self._voltage

    @voltage.setter
    def voltage(self, value):           # setter with validation
        if value <= 0:
            raise ValueError("voltage must be positive")
        self._voltage = value

car = Car("red", "Model S", 2024)
print(car.voltage)                      # 12   (not car.getVoltage())
car.voltage = 24                        # calls the setter
  • Naming convention: a leading underscore (_voltage) signals an internal/protected attribute. Two underscores (__x) trigger name mangling. Python has no real private; it relies on convention.
  • @property decorator: works like a Java getter, letting you write car.voltage instead of car.getVoltage(), which is cleaner and more "Pythonic".

11.4 Static methods, class methods, abstract classes

from abc import ABC, abstractmethod

class MathUtil:
    @staticmethod
    def add(a, b):                      # Java: public static int add(...)
        return a + b

    @classmethod
    def create(cls):                    # receives the class itself (cls)
        return cls()

print(MathUtil.add(2, 3))               # 5

class Shape(ABC):                       # Java: abstract class / interface
    @abstractmethod
    def area(self): ...

class Square(Shape):
    def __init__(self, side):
        self.side = side
    def area(self):
        return self.side ** 2

print(Square(4).area())                 # 16
# Shape()                               # TypeError: cannot instantiate abstract class

11.5 Multiple inheritance

Python supports multiple inheritance directly in classes; Java does not (it only allows implementing multiple interfaces). Python resolves method lookup with the MRO (Method Resolution Order).

class Flyer:
    def move(self): return "fly"
class Swimmer:
    def move(self): return "swim"
class Duck(Flyer, Swimmer): pass

print(Duck().move())                    # fly   (Flyer comes first in the MRO)
print([k.__name__ for k in Duck.__mro__])   # ['Duck', 'Flyer', 'Swimmer', 'object']

12. Exception Handling

Python uses try / except / else / finally and raise. There are no checked exceptions: you never have to declare throws.

LanguageExample
Java
try {
    int v = Integer.parseInt("abc");
} catch (NumberFormatException e) {
    System.out.println("Invalid: " + e.getMessage());
} finally {
    System.out.println("done");
}
throw new IllegalArgumentException("bad input");
Python
try:
    v = int("abc")
except ValueError as e:
    print(f"Invalid: {e}")
else:
    print("no error")          # runs only if no exception
finally:
    print("done")

raise ValueError("bad input")
class InsufficientFundsError(Exception):      # custom exception
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(f"Need {amount - balance} more")
    return balance - amount

try:
    withdraw(100, 150)
except (InsufficientFundsError, TypeError) as e:   # catch several types
    print(e)                                       # Need 50 more

Java try-with-resources corresponds to Python's with statement, which closes the resource automatically (see section 14).

13. Modules & Packages

Every .py file is a module; a folder with __init__.py is a package. Imports are statements you can write anywhere, and they are not tied to folder-matching class names as in Java.

LanguageExample
Java
import java.util.List;
import java.time.LocalDate;
import static java.lang.Math.sqrt;
Python
import math
from datetime import date
from math import sqrt
import numpy as np      # alias
import math
from datetime import date

print(math.sqrt(16))        # 4.0
print(date.today().year)    # current year

# your own module: utils.py contains def hello(): ...
# from utils import hello

14. File I/O

The with statement guarantees the file is closed, even if an exception occurs.

LanguageExample
Java
Files.writeString(Path.of("data.txt"), "line 1\nline 2\n");
List<String> lines = Files.readAllLines(Path.of("data.txt"));
for (String line : lines) {
    System.out.println(line.trim());
}
Python
with open("data.txt", "w", encoding="utf-8") as f:
    f.write("line 1\nline 2\n")

with open("data.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())
import json
data = {"name": "Anna", "rooms": [215, 118]}
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f)                  # write JSON (like Jackson/Gson)
with open("data.json", encoding="utf-8") as f:
    print(json.load(f)["name"])         # Anna

15. Type Hints (optional)

Type hints document intent and help IDEs and tools like mypy, but Python does not enforce them at runtime.

def add(a: int, b: int) -> int:
    return a + b

names: list[str] = ["Anna", "Bob"]
ages: dict[str, int] = {"Anna": 30}
maybe: str | None = None                # like Optional<String>

print(add("a", "b"))                    # ab   (no error at runtime!)

16. Common Pitfalls for Java Developers

  • No ++/--: use i += 1.
  • == vs is: == compares values (like .equals()), is compares identity (like Java ==).
  • Integer division: / returns a float; use // for integers.
  • Forgetting self in method definitions and attribute access.
  • Indentation errors: mixing tabs and spaces causes IndentationError.
  • {} is an empty dict, not an empty set.
  • No block scope: variables created inside if/for remain visible afterwards.
  • No overloading: a second def with the same name replaces the first.

Mutable default arguments are created once and shared between calls:

def add_item(item, items=[]):           # BAD
    items.append(item)
    return items

print(add_item(1))                      # [1]
print(add_item(2))                      # [1, 2]   (surprise!)

def add_item_fixed(item, items=None):   # GOOD
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item_fixed(1))                # [1]
print(add_item_fixed(2))                # [2]

for i in range(3):
    pass
print(i)                                # 2   (i is still accessible)

17. Quick Java → Python Mapping

JavaPython
System.out.println(x)print(x)
nullNone
thisself
x instanceof Fooisinstance(x, Foo)
a.equals(b) / a == b (ref)a == b / a is b
Integer.parseInt(s)int(s)
String.format(...)f"...{x}..."
ArrayList / HashMap / HashSetlist / dict / set
Optional.orElse(d)x or d / x if x is not None else d
toString()__str__()
equals() / hashCode()__eq__() / __hash__()
static@staticmethod / @classmethod
interface / abstract classabc.ABC / typing.Protocol
try-with-resourceswith
Arrays.sort(a) / Collections.sort(l)l.sort() / sorted(l)
StringBuilderlist.append(...) + "".join(list)
stream().filter().map()list comprehension
Math.max(a, b)max(a, b)
finalUPPER_CASE convention
Maven / Gradlepip + venv
Java vs Python

Reference