In Java, methods are blocks of code that perform specific tasks. They help you organize code, avoid repetition, and make your programs more readable and reusable.
This section introduces how to define your own methods, how to give them names and parameters, and how to call them from the main
method.
A method in Java is a group of statements that performs a task. It may accept input, do some processing, and optionally return a value.
Here is the general structure of a method:
returnType methodName(parameters) {
// method body
}
returnType
: The type of value the method returns (e.g., int
, String
, double
, or void
for no return).methodName
: A name that describes what the method does (use camelCase).parameters
: Inputs the method needs (can be empty).Let’s define a method that takes two integers as input and returns their sum.
public class AddExample {
// Method that returns the sum of two integers
public static int add(int a, int b) {
int result = a + b;
return result;
}
public static void main(String[] args) {
int x = 5;
int y = 7;
int sum = add(x, y); // Method call
System.out.println("The sum is: " + sum);
}
}
public static int add(int a, int b)
: A method named add
that returns an int
.int sum = add(x, y)
: Calls the method and stores the result in sum
.main
, which is where program execution begins.Now let’s define a method that returns a personalized greeting using a String
parameter.
public class GreetingExample {
// Method that returns a greeting message
public static String greet(String name) {
return "Hello, " + name + "!";
}
public static void main(String[] args) {
String message = greet("Alice");
System.out.println(message);
}
}
String
, because the method returns text.name
of type String
.This method improves reusability — you can greet anyone by just changing the name.
Let’s write a method to calculate the area of a rectangle.
public class AreaCalculator {
// Method to calculate the area of a rectangle
public static double calculateArea(double width, double height) {
return width * height;
}
public static void main(String[] args) {
double w = 4.5;
double h = 3.2;
double area = calculateArea(w, h);
System.out.println("Area: " + area);
}
}
double
, because area may have decimal values.double
values for width and height.width
and height
.When defining methods:
calculateArea
is more meaningful than doStuff
.main
All Java programs start from the main
method:
public static void main(String[] args) {
// This is where your program starts
}
You call methods from main
by using their name and passing any required arguments. The method’s return value (if any) can be stored in a variable or printed directly.
In Java, parameters and return values are essential parts of how methods communicate with the rest of your program. Parameters let you pass input into a method, and return values allow the method to pass results back.
This section builds on what you learned in Section 1 by expanding how methods handle input and output. You’ll learn how to define methods with multiple parameters, use void
when no return is needed, and return various types like int
, String
, and boolean
.
return
keyword. If a method doesn't return anything, its return type is void
.You can define a method that accepts more than one parameter by separating them with commas.
public class MultiParameterExample {
// Method with three parameters
public static int addThreeNumbers(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
int result = addThreeNumbers(5, 10, 15); // Passing three arguments
System.out.println("Sum: " + result); // Output: Sum: 30
}
}
addThreeNumbers
accepts three int
parameters.return a + b + c;
.main
, the method is called with 5
, 10
, and 15
as arguments.void
)Sometimes, you don’t need a method to return a value — you just want it to perform an action, like printing something.
public class VoidExample {
// Method with no return value
public static void showWelcomeMessage(String name) {
System.out.println("Welcome, " + name + "!");
}
public static void main(String[] args) {
showWelcomeMessage("Alice"); // Output: Welcome, Alice!
}
}
void
because it doesn’t return anything.String
parameter and prints a message.Java methods can return any data type. Let’s look at a few examples:
int
public static int square(int number) {
return number * number;
}
Usage:
int result = square(6); // result = 36
String
public static String getFullName(String firstName, String lastName) {
return firstName + " " + lastName;
}
Usage:
String name = getFullName("John", "Doe"); // name = "John Doe"
boolean
public static boolean isEven(int number) {
return number % 2 == 0;
}
Usage:
if (isEven(4)) {
System.out.println("The number is even.");
}
These examples show how return types allow your methods to send different kinds of data back to the caller.
Let’s create a small program that checks if someone is an adult based on their age.
import java.util.Scanner;
public class AgeChecker {
// Method that returns a boolean
public static boolean isAdult(int age) {
return age >= 18;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int userAge = scanner.nextInt();
if (isAdult(userAge)) {
System.out.println("You are an adult.");
} else {
System.out.println("You are not an adult.");
}
}
}
int age
boolean
main
method uses a Scanner
to take input and passes it to isAdult()
.true
or false
, which is used in an if
condition.This shows how methods with parameters and return values can interact with user input to make decisions.
When you call a method, the arguments must match the parameters in both type and order.
public static double average(int a, int b) {
return (a + b) / 2.0;
}
// Calling the method
double result = average(8, 10); // result = 9.0
8
and 10
as arguments.result
.Always ensure:
In Java, you can define multiple methods with the same name as long as they have different parameter lists. This is called method overloading. It allows a class to perform similar tasks in slightly different ways without creating completely different method names.
Method overloading means defining more than one method in the same class with the same name, but with different:
Important: The method name stays the same, but the parameter list must differ in some way.
calculateAreaSquare
, calculateAreaRectangle
, etc.Let’s look at a practical example: calculating the area of different shapes using overloaded methods.
public static double calculateArea(double side) {
return side * side;
}
public static double calculateArea(double length, double width) {
return length * width;
}
public static double calculateArea(double radius, boolean isCircle) {
if (isCircle) {
return Math.PI * radius * radius;
} else {
return -1; // Invalid input
}
}
double
and a boolean
isCircle
is true
public class AreaOverload {
// Square
public static double calculateArea(double side) {
return side * side;
}
// Rectangle
public static double calculateArea(double length, double width) {
return length * width;
}
// Circle
public static double calculateArea(double radius, boolean isCircle) {
if (isCircle) {
return Math.PI * radius * radius;
} else {
return -1;
}
}
public static void main(String[] args) {
System.out.println("Area of square (5): " + calculateArea(5));
System.out.println("Area of rectangle (4, 6): " + calculateArea(4, 6));
System.out.println("Area of circle (radius 3.0): " + calculateArea(3.0, true));
}
}
Area of square (5): 25.0
Area of rectangle (4, 6): 24.0
Area of circle (radius 3.0): 28.274333882308138
Java determines which overloaded method to execute using method signature, which includes:
At compile time, Java checks the arguments you pass and chooses the method whose parameters match best.
calculateArea(5)
→ Matches method with 1 double
→ squarecalculateArea(4, 6)
→ Matches method with 2 double
→ rectanglecalculateArea(3.0, true)
→ Matches method with double
and boolean
→ circleInvalid Example (doesn't compile):
public static int example() { return 1; }
public static double example() { return 2.0; } // ❌ Error: duplicate method
Using the same method name for similar operations makes code easier to understand.
You can handle multiple input variations without rewriting code.
Users of your method don’t have to remember different method names for similar tasks.
main
Method ExplainedEvery Java program begins execution from a special method called the main
method. This method acts as the entry point — the place where the program starts running.
If your class doesn't have a correctly defined main
method, the Java Virtual Machine (JVM) won’t know where to begin, and your program won’t run.
public static void main(String[] args)
Let’s break down each part of this line:
public
This is an access modifier. It means the main
method is accessible from anywhere, including by the JVM when the program starts.
static
This means the method belongs to the class rather than to any specific object. Since the JVM needs to call this method before any objects exist, main
must be static
.
void
This indicates that the method does not return a value. The main
method simply starts the program — it doesn't give back a result.
main
This is the name of the method. It must be spelled exactly like this — lowercase main
— because the JVM looks for it when launching a program.
String[] args
This is an array of Strings. It holds any command-line arguments passed when the program is run. If you don’t provide any, the array is simply empty.
Here’s a simple program that prints whatever arguments you pass to it:
public class CommandLineDemo {
public static void main(String[] args) {
System.out.println("Arguments received:");
for (int i = 0; i < args.length; i++) {
System.out.println("Arg " + i + ": " + args[i]);
}
}
}
If you compile and run the program from a command line:
java CommandLineDemo Hello 123 Java
Arguments received:
Arg 0: Hello
Arg 1: 123
Arg 2: Java
Hello
, 123
, and Java
.main
method stores them in the args
array.main
Method Crucial?main
method.Yes! In addition to the main method, you can define and use other methods to organize your code and avoid repetition.
public class Welcome {
public static void printGreeting() {
System.out.println("Welcome to Java!");
}
public static void main(String[] args) {
printGreeting(); // Call to another method
}
}