[Go to site: main page, start]

0% found this document useful (0 votes)
7 views7 pages

Java Vs Python

This document provides a comprehensive comparison between Java and Python, highlighting key differences in syntax, data structures, object-oriented programming, and error handling. It covers various programming concepts such as variables, conditionals, loops, functions, and file I/O, illustrating how each language approaches these topics. The guide serves as a quick reference for Java developers transitioning to Python, emphasizing Python's simplicity and readability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Java Vs Python

This document provides a comprehensive comparison between Java and Python, highlighting key differences in syntax, data structures, object-oriented programming, and error handling. It covers various programming concepts such as variables, conditionals, loops, functions, and file I/O, illustrating how each language approaches these topics. The guide serves as a quick reference for Java developers transitioning to Python, emphasizing Python's simplicity and readability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A Side-by-Side Guide for Core concepts • Syntax •

Java Developers Learning Data structures • OOP • File


Java vs Python I/O • Error handling
Python

1. Hello World
■ Python needs no class wrapper or main method — the script itself is the entry point.

Java Python
public class HelloWorld { print("Hello, World!")
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

2. Variables & Data Types


■ Python is dynamically typed — no type declarations needed. Types are inferred at runtime.

Java Python
// Static typing — declare type explicitly # Dynamic typing — Python infers the type
int age = 25; age = 25
double price = 9.99; price = 9.99
String name = "Alice"; name = "Alice"
boolean isActive = true; is_active = True

// Type casting # Type conversion


int x = (int) 3.7; // x = 3 x = int(3.7) # x = 3
String s = [Link](42); s = str(42)

# Check type
print(type(age)) # <class 'int'>

3. String Operations
■ Python f-strings (f'...') are the modern equivalent of [Link]() — clean and readable.
Java Python
String first = "Java"; first = "Python"
String last = "Developer"; last = "Developer"

// Concatenation # Concatenation
String full = first + " " + last; full = first + " " + last

// [Link] # f-string (preferred)


String msg = [Link]( msg = f"Hello, {full}! Age: {30}"
"Hello, %s! Age: %d", full, 30); # Common methods
// Common methods len(first)
[Link](); [Link]()
[Link](); first[0:2] # slice
[Link](0, 2); "av" in first
[Link]("av"); " hi ".strip()
" hi ".strip();

4. Conditionals
■ Python uses indentation (4 spaces) instead of curly braces. 'elif' replaces 'else if'.

Java Python
int score = 85; score = 85

if (score >= 90) { if score >= 90:


[Link]("A"); print("A")
} else if (score >= 80) { elif score >= 80:
[Link]("B"); print("B")
} else { else:
[Link]("C"); print("C")
} # Ternary (conditional expression)
// Ternary r = "Pass" if score > 50 else "Fail"
String r = (score > 50) ? "Pass" : "Fail";

5. Loops
■ 'for x in collection' is Python's for-each. Use range() to get an index-based loop.

Java Python
// For loop # for with range
for (int i = 0; i < 5; i++) { for i in range(5):
[Link](i); print(i)
} # for-each over a list
// Enhanced for-each nums = [1, 2, 3]
int[] nums = {1, 2, 3}; for n in nums:
for (int n : nums) { print(n)
[Link](n); # enumerate — index + value
} for i, n in enumerate(nums):
// While print(i, n)
int i = 0; # while
while (i < 5) { i++; } i = 0
while i < 5:
i += 1
6. Arrays / Lists
■ Python lists are dynamic (no fixed size), can hold mixed types, and have powerful slicing.

Java Python
// Fixed-size array # Python list (dynamic)
int[] arr = {1, 2, 3, 4, 5}; lst = [1, 2, 3, 4, 5]
arr[0] = 10; lst[0] = 10
[Link]; len(lst)

// ArrayList (dynamic) [Link](6)


ArrayList<Integer> list = new ArrayList<>(); [Link](3) # removes value 3
[Link](1); [Link](0) # removes index 0
[Link](2); [Link]()
[Link](0); # Slicing
[Link](); lst[1:3] # [2, 3]
[Link](list); lst[::-1] # reversed

# List comprehension
squares = [x**2 for x in range(5)]

7. HashMap / Dictionary
■ Python's dict is a first-class citizen — lighter syntax than Java's HashMap.

Java Python
HashMap<String,Integer> map scores = {"alice": 90, "bob": 85}
= new HashMap<>(); # Access
[Link]("alice", 90); s = scores["alice"]
[Link]("bob", 85); has = "bob" in scores
// Access del scores["bob"]
int s = [Link]("alice"); # Safe access
boolean has = [Link]("bob"); [Link]("carol", 0) # default 0
[Link]("bob"); # Iterate
// Iterate for key, val in [Link]():
for ([Link]<String,Integer> e print(f"{key}:{val}")
: [Link]()) { # Dict comprehension
[Link]( doubled = {k: v*2 for k,v in [Link]()}
[Link]() + ":" + [Link]());
}
8. Functions / Methods
■ Python supports default arguments and keyword arguments natively — no overloading needed.

Java Python
// Return type declared explicitly # No return type needed
public static int add(int a, int b) { def add(a, b):
return a + b; return a + b
} # Default arguments
// Overloading for defaults def greet(name, msg="Hello"):
public static void greet(String name) { print(f"{msg}, {name}")
greet(name, "Hello"); # Keyword arguments
} greet(msg="Hi", name="Bob")
public static void greet( # Variable args
String name, String msg) { def total(*nums):
[Link](msg+", "+name); return sum(nums)
}
# Lambda
// Lambda sq = lambda x: x * x
Function<Integer,Integer> sq = x -> x*x;

9. Classes & OOP


■ Python uses 'self' instead of 'this'. No access modifiers — _ prefix is convention for private.

Java Python
public class Animal { class Animal:
private String name; def __init__(self, name, age):
private int age; self._name = name # 'private'

public Animal(String name, int age) { self._age = age

[Link] = name; @property


[Link] = age; def name(self): return self._name
} def speak(self):
public String getName() { return name; } print(f"{self._name} speaks")

public void speak() { # Inheritance


[Link](name + " speaks"); class Dog(Animal):
} def __init__(self, name, age):
} super().__init__(name, age)
// Inheritance def speak(self): # override
public class Dog extends Animal { print("Woof!")
public Dog(String name, int age) { # Usage
super(name, age); dog = Dog("Rex", 3)
} [Link]() # Woof!
@Override
public void speak() {
[Link]("Woof!");
}
}

10. Exception Handling


■ Python uses 'except' (not 'catch') and 'finally' works the same way.

Java Python
try { try:
int result = 10 / 0; result = 10 / 0
} catch (ArithmeticException e) { except ZeroDivisionError as e:
[Link]("Error: " + [Link]()); print(f"Error: {e}")
} catch (Exception e) { except Exception as e:
[Link]("General error"); print("General error")
} finally { finally:
[Link]("Always runs"); print("Always runs")
} # Raise custom exception
// Throw custom exception raise ValueError("Invalid value")
throw new IllegalArgumentException( # Custom exception class
"Invalid value"); class MyError(Exception):
pass

11. File I/O


■ Python's 'with' statement handles closing automatically — same as try-with-resources in Java.

Java Python
// Write file # Write file
try (FileWriter fw = new FileWriter( with open('[Link]', 'w') as f:
"[Link]")) { [Link]('Hello Python\n')
[Link]("Hello Java\n");
# Read file
} catch (IOException e) {
with open('[Link]', 'r') as f:
[Link]();
for line in f:
}
print([Link]())
// Read file
# Read all at once
try (BufferedReader br =
with open('[Link]') as f:
new BufferedReader(
content = [Link]()
new FileReader("[Link]"))) {
# Read all lines as list
String line;
with open('[Link]') as f:
while ((line=[Link]())!=null) {
lines = [Link]()
[Link](line);
}
} catch (IOException e) {
[Link]();
}

12. Sets & Tuples


■ Tuples are immutable lists. Sets work like Java's HashSet but with cleaner syntax.
Java Python
// HashSet # Set
Set<Integer> set = new HashSet<>(); my_set = {1, 2, 1} # {1, 2}
[Link](1); [Link](2); [Link](1); my_set.add(3)
// {1, 2} — duplicates removed 1 in my_set # True

[Link](1); // true my_set.remove(2)

[Link](2); # Set operations

// Java has no built-in tuple — a = {1,2,3}; b = {2,3,4}

// use arrays or custom class a | b # union {1,2,3,4}

int[] pair = {10, 20}; a &amp; b # intersect {2,3}

# Tuple — immutable
point = (10, 20)
x, y = point # unpacking
point[0] # 10
13. Imports & Packages
■ Python's 'import' is simpler — install third-party packages with 'pip install '.

Java Python
import [Link]; # Standard library
import [Link]; import math
import [Link]; from datetime import datetime
import [Link].*; from collections import defaultdict

// Math # Math
import [Link]; [Link](16)
[Link](16); [Link](2, 8)
[Link](2, 8); abs(-5) # built-in
[Link](-5); # Alias
import numpy as np # pip install numpy
import pandas as pd # pip install pandas

14. Quick Cheat-Sheet


Concept Java Python

Print [Link](x) print(x)

String format [Link]("%d", n) f"{n}"

Null check x == null x is None

Array length [Link] len(arr)

Logical AND/OR && / || and / or

Not equal != !=

Boolean values true / false True / False

Multiline str "+\n+" """..."""

Power of [Link](2,8) 2 ** 8

Integer division 10 / 3 (int) = 3 10 // 3 = 3

Type check x instanceof String isinstance(x, str)

Null-safe call [Link](x) x or default

List to array [Link]() no conversion needed

Main entry public static void main() if __name__=='__main__':

Tip for Java developers: Python rewards brevity. Drop the semicolons, braces, and type declarations — focus on
readability, and let the REPL be your playground. Run python3 in your terminal to experiment interactively!

You might also like