Function Definition Syntax

Java: - Explicit type declarations for parameters and return value. - Functions (called “methods”) must be inside a class.

TrackJava to Python Journey
Current SectionPython Basics
Progress6 of 19

1. Function Definition Syntax

Java:

  • Explicit type declarations for parameters and return value.
  • Functions (called “methods”) must be inside a class.
public int add(int a, int b) {
    return a + b;
}

Python:

  • Use def keyword, no type declarations required.
  • Functions are first-class objects and can exist outside classes.
def add(a, b):
    return a + b

2. Mandatory ‘self’ vs No ‘this’

Java:
Every non-static method in a class gets this as a reference to the instance; it’s implicit.

Python:
Instance methods require an explicit self as the first argument.

class Greeter:
    def greet(self, name):
        print("Hello, " + name)

g = Greeter()
g.greet("Alice")
# 'self' must be the first parameter, passed automatically by Python when using instance method

3. Standalone Functions

Java:
All methods must be inside a class.

public class Utils {
    public static int square(int x) { return x * x; }
}

Usage: Utils.square(3);

Python:
Functions can be declared at the module level, outside any class.

def square(x):
    return x * x

square(3)

4. Default Arguments and Keyword Arguments

Java:
Default arguments are achieved by method overloading.

public void printMessage(String msg) { printMessage(msg, 1); }
public void printMessage(String msg, int count) {
    for (int i = 0; i < count; i++) System.out.println(msg);
}

Python:
Default parameters and keyword arguments are built-in.

def print_message(msg, count=1):
    for _ in range(count):
        print(msg)

print_message("Hello")        # prints once
print_message("Hello", 3)     # prints three times
print_message(count=2, msg="Hi") # keyword argument

5. Variable-Length (Varargs) Arguments

Java:

public int sum(int... numbers) {
    int total = 0;
    for(int n: numbers) total += n;
    return total;
}

Python:

def sum_numbers(*numbers):
    return sum(numbers)

sum_numbers(1, 2, 3)  # 6
  • *args collects positional arguments as a tuple.
  • **kwargs collects keyword arguments as a dict.

6. Return Types

Java:
Must specify return type. Compile-time checked.

Python:
No declaration—return value is dynamic and can be any type, including multiple values (as a tuple).

def analyze(nums):
    return min(nums), max(nums), sum(nums)
# Returns multiple values: tuple with min, max, total

7. Functions as First-Class Objects (Lambdas & Passing Functions)

Java:
Since Java 8, supports lambdas but syntax is more verbose.

Function<Integer, Integer> doubler = x -> x * 2;

Python:
Functions are objects, easy to pass around or return.

doubler = lambda x: x * 2

def operate(fn, value):
    return fn(value)

operate(doubler, 3)  # Returns 6

8. Decorators (Advanced Python Feature)

No exact Java equivalent. A decorator is a function that modifies another function, often used for logging, timing, etc.

def loud(f):
    def wrapper(*args, **kwargs):
        print("Calling function...")
        return f(*args, **kwargs)
    return wrapper

@loud
def say_hi():
    print("Hi!")

say_hi()

Summary Table

  • Type Declarations

    • Java: Required
    • Python: Not required (dynamic typing)
  • Method Location

    • Java: Must be inside a class
    • Python: Anywhere (module/global)
  • Default/Keyword Arguments

    • Java: No (use overloading)
    • Python: Yes (native)
  • Variable-Length Arguments

    • Java: Yes (...)
    • Python: Yes (*args, **kwargs)
  • Return Multiple Values

    • Java: No (usually custom object/array)
    • Python: Yes (tuples)
  • Functions as Objects

    • Java: Since Java 8 (with verbose syntax)
    • Python: Yes (naturally)
  • Decorators

    • Java: No (ad-hoc via interfaces/Wrappers)
    • Python: Yes (native and widely used)
  • Lambdas/Simple Anonymous Funcs

    • Java: Yes (Java 8+, but less concise)
    • Python: Yes (very concise)