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):
Java (compiled, class-based):
- Entry Point: Java requires a
public static void mainmethod 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):
Java (static typing):
- Primitives vs Objects: Use
int,double, etc., for primitives, and classes likeIntegerorDatefor objects. - Declaration: Specify the type before variable names (e.g.,
String name;). - More info here.
3. Control Structures
If-Else
Python:
Java:
More info here.
For Loop
Python:
Java:
More info here.
While Loop
Python:
Java:
More info here.
4. Functions vs Methods
Python (standalone functions):
Java (methods inside classes):
- Static Keyword: Use
staticfor methods called without object creation. - Return Type: Required in Java (use
voidif no return). - More info here.
5. Classes and Objects
Python:
Java:
- Constructor: Named after the class (no
__init__). thisKeyword: Refers to instance variables.- Access Modifiers: Use
public,private, etc., to control visibility. - More info here.
6. Arrays and Collections
Python (lists):
Java (arrays and ArrayList):
- Array Size: Fixed after creation.
- ArrayList: Similar to Python lists (use
import java.util.ArrayList). - More info here.
7. Common Tasks
Print Output
Python:
Java:
Read Input
Python:
Java:
8. Key Tips
- String Comparison: Use
.equals()instead of==(e.g.,str1.equals(str2)). - Null: Use
nullinstead of Python’sNone. - Comments:
// Single-lineor/* Multi-line */(vs Python’s#and"""). - Exception Handling: Use
try-catchblocks (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! 🚀