Java to Python
With the support of auto-completion and AI, syntax has become less critical, but you still need to understand the code.
I have compiled a comparison of Java and Python code to reinforce your understanding, as familiarity comes with exposure.
1. Declaration and Output
Java:
public class Main {
public static void main(String[] args) {
int x = 10;
String name = "Alice";
System.out.println("Hello, " + name + ", x=" + x);
}
}
Python:
x = 10
name = "Alice"
print(f"Hello, {name}, x={x}")
2. Conditional Statements
Java:
if (x > 5) {
System.out.println("Big");
} else {
System.out.println("Small");
}
Python:
if x > 5:
print("Big")
else:
print("Small")
3. Arrays
Java:
List<Integer> nums = new ArrayList<>();
nums.add(1); // Add element
nums.add(2);
System.out.println(nums.get(0));
Python:
nums = [1, 2]
nums.append(3) # Add element
print(nums[0])
4. Loops
Java:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Python:
for i in range(5):
print(i)
5. Functions
Java:
int add(int a, int b) {
return a + b;
}
Python:
def add(a, b):
return a + b
6. Dictionaries
Java:
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 20);
System.out.println(ages.get("Alice"));
Python:
ages = {"Alice": 20} # Similar to JSON
print(ages["Alice"]) # A bit odd
7. Objects
Java:
public class Person {
private String name;
public Person(String name) { this.name = name; }
public void sayHi() { System.out.println("Hi " + name); }
}
Person p = new Person("Tom");
p.sayHi();
Python:
class Person:
def __init__(self, name): # Constructor
self.name = name # Equivalent to this.name
def say_hi(self):
print("Hi", self.name)
p = Person("Tom")
p.say_hi()