A function is a named block of code that does one job. You write the code once, give it a name, and then run it by calling that name whenever you need it. Functions can take inputs and give back a result.
This guide shows how to define a function, call it, pass parameters and return a value. Every example is written in both Java and Python so you can compare them. It helps to know variables and data types first.
What is a function: an everyday example
Think of a juice machine at a shop.
- You put in fruit (the input).
- The machine does the same steps every time: wash, cut, squeeze.
- You get juice back (the output).
You do not need to know what happens inside. You only need to know what to put in and what comes out. A function works the same way. Its inputs are parameters, its steps are the body, and its output is the return value.
Why we use functions
Without functions, you would copy the same lines wherever you need them. If there is a bug, you must fix every copy.
| Without functions | With functions |
|---|---|
| Same code repeated in many places | Code written once, called many times |
| A fix must be made in every copy | A fix is made in one place |
| Long programs are hard to read | Each function has a clear name and job |
| Hard to test small parts | Each function can be tested alone |
A good function does one thing and has a name that says what it does, such as calculateTotal or is_even.
The four parts of a function
| Part | Meaning | Example in add(a, b) |
|---|---|---|
| Name | How you call it | add |
| Parameters | Inputs it accepts | a and b |
| Body | The steps it runs | a + b |
| Return value | The result it sends back | the sum |
Define and call a function
Defining a function means writing it. Calling a function means running it. Defining alone does nothing. The code inside runs only when you call it.
Java
public class Functions {
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
static int add(int a, int b) {
return a + b;
}
static double average(int a, int b, int c) {
return (a + b + c) / 3.0;
}
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
greet("Ravi");
greet("Sneha");
int total = add(4, 6);
System.out.println(total);
System.out.println(average(70, 80, 95));
System.out.println(isEven(7));
}
}
Output:
Hello, Ravi!
Hello, Sneha!
10
81.66666666666667
false
Python
def greet(name):
print("Hello, " + name + "!")
def add(a, b):
return a + b
def average(a, b, c):
return (a + b + c) / 3
def is_even(n):
return n % 2 == 0
greet("Ravi")
greet("Sneha")
total = add(4, 6)
print(total)
print(average(70, 80, 95))
print(is_even(7))
Output:
Hello, Ravi!
Hello, Sneha!
10
81.66666666666667
False
The two programs do the same work. Python prints False with a capital F, and Java prints false, because that is how each language writes its boolean values.
Java and Python side by side
| Point | Java | Python |
|---|---|---|
| Keyword to define | No keyword, you write the return type | def |
| Return type | Must be written, such as int, double, void |
Not written |
| Parameter types | Must be written, such as int a |
Not written |
| Body | Inside { } |
Indented block after : |
| Where it lives | Always inside a class | Anywhere in the file |
| No return value | Return type void |
Returns None automatically |
In Java, static lets main call these methods without creating an object first. You will learn more about static and objects when you study classes.
Parameters and arguments
People often mix up these two words.
- A parameter is the name in the definition:
aandbinadd(a, b). - An argument is the real value you pass in a call:
4and6inadd(4, 6).
When you call add(4, 6), the value 4 is copied into a and 6 into b. Arguments are matched to parameters by position, so the order matters.
Python also lets you give a parameter a default value and pass arguments by name:
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25, exponent uses the default 2
print(power(2, 10)) # 1024
print(power(exponent=3, base=4)) # 64, named arguments in any order
Java does not have default values. Instead, you can write two methods with the same name and different parameters. This is called method overloading.
Return values
return does two things: it sends a value back to the caller and it ends the function at once. Any line after a return in the same block does not run.
int total = add(4, 6); // add returns 10, which is stored in total
You can use a returned value directly, without storing it:
System.out.println(add(4, 6) * 2); // prints 20
Functions that return nothing
greet prints a message but does not return a value. In Java its return type is void. In Python it gives back None.
def show():
print("Hi")
result = show()
print(result)
Output:
Hi
None
Common mistake: Confusing
return. A function that only prints a value does not give it back. If you writetotal = greet("Ravi")in Python,totalisNone. Usereturnwhen the caller needs the value.
Returning more than one value
Python can return several values at once as a tuple:
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([7, 2, 9, 4])
print(low, high) # 2 9
Java returns only one value. To send back more, return an array, a list or an object that holds the values.
Local variables and scope
A variable created inside a function exists only inside that function. This is called local scope. When the function ends, the variable is gone.
public class Scope {
static void change(int x) {
x = 100;
System.out.println("Inside: " + x);
}
public static void main(String[] args) {
int x = 5;
change(x);
System.out.println("Outside: " + x);
}
}
Output:
Inside: 100
Outside: 5
The x inside change is a separate copy. Changing it does not change the x in main. Java always passes arguments by value: a primitive such as int is copied, and for an object the reference is copied. Python passes a reference to the object, so changing a list inside a function does change the caller's list, while giving a parameter a new value does not.
Methods vs functions
| Point | Function | Method |
|---|---|---|
| Belongs to | Nobody, stands alone | A class or an object |
| How you call it | add(4, 6) |
name.toUpperCase(), list.append(5) |
| Java | Java has no stand-alone functions | Every function is a method |
| Python | def add(a, b): at the top level |
def inside a class |
So in Java, "method" is the correct word. In Python, len(items) is a function and items.append(3) is a method of the list. The ideas of parameters and return values are the same for both.
How to write a good function
- One job per function. If you need "and" to describe it, split it.
- Clear name. Use a verb for actions (
printReport) and a question for true or false results (isEven,has_access). - Few parameters. More than three or four is hard to read.
- Return, do not print, when the caller needs the result.
- Keep it short. If it does not fit on one screen, it probably does too much.
Pro tip: Write the function call first, before the function. For example, write
int total = calculateTotal(prices);and then buildcalculateTotalto make that line work. This keeps the function focused on what the caller needs.
Practice tasks
Write each one in both Java and Python:
square(n)returns n x n.max_of_three(a, b, c)returns the largest of three numbers.is_vowel(ch)returns true if a letter is a vowel.count_digits(n)returns how many digits a number has.celsius_to_fahrenheit(c)returnsc * 9 / 5 + 32.
A function can also call itself. This is called recursion, and it is the next step after functions. Read what is recursion once these tasks feel easy.
Quick revision
- A function is a named block of code that does one job.
- Define it once, call it many times.
- Parameters are inputs.
returnsends back the output. - Java methods need types. Python functions use
def. - A method is a function that belongs to a class or object.
Not sure which language to start with? Compare them in Java vs Python for freshers. If you are heading into web development, the JavaScript closures and functions interview questions show how functions are tested in interviews.
Frequently Asked Questions
What is a function in programming in simple words?
What is the difference between a parameter and an argument?
What is the difference between a method and a function?
What does return do in a function?
Can a function have no parameters or no return value?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — View the Java Full Stack curriculum

