Easy Tutorial
❮ Java String Touppercase Exception Hierarchy ❯

Java Methods

In the previous chapters, we frequently used System.out.println(). So, what is it?

What is a method?

A Java method is a collection of statements that are grouped together to perform an operation.

Advantages of Methods

Naming Rules for Methods


Method Definition

Generally, a method is defined using the following syntax:

modifier returnType methodName(parameterType parameterName){
    ...
    method body
    ...
    return returnValue;
}

A method includes a method header and a method body. Here are all the parts of a method:

For example:

public static int age(int birthday){...}

Parameters can be multiple:

static float interest(float principal, int year){...}

Note: In some other languages, methods refer to procedures and functions. A method that returns a non-void value is called a function; a method that returns a void value is called a procedure.

Example

The following method includes two parameters num1 and num2 and returns the maximum value of these two parameters.

/** Returns the larger value between two integers */
public static int max(int num1, int num2) {
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result; 
}

A more concise way (using the ternary operator):

public static int max(int num1, int num2) {
  return num1 > num2 ? num1 : num2;
}

Method Invocation

Java supports two ways to invoke a method, depending on whether the method returns a value.

When a program calls a method, control is transferred to the called method. The control is returned to the program when the return statement of the called method is executed or when the method's closing brace is reached.

When a method returns a value, the method call is often treated as a value. For example:

int larger = max(30, 40);

If the method returns void, the method call must be a statement. For example, the println method returns void. The following call is a statement:

System.out.println("Welcome to tutorialpro.org!");

Example

The following example demonstrates how to define a method and how to call it:

TestMax.java File Code:

public class TestMax {
   /** Main method */
   public static void main(String[] args) {
      int i = 5;
      int j = 2;
      int k = max(i, j);
      System.out.println( i + " and " + j + " compared, the maximum value is: " + k);
   }

   /** Returns the larger value between two integers */
   public static int max(int num1, int num2) {
      int result;
      if (num1 > num2)
         result = num1;
      else
         result = num2;

      return result; 
   }
}
if (num1 > num2) {
   result = num1;
} else {
   result = num2;
}

return result;
}
}

The above example compiles and runs with the following result:

Comparing 5 and 2, the maximum value is: 5

This program includes a main method and a max method. The main method is called by the JVM, and apart from that, the main method is no different from other methods.

The header of the main method is fixed, as shown in the example, with modifiers public and static, returning void, named main, and taking a String[] type parameter. String[] indicates that the parameter is an array of strings.


void Keyword

This section explains how to declare and call a void method.

The following example declares a method named printGrade and calls it to print the given score.

Example

TestVoidMethod.java File Code:

public class TestVoidMethod {
  public static void main(String[] args) {
    printGrade(78.5);
  }

  public static void printGrade(double score) {
    if (score >= 90.0) {
       System.out.println('A');
    }
    else if (score >= 80.0) {
       System.out.println('B');
    }
    else if (score >= 70.0) {
       System.out.println('C');
    }
    else if (score >= 60.0) {
       System.out.println('D');
    }
    else {
       System.out.println('F');
    }
  }
}

The above example compiles and runs with the following result:

C

Here, the printGrade method is a void method that does not return a value.

The call to a void method must be a statement. It is called as a statement in the third line of the main method, just like any statement ending with a semicolon.


Passing Parameters by Value

When calling a method, you need to provide arguments, and you must follow the order specified by the parameter list.

For example, the following method prints a message n times:

TestVoidMethod.java File Code:

public static void nPrintln(String message, int n) {
  for (int i = 0; i < n; i++) {
    System.out.println(message);
  }
}

Example

The following example demonstrates the effect of passing by value.

The program creates a method that swaps two variables.

TestPassByValue.java File Code:

public class TestPassByValue {
  public static void main(String[] args) {
    int num1 = 1;
    int num2 = 2;

    System.out.println("Before swapping, the value of num1 is: " +
                        num1 + " and num2 is: " + num2);

    // Call the swap method
    swap(num1, num2);
    System.out.println("After swapping, the value of num1 is: " +
                       num1 + " and num2 is: " + num2);
  }
  /** Method to swap two variables */
  public static void swap(int n1, int n2) {
    System.out.println("\tInside the swap method");
    System.out.println("\t\tBefore swapping, n1 is: " + n1
                         + " and n2 is: " + n2);
    // Swap n1 and n2
    int temp = n1;
    n1 = n2;
    n2 = temp;

    System.out.println("\t\tAfter swapping, n1 is " + n1
                         + " and n2 is: " + n2);
  }
}

The above example compiles and runs with the following result:

Before swapping, the value of num1 is: 1 and num2 is: 2
    Inside the swap method
        Before swapping, n1 is: 1 and n2 is: 2
        After swapping, n1 is 2 and n2 is: 1
After swapping, the value of num1 is: 1 and num2 is: 2

Before the swap, the value of n1 is: 1, and the value of n2 is: 2. After the swap, the value of n1 is 2, and the value of n2 is: 1. After the swap, the value of num1 is: 1, and the value of num2 is: 2.

When two parameters are passed to the swap method, it's interesting to note that the values of the actual arguments do not change after the method is called.


Method Overloading

The max method used above is only applicable to int type data. But what if you want to get the maximum value of two floating-point type data?

The solution is to create another method with the same name but different parameters, as shown in the following code:

public static double max(double num1, double num2) {
  if (num1 > num2)
    return num1;
  else
    return num2;
}

