Skip to content

Python to Java Cheatsheet

Python to Java Syntax Cheatsheet

Python to Java Syntax Cheatsheet

Python Java
# Variable Declaration and Assignment
x = 10
y = 5.5
z = "Hello"
int x = 10;
double y = 5.5;
String z = "Hello";
# Function Definition
def add(a, b):
    return a + b
public int add(int a, int b) {
    return a + b;
}
# Function Calling
print(add(3, 5))
System.out.println(add(3, 5));
# Comments and Docstrings
# Single-line comment
"""
Multi-line
docstring
"""
// Single-line comment
/*
Multi-line
comment
*/
/**
Multi-line
JavaDoc comment
@param annotations_can_be_used
*/
# Conditionals
if x > 10:
    print("x is large")
elif x == 10:
    print("x is ten")
else:
    print("x is small")
if (x > 10) {
    System.out.println("x is large");
} else if (x == 10) {
    System.out.println("x is ten");
} else {
    System.out.println("x is small");
}
# Recursion
def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)
public int factorial(int n) {
    if (n == 1) return 1;
    return n * factorial(n - 1);
}
# For loop
for i in range(5):
    print(i)

# While loop
n = 0
while n < 5:
    print(n)
    n += 1
// For loop
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

// While loop
int n = 0;
while (n < 5) {
    System.out.println(n);
    n++;
}
# List declaration
my_list = [1, 2, 3, 4]

# Adding to a list
my_list.append(5)

# Accessing elements
first = my_list[0]
last = my_list[-1]
// List declaration
import java.util.ArrayList;
import java.util.List;

List myList = new ArrayList<>();
myList.add(1);
myList.add(2);
myList.add(3);
myList.add(4);

// Adding to a list
myList.add(5);

// Accessing elements
int first = myList.get(0);
int last = myList.get(myList.size() - 1);
# Dictionary declaration
my_dict = {"a": 1, "b": 2, "c": 3}

# Adding a key-value pair
my_dict["d"] = 4

# Accessing values
value = my_dict["a"]

# Iterating through keys and values
for key, val in my_dict.items():
    print(f"{key}: {val}")
// Dictionary declaration
import java.util.HashMap;
import java.util.Map;

Map myDict = new HashMap<>();
myDict.put("a", 1);
myDict.put("b", 2);
myDict.put("c", 3);

// Adding a key-value pair
myDict.put("d", 4);

// Accessing values
int value = myDict.get("a");

// Iterating through keys and values
for (Map.Entry entry : myDict.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}
# Tuple declaration
my_tuple = (1, 2, 3)

# Accessing elements
first = my_tuple[0]
last = my_tuple[-1]
// Tuple equivalent (use a class or array)
class Tuple {
    int first, second, third;

    Tuple(int first, int second, int third) {
        this.first = first;
        this.second = second;
        this.third = third;
    }
}

// Creating and accessing a tuple
Tuple myTuple = new Tuple(1, 2, 3);
int first = myTuple.first;
int last = myTuple.third;
# Static method in Python
class MyClass:
    @staticmethod
    def static_method():
        return "This is a static method"

# Calling the static method
result = MyClass.static_method()
// Static method in Java
class MyClass {
    public static String staticMethod() {
        return "This is a static method";
    }
}

// Calling the static method
String result = MyClass.staticMethod();
# Instance method in Python
class MyClass:
    def __init__(self, value):
        self.value = value

    def instance_method(self):
        return f"The value is {self.value}"

# Creating an instance and calling the instance method
obj = MyClass(42)
result = obj.instance_method()
// Instance method in Java
class MyClass {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }

    public String instanceMethod() {
        return "The value is " + value;
    }
}

// Creating an instance and calling the instance method
MyClass obj = new MyClass(42);
String result = obj.instanceMethod();
# Input and Output in Python
name = input("Enter your name: ")
print(f"Hello, {name}!")
// Input and Output in Java
import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
# File Input and Output in Python
# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, World!")

