From Python to Java
Transitioning from Python to Java: a Syntax Guide
This document helps Python programmers adapt to Java syntax by highlighting key differences and providing side-by-side examples.
1. Program Structure
Python (interpreted, loose structure):
# Standalone code
print("Hello, World!")
Java (compiled, class-based):
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
- Entry Point: Java requires a
public static void main
method inside a class. - Braces
{}
: Replace Python indentation with{}
to define code blocks. - Semicolons: End statements with
;
. - More info here.
2. Variables and Data Types
Python (dynamic typing):
x = 10 # int
y = 3.14 # float
name = "Alice" # str
is_valid = True # bool
Java (static typing):
int x = 10; // Primitive
double y = 3.14; // Primitive
String name = "Alice"; // Object
boolean is_valid = true; // Primitive
Integer boxedInt = Integer.valueOf(10); // Wrapper class
- Primitives vs Objects: Use
int
,double
, etc., for primitives, and classes likeInteger
orDate
for objects. - Declaration: Specify the type before variable names (e.g.,
String name;
). - More info here.
3. Control Structures
If-Else
Python:
if x > 5:
print("Large")
elif x == 5:
print("Medium")
else:
print("Small")
Java:
if (x > 5) {
System.out.println("Large");
} else if (x == 5) {
System.out.println("Medium");
} else {
System.out.println("Small");
}
More info here.
For Loop
Python:
for i in range(5):
print(i)
Java:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
More info here.
While Loop
Python:
while x < 5:
x += 1
Java:
while (x < 5) {
x++;
}
More info here.
4. Functions vs Methods
Python (standalone functions):
def add(a, b):
return a + b
Java (methods inside classes):
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
- Static Keyword: Use
static
for methods called without object creation. - Return Type: Required in Java (use
void
if no return). - More info here.
5. Classes and Objects
Python:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hi, I'm {self.name}.")
Java:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void greet() {
System.out.printf("Hi, I'm %s.\n", name);
}
}
- Constructor: Named after the class (no
__init__
). this
Keyword: Refers to instance variables.- Access Modifiers: Use
public
,private
, etc., to control visibility. - More info here.
6. Arrays and Collections
Python (lists):
nums = [1, 2, 3]
nums.append(4)
Java (arrays and ArrayList
):
int[] numsArray = {1, 2, 3}; // Fixed-size array
ArrayList<Integer> numsList = new ArrayList<>(); // Dynamic list
numsList.add(4);
- Array Size: Fixed after creation.
- ArrayList: Similar to Python lists (use
import java.util.ArrayList
). - More info here.
7. Common Tasks
Print Output
Python:
print("Value:", x)
Java:
System.out.println("Value: " + x);
Read Input
Python:
name = input("Enter name: ")
Java:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name: ");
String name = scanner.nextLine();
scanner.close();
8. Key Tips
- String Comparison: Use
.equals()
instead of==
(e.g.,str1.equals(str2)
). - Null: Use
null
instead of Python’sNone
. - Comments:
// Single-line
or/* Multi-line */
(vs Python’s#
and"""
). - Exception Handling: Use
try-catch
blocks (similar totry-except
).
Cheat Sheet Table
Concept | Python | Java |
---|---|---|
print("Hello") |
System.out.println("Hello"); |
|
Variable | x = 10 |
int x = 10; |
If Statement | if x > 5: |
if (x > 5) { ... } |
For Loop | for i in range(5): |
for (int i=0; i<5; i++) { ... } |
Function/Method | def add(a, b): |
public static int add(int a, int b) { ... } |
List/Array | nums = [1, 2, 3] |
int[] nums = {1, 2, 3}; or ArrayList<Integer> |
Class | class Person: |
public class Person { ... } |
Constructor | def __init__(self): |
public ClassName() { ... } |
Happy coding! 🚀