Progress6 of 14 topics

43% complete

Java Methods

Methods are blocks of code that perform specific tasks and can be reused throughout your program. In this tutorial, you'll learn how to create and use methods in Java, making your code more organized, reusable, and maintainable.

What is a Method?

A method is a block of code that performs a specific task. Methods are used to break down complex problems into smaller, manageable pieces, promoting code reusability and organization. In Java, methods are always part of a class.

Here's the basic syntax of a method in Java:

accessModifier returnType methodName(parameterList) {
    // Method body
    // Code to be executed
    return value;  // if the method returns a value
}

Creating and Calling Methods

Let's start with a simple example of creating and calling a method:

java
1public class MethodExample {
2 public static void main(String[] args) {
3 // Calling the greet method
4 greet();
5
6 // Calling the greet method multiple times
7 greet();
8 greet();
9 }
10
11 // Method definition
12 public static void greet() {
13 System.out.println("Hello, World!");
14 }
15}
16
17// Output:
18// Hello, World!
19// Hello, World!
20// Hello, World!

In this example:

  • We defined a method called greet() that prints "Hello, World!"
  • We called this method three times from the main method
  • The static keyword allows us to call the method without creating an object
  • The void keyword indicates that the method doesn't return any value

Method Parameters

Methods can accept parameters (inputs) that provide data for the method to work with:

java
1public class ParameterExample {
2 public static void main(String[] args) {
3 // Calling methods with parameters
4 greet("Alice");
5 greet("Bob");
6
7 // Calling a method with multiple parameters
8 displayInfo("Charlie", 25);
9 }
10
11 // Method with one parameter
12 public static void greet(String name) {
13 System.out.println("Hello, " + name + "!");
14 }
15
16 // Method with multiple parameters
17 public static void displayInfo(String name, int age) {
18 System.out.println(name + " is " + age + " years old.");
19 }
20}
21
22// Output:
23// Hello, Alice!
24// Hello, Bob!
25// Charlie is 25 years old.

Parameter vs. Argument

Parameter: The variable defined in the method declaration (e.g., String name in the greet method).
Argument: The actual value passed to the method when it's called (e.g., "Alice" in greet("Alice")).

Return Values

Methods can also return values using the return statement. The return type must be specified in the method declaration:

java
1public class ReturnExample {
2 public static void main(String[] args) {
3 // Calling methods that return values
4 int sum = add(5, 3);
5 System.out.println("Sum: " + sum);
6
7 String fullName = createFullName("John", "Doe");
8 System.out.println("Full name: " + fullName);
9
10 boolean isAdult = checkAge(20);
11 System.out.println("Is adult: " + isAdult);
12 }
13
14 // Method that returns an integer
15 public static int add(int a, int b) {
16 return a + b;
17 }
18
19 // Method that returns a String
20 public static String createFullName(String firstName, String lastName) {
21 return firstName + " " + lastName;
22 }
23
24 // Method that returns a boolean
25 public static boolean checkAge(int age) {
26 return age >= 18;
27 }
28}
29
30// Output:
31// Sum: 8
32// Full name: John Doe
33// Is adult: true

In these examples:

  • The add method returns an int value
  • The createFullName method returns a String value
  • The checkAge method returns a boolean value

Important:

When a method has a return type other than void, it must include a return statement that returns a value of the specified type. If a method is declared as void, it doesn't need areturn statement, but you can use return; to exit the method early.

Method Overloading

Method overloading allows you to define multiple methods with the same name but different parameters. Java determines which method to call based on the arguments provided:

java
1public class OverloadingExample {
2 public static void main(String[] args) {
3 // Calling overloaded methods
4 int sum1 = add(5, 3);
5 int sum2 = add(5, 3, 2);
6 double sum3 = add(5.5, 3.5);
7
8 System.out.println("Sum1: " + sum1);
9 System.out.println("Sum2: " + sum2);
10 System.out.println("Sum3: " + sum3);
11 }
12
13 // Method to add two integers
14 public static int add(int a, int b) {
15 return a + b;
16 }
17
18 // Overloaded method to add three integers
19 public static int add(int a, int b, int c) {
20 return a + b + c;
21 }
22
23 // Overloaded method to add two doubles
24 public static double add(double a, double b) {
25 return a + b;
26 }
27}
28
29// Output:
30// Sum1: 8
31// Sum2: 10
32// Sum3: 9.0