# Reading from a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
// File Input and Output in Java
import java.io.*;

try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
    writer.write("Hello, World!");
}

try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
    String content = reader.readLine();
    System.out.println(content);
}
# Randomizing in Python
import random

# Random integer
rand_int = random.randint(1, 10)

# Random float
rand_float = random.random()

print(f"Random int: {rand_int}, Random float: {rand_float}")
// Randomizing in Java
import java.util.Random;

Random random = new Random();

// Random integer
int randInt = random.nextInt(10) + 1;

// Random float
float randFloat = random.nextFloat();

System.out.println("Random int: " + randInt + ", Random float: " + randFloat);
# Regular Expressions in Python
import re

text = "Hello, 123 World!"
pattern = r"\d+"
matches = re.findall(pattern, text)
print(matches)
// Regular Expressions in Java
import java.util.regex.*;
import java.util.ArrayList;

String text = "Hello, 123 World!";
String pattern = "\\d+";
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher(text);

ArrayList matches = new ArrayList<>();
while (matcher.find()) {
    matches.add(matcher.group());
}
System.out.println(matches);
# f-string formatting in Python
name = "Alice"
age = 30
formatted = f"My name is {name} and I am {age} years old."
print(formatted)
// String formatting in Java
String name = "Alice";
int age = 30;
String formatted = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(formatted);
# Special methods in Python
class MyClass:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return f"MyClass with value {self.value}"

    def __eq__(self, other):
        if isinstance(other, MyClass):
            return self.value == other.value
        return False

# Creating instances
obj1 = MyClass(42)
obj2 = MyClass(42)

# Using special methods
print(obj1)                # Calls __str__
is_equal = obj1 == obj2    # Calls __eq__
// Equivalent in Java (toString and equals)
class MyClass {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "MyClass with value " + value;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        MyClass myClass = (MyClass) obj;
        return value == myClass.value;
    }
}

// Creating instances
MyClass obj1 = new MyClass(42);
MyClass obj2 = new MyClass(42);

// Using methods
System.out.println(obj1);             // Calls toString
boolean isEqual = obj1.equals(obj2);  // Calls equals
# Object Composition in Python
class Engine:
    def start(self):
        return "Engine started"

class Car:
    def __init__(self, engine):
        self.engine = engine

    def drive(self):
        return self.engine.start() + " and driving"

engine = Engine()
car = Car(engine)
print(car.drive())
// Object Composition in Java
class Engine {
    public String start() {
        return "Engine started";
    }
}

class Car {
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }

    public String drive() {
        return engine.start() + " and driving";
    }
}

Engine engine = new Engine();
Car car = new Car(engine);
System.out.println(car.drive());
# Interfaces in Python
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof"
// Interfaces in Java
interface Animal {
    String speak();
}

class Dog implements Animal {
    @Override
    public String speak() {
        return "Woof";
    }
}
# Abstract Classes in Python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height
// Abstract Classes in Java
abstract class Shape {
    abstract double area();
}

class Rectangle extends Shape {
    private double width, height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double area() {
        return width * height;
    }
}
# Polymorphism in Python
class Animal:
    def speak(self):
        return "Some sound"

class Dog(Animal):
    def speak(self):
        return "Woof"

animals = [Animal(), Dog()]
for animal in animals:
    print(animal.speak())
// Polymorphism in Java
class Animal {
    String speak() {
        return "Some sound";
    }
}

class Dog extends Animal {
    @Override
    String speak() {
        return "Woof";
    }
}

Animal[] animals = { new Animal(), new Dog() };
for (Animal animal : animals) {
    System.out.println(animal.speak());
}
Features in Python not in Java
  • Dynamic typing
  • List comprehensions
  • Duck typing
  • Built-in(s): slicing, defaultdict, etc.
  • Decorators
Features in Java not in Python
  • Static typing
  • Generics
  • Checked exceptions
  • Concurrency utilities (e.g., Executors)
  • Annotations