If you call the max method with int type parameters, the max method for int type parameters will be called; If you pass double type parameters, the max method for double type parameters will be called, which is called method overloading; This means that two methods in a class have the same name but different parameter lists. The Java compiler determines which method should be called based on the method signature.

Method overloading can make the program clearer and more readable. Methods that perform closely related tasks should use the same name. Overloaded methods must have different parameter lists. You cannot overload methods based solely on different modifiers or return types.


Variable Scope

The scope of a variable is the part of the program where the variable can be referenced.

Variables defined within a method are called local variables.

The scope of a local variable starts from its declaration and ends with the block containing it.

Local variables must be declared before they can be used.

The scope of a method's parameters covers the entire method. Parameters are essentially local variables.

Variables declared in the initialization part of a for loop have their scope throughout the loop.

However, variables declared inside the loop body have their scope from their declaration to the end of the loop body.

You can declare a local variable with the same name in different non-nested blocks within a method, but you cannot declare a local variable twice within nested blocks.

Using Command-Line Arguments

Sometimes you want to pass messages to a program when you run it. This is done by passing command-line arguments to the main() function.

Command-line arguments are information that follows the program name when executing the program.

Example

The following program prints all command-line arguments:

CommandLine.java File Code:

public class CommandLine {
   public static void main(String[] args){ 
      for(int i=0; i&lt;args.length; i++){
         System.out.println("args[" + i + "]: " + args[i]);
      }
   }
}

Run this program as follows:

$ javac CommandLine.java 
$ java CommandLine this is a command line 200 -100
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

Constructor Method

A constructor is used to initialize an object when it is created. The constructor has the same name as the class and does not have a return value.

Typically, constructors are used to assign initial values to instance variables of a class or to perform other necessary steps to create a complete object.

Regardless of whether you define a constructor, all classes have constructors because Java automatically provides a default constructor, whose access modifier is the same as the class's access modifier (if the class is public, the constructor is also public; if the class is protected, the constructor is also protected).

Once you define your own constructor, the default constructor becomes ineffective.

Example

Here is an example using a constructor:

// A simple constructor
class MyClass {
  int x;

  // This is the constructor
  MyClass() {
    x = 10;
  }
}

You can call the constructor to initialize an object like this:

ConsDemo.java File Code:

public class ConsDemo {
   public static void main(String[] args) {
      MyClass t1 = new MyClass();
      MyClass t2 = new MyClass();
      System.out.println(t1.x + " " + t2.x);
   }
}

Most of the time, you need a constructor with parameters.

Example

Here is an example using a constructor:

// A simple constructor
class MyClass {
  int x;

  // This is the constructor
  MyClass(int i ) {
    x = i;
  }
}

You can call the constructor method to initialize an object as shown below:

ConsDemo.java File Code:

public class ConsDemo {
  public static void main(String[] args) {
    MyClass t1 = new MyClass(10);
    MyClass t2 = new MyClass(20);
    System.out.println(t1.x + " " + t2.x);
  }
}

Running result is as follows:

10 20

Variable Arguments

Starting from JDK 1.5, Java supports passing variable arguments of the same type to a method.

The declaration of a variable argument in a method is as follows:

typeName... parameterName

In the method declaration, an ellipsis (...) is added after specifying the parameter type.

A method can only specify one variable argument, which must be the last parameter. Any regular parameters must be declared before it.

Example

VarargsDemo.java File Code:

public class VarargsDemo {
    public static void main(String[] args) {
        // Call the method with variable arguments
        printMax(34, 3, 3, 2, 56.5);
        printMax(new double[]{1, 2, 3});
    }

    public static void printMax(double... numbers) {
        if (numbers.length == 0) {
            System.out.println("No argument passed");
            return;
        }

        double result = numbers[0];

        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > result) {
                result = numbers[i];
            }
        }
        System.out.println("The max value is " + result);
    }
}

The compilation and running result of the above example is as follows:

The max value is 56.5
The max value is 3.0

finalize() Method

Java allows defining a method that is called before the object is garbage collected by the garbage collector, called finalize(). It is used to clean up the object before it is recycled.

For example, you can use finalize() to ensure that a file opened by an object is closed.

In the finalize() method, you must specify the operations to be performed when the object is destroyed.

The general format of finalize() is:

protected void finalize()
{
   // Finalization code here
}

The keyword protected is a qualifier that ensures the finalize() method cannot be called by code outside of this class.

Of course, Java's memory management can be handled automatically by the JVM. If you manually manage it, you can use the above method.

Example

FinalizationDemo.java File Code:

public class FinalizationDemo {  
  public static void main(String[] args) {  
    Cake c1 = new Cake(1);  
    Cake c2 = new Cake(2);  
    Cake c3 = new Cake(3);  

    c2 = c3 = null;  
    System.gc(); // Call Java garbage collector
  }  
}  

class Cake extends Object {  
  private int id;  
  public Cake(int id) {  
    this.id = id;  
    System.out.println("Cake Object " + id + " is created");  
  }  

  protected void finalize() throws java.lang.Throwable {  
    super.finalize();  
    System.out.println("Cake Object " + id + " is disposed");  
  }  
}

Run the above code, and the output is as follows:

$ javac FinalizationDemo.java 
$ java FinalizationDemo
Cake Object 1 is created
Cake Object 2 is created
Cake Object 3 is created
Cake Object 3 is disposed
Cake Object 2 is disposed
❮ Java String Touppercase Exception Hierarchy ❯