Method overloading is based on:

  • Different number of parameters
  • Different types of parameters
  • Different order of parameters

Note:

Method overloading is not based on return types. You cannot have two methods with the same name and parameter list but different return types.

The main Method

The main method is a special method that serves as the entry point for Java applications:

java
1public class MainMethodExample {
2 // The main method - entry point of the program
3 public static void main(String[] args) {
4 System.out.println("Program started!");
5
6 // Accessing command-line arguments
7 System.out.println("Number of arguments: " + args.length);
8
9 for (int i = 0; i < args.length; i++) {
10 System.out.println("Argument " + i + ": " + args[i]);
11 }
12
13 System.out.println("Program ended!");
14 }
15}

Key points about the main method:

  • It must be declared as public static void main(String[] args)
  • The args parameter allows you to pass command-line arguments to your program
  • It's the first method called when you run a Java program

Variable Scope in Methods

Variables defined inside a method are called local variables and are only accessible within that method:

java
1public class ScopeExample {
2 // Class variable (instance variable)
3 private int instanceVar = 10;
4
5 // Class variable (static variable)
6 private static int staticVar = 20;
7
8 public static void main(String[] args) {
9 // Local variable in main
10 int mainVar = 30;
11
12 System.out.println("staticVar: " + staticVar);
13 System.out.println("mainVar: " + mainVar);
14
15 // Call another method
16 anotherMethod();
17
18 // This would cause an error - methodVar is not accessible here
19 // System.out.println(methodVar);
20 }
21
22 public static void anotherMethod() {
23 // Local variable in anotherMethod
24 int methodVar = 40;
25
26 System.out.println("staticVar: " + staticVar);
27 System.out.println("methodVar: " + methodVar);
28
29 // This would cause an error - mainVar is not accessible here
30 // System.out.println(mainVar);
31 }
32
33 public void nonStaticMethod() {
34 // Can access instance variables
35 System.out.println("instanceVar: " + instanceVar);
36 System.out.println("staticVar: " + staticVar);
37 }
38}

Method Parameters: Pass-by-Value

Java uses pass-by-value for method parameters, which means a copy of the value is passed to the method:

java
1public class PassByValueExample {
2 public static void main(String[] args) {
3 // Primitive type example
4 int number = 10;
5 System.out.println("Before modifyValue: " + number);
6 modifyValue(number);
7 System.out.println("After modifyValue: " + number);
8
9 // Reference type example
10 int[] numbers = {1, 2, 3};
11 System.out.println("Before modifyArray: " + numbers[0]);
12 modifyArray(numbers);
13 System.out.println("After modifyArray: " + numbers[0]);
14 }
15
16 // Method that attempts to modify a primitive parameter
17 public static void modifyValue(int x) {
18 x = 20;
19 System.out.println("Inside modifyValue: " + x);
20 }
21
22 // Method that modifies an array (reference type)
23 public static void modifyArray(int[] arr) {
24 arr[0] = 99;
25 System.out.println("Inside modifyArray: " + arr[0]);
26 }
27}
28
29// Output:
30// Before modifyValue: 10
31// Inside modifyValue: 20
32// After modifyValue: 10
33// Before modifyArray: 1
34// Inside modifyArray: 99
35// After modifyArray: 99

Understanding Pass-by-Value:

For primitive types (int, double, boolean, etc.), a copy of the actual value is passed.
For reference types (objects, arrays), a copy of the reference (memory address) is passed, not the object itself. This is why changes to the object's content are visible outside the method, but reassigning the reference has no effect outside.

Recursive Methods

A recursive method is one that calls itself. Recursive methods need a base case to prevent infinite recursion:

java
1public class RecursionExample {
2 public static void main(String[] args) {
3 // Calculate factorial using recursion
4 int result = factorial(5);
5 System.out.println("Factorial of 5: " + result);
6
7 // Calculate Fibonacci number using recursion
8 int fib = fibonacci(7);
9 System.out.println("7th Fibonacci number: " + fib);
10 }
11
12 // Recursive method to calculate factorial
13 public static int factorial(int n) {
14 // Base case
15 if (n == 0 || n == 1) {
16 return 1;
17 }
18 // Recursive case
19 else {
20 return n * factorial(n - 1);
21 }
22 }
23
24 // Recursive method to calculate Fibonacci number
25 public static int fibonacci(int n) {
26 // Base cases
27 if (n <= 1) {
28 return n;
29 }
30 // Recursive case
31 else {
32 return fibonacci(n - 1) + fibonacci(n - 2);
33 }
34 }
35}
36
37// Output:
38// Factorial of 5: 120
39// 7th Fibonacci number: 13

Method Best Practices

Single Responsibility Principle

Each method should have a single, well-defined purpose. If a method is doing too many things, consider breaking it down into smaller, more focused methods.

Descriptive Method Names

Use clear, descriptive names that indicate what the method does. Method names should typically start with a verb (e.g., calculateTotal, findUser, isValid).

Keep Methods Short

A good rule of thumb is to keep methods short enough to fit on a single screen (20-30 lines). Long methods are harder to understand and maintain.

Limit Parameters

Try to limit the number of parameters to 3-4. If you need more, consider using a class to encapsulate the parameters or breaking the method into smaller methods.

Practical Example: Calculator Application

Let's put everything together in a practical example of a calculator application:

java
1import java.util.Scanner;
2
3public class Calculator {
4 // Instance variable
5 private String calculatorName;
6
7 // Constructor
8 public Calculator(String name) {
9 this.calculatorName = name;
10 }
11
12 // Method with return value
13 public int add(int a, int b) {
14 return a + b;
15 }
16
17 // Method overloading - same name, different parameters
18 public double add(double a, double b) {
19 return a + b;
20 }
21
22 // Method accepting array
23 public double calculateAverage(int[] numbers) {
24 if (numbers.length == 0) {
25 return 0;
26 }
27
28 int sum = 0;
29 for (int number : numbers) { // Enhanced for loop
30 sum += number;
31 }
32
33 return (double) sum / numbers.length;
34 }
35
36 // Method with variable arguments (varargs)
37 public int sum(int... numbers) {
38 int total = 0;
39 for (int num : numbers) {
40 total += num;
41 }
42 return total;
43 }
44
45 // Static method - belongs to the class, not instances
46 public static double square(double number) {
47 return number * number;
48 }
49
50 public static void main(String[] args) {
51 // Creating object instance
52 Calculator calc = new Calculator("MyCalculator");
53
54 // Calling instance methods
55 System.out.println("5 + 3 = " + calc.add(5, 3));
56 System.out.println("2.5 + 3.5 = " + calc.add(2.5, 3.5));
57
58 // Using array method
59 int[] scores = {85, 90, 78, 92, 88};
60 System.out.println("Average: " + calc.calculateAverage(scores));
61
62 // Using varargs method
63 System.out.println("Sum: " + calc.sum(1, 2, 3, 4, 5));
64
65 // Using static method
66 System.out.println("5 squared: " + Calculator.square(5));
67 }
68}

Practice Exercises

  1. Create a method that checks if a number is prime.
  2. Write a method that reverses a string.
  3. Create a method that finds the maximum value in an array of integers.
  4. Write a recursive method to calculate the sum of digits in a number.
  5. Create a temperature conversion application with methods to convert between Celsius, Fahrenheit, and Kelvin.

Summary

In this tutorial, you've learned:

  • How to create and call methods in Java
  • How to use parameters to pass data to methods
  • How to return values from methods
  • How to use method overloading to create multiple methods with the same name
  • The concept of variable scope in methods
  • How Java uses pass-by-value for method parameters
  • How to create recursive methods
  • Best practices for writing clean and efficient methods

Methods are fundamental building blocks in Java programming. They allow you to organize your code into reusable, manageable pieces, making your programs more modular and easier to maintain. As you continue your Java journey, you'll find yourself creating and using methods in virtually every program you write.

Related Tutorials

Learn about decision making and loops in Java.

Learn more

Understand the fundamentals of OOP in Java.

Learn more

Learn how to work with arrays in Java.

Learn more