13) Methods

A method is a group of statements identified with a name. Methods are used to define the behavior of an object.

How to call a Java Method?

Now you defined a method, you need to use it. For that, you have to call the method. Here's how:

myMethod();

This statement calls the myMethod() method that was declared earlier.

  1. While Java is executing the program code, it encounters myMethod(); in the code.

  2. The execution then branches to the myFunction() method, and executes code inside the body of the method.

  3. After the codes execution inside the method body is completed, the program returns to the original state and executes the next statement.

Example: 1

Let's see a Java method in action by defining a Java class.

class Main {

   public static void main(String[] args) {
       System.out.println("About to enter a method.");

       // method call
       printSomething();

       System.out.println("Method was executed successfully!");
   }

   // method definition
   private static void printSomething(){
       System.out.println("Printing from inside printSomething()!");
   }
}

When you run the program, the output will be:

About to enter a method.
Printing from inside printSomething()!
Method was executed successfully!

The method printSomething() in the above program doesn't accept any arguments. Also, the method doesn't return any value (return type is void).

Note that, we called the method without creating object of the class. It was possible because printSomething() is static.

Here's another example. In this example, our method is non-static and is inside another class.

class Main {

   public static void main(String[] args) {

       Output obj = new Output();
       System.out.println("About to encounter a method.");

       // calling myMethod() of Output class
       obj.myMethod();

       System.out.println("Method was executed successfully!");
   }
}

class Output {
  
   // public: this method can be called from outside the class
   public void myMethod() {
       System.out.println("Printing from inside myMethod().");
   }
}

When you run the program, the output will be:

About to encounter a method.
Printing from inside myMethod().
Method was executed successfully!

Note that, we first created instance of Output class, then the method was called using objobject. This is because myMethod() is a non-static method.

Example: 2

Let's take an example of method returning a value.

class SquareTest {
    public static void main(String[] args) {
        int result;
        result = square(); 
        System.out.println("Squared value of 12 is: " + result);
    }

          public static int square() {
        // return statement
        return 12 * 12;
    }

}

When you run the program, the output will be:

Squared value of 12 is: 144

In the above code snippet, the method square() does not accept any arguments and always returns the value of 10 squared.

Notice, the return type of square() method is int. Meaning, the method returns an integer value.

As you can see, the scope of this method is limited as it always returns the same value.

Now, let's modify the above code snippet so that instead of always returning the squared value of 10, it returns the squared value of any integer passed to the method.

Example: Method Accepting Arguments and Returning Value

public class SquareMain {
   
    public static void main(String[] args) {
        int result, n;
        
        n = 3
        result = square(n);
        System.out.println("Square of 3 is: " + result);
        
        n = 4
        result = square(n); 
        System.out.println("Square of 4 is: " + result);
    }

	static int square(int i) {
        return i * i;
    }
}

When you run the program, the output will be:

Squared value of 3 is: 9
Squared value of 4 is: 16

Now, the square() method returns the squared value of whatever integer value passed to it.

Java is a strongly-typed language. If you pass any other data type except int (in the above example), compiler will throw an error.

The argument passed n to the getSquare() method during the method call is called actual argument.

result = getSquare(n);

The parameter it accepts the passed arguments in the method definition getSquare(int i). This is called formal argument (parameter). The type of the formal argument must be explicitly typed.

You can pass more than one argument to the Java method by using commas. For example,

public class Calculator{

    public static int calculateSum (int a, int b) {
        return a + b;
    }

    public static int calculateProduct(int x, int y) {
        return x * y;
    }

    public static void main(String[] args) {
        System.out.println("10 + 20 = " + calculateSum (10, 20));
        System.out.println("20 x 40 = " + calculateProduct(20, 40));
    }
}

When you run the program, the output will be:

10 + 20 = 30
20 x 40 = 800

The data type of actual and formal arguments should match, i.e., the data type of first actual argument should match the type of first formal argument. Similarly, the type of second actual argument must match the type of second formal argument and so on.

Example: Get Squared Value Of Numbers from 1 to 6

public class Utility {

    // method defined
    private static int getSquare(int x){
        return x * x;
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 6; i++) {

            // method call
            result = getSquare(i)
            System.out.println("Square of " + i + " is : " + result); }
    }
}

When you run the program, the output will be:

Square of 1 is : 1
Square of 2 is : 4
Square of 3 is : 9
Square of 4 is : 16
Square of 5 is : 25
Square of 6 is : 36

In above code snippet, the method getSquare() takes int as a parameter. Based on the argument passed, the method returns the squared value of it.

Here, argument i of type int is passed to the getSquare() method during method call.

result = getSquare(i);

The parameter x accepts the passed argument [in the function definition getSquare(int x).

return i * i; is the return statement. The code returns a value to the calling method and terminates the function.

Did you notice, we reused the getSquare method 6 times?

What are the advantages of using methods?

  • The main advantage is code reusability. You can write a method once, and use it multiple times. You do not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple times."

  • Methods make code more readable and easier to debug. For example, getSalaryInformation() method is so readable, that we can know what this method will be doing than actually reading the lines of code that make this method.

Program Execution:

Part-1:

The following process takes place when we execute a program:

  1. Program execution happens in RAM.

  2. RAM memory is divided into 2 types,

    1. Stack: For execution purpose.

    2. Heap: For Storage purpose.

  3. JVM will be loaded onto stack automatically.

  4. JVM will call class loader (Built-in Library).

  5. Class Loader will create a static pool in the heap memory and all the static members of the class will be loaded on to it.

Static pool name will be similar to class name.

Part-2:

  1. JVM will check the availability of main method in the static pool, if its available, JVM will load the main method for execution purpose.

  2. JVM will pass the control to main method so that main method can execute its statement.

Part-3:

  1. From main method, some method is called by using static pool name i.e.,

Classname.someMethod(1);

  1. someMethod() will be loaded onto the stack.

  2. Control will pass to the someMethod(), so it can executes its statement.

  3. someMethod() after its execution will return the control back to main method.

  4. someMethod() will be erased from the stack.

  5. Main method resume its execution and finally it will return the control back to JVM.

  6. Main method will be erased from stack.

  7. JVM will call Garbage Collector(Daemon Thread).

  8. Garbage Collector will clear the contents from the HEAP memory.

  9. JVM will exit from the stack.

More Examples:

Example:

package com.gs.ilp.corejava.Methods;

public class Simple2 {
	static void cube(int num) {
		int c = num * num * num;
		System.out.println("Result is: " + c);
	}

	public static void main(String[] args) {
		Simple2.cube(3);
	}
}

Output:

Result is: 27

Note:

  1. void means return no value but return control.

  2. If the method return-type is void, then that method cannot return any value after processing.

  3. If any methods return-type is void, then developing return statement is not mandatory.

  4. If any methods return-type is void and if the programmer has not developed to return statement then compiler will develop return statement automatically at compile time.

  5. Developing methods with arguments is not mandatory i.e., we can develop methods without arguments.

  6. The methods without arguments cannot receive any input at the time of method invocation.

Example: Interview Question

package com.gs.ilp.corejava.Methods;

public class Simple5 {
	static  test()// Return type required
	{
		System.out.println("Running test method()");
	}

	public static void main(String[] args) {
		Simple5.test();
	}
}

Output:

CTE

Return type required

Note:

Can we develop a method without return type?

No, we cannot develop any method without return type, return type is mandatory should be either a primitive data type or Derived Data-type or void, but arguments for a method is not mandatory

Example: Non-void method

package com.gs.ilp.corejava.Methods;

public class Simple6 {
	static int square(int num) {
		int sq = num * num;
		return sq;
	}

	public static void main(String[] args) {
		int res = Simple6.square(9);
		System.out.println("Result is :" + res);
	}
}

Output:

Result is :81

Example:

package com.gs.ilp.corejava.Methods;

public class Simple7 {
	static int test() {
		return 90;
	}

	public static void main(String[] args) {
		int res = Simple7.test();
		System.out.println("Result is :" + res);
	}
}

Output:

Result is :90

Example:

package com.gs.ilp.corejava.Methods;

public class Simple8 {
	static double test() {
		return 90.5;
	}

	public static void main(String[] args) {
		System.out.println(Simple8.test());
	}
}

Output:

90.5

Note:

In System.out.println we cannot call the method of type void, which cannot return value. We can call only non-void method.

Example: Void type not allowed in “System.out.println”

package com.gs.ilp.corejava.Methods;

public class Simple9 {
	static void test() {
		return;
	}

	public static void main(String[] args) {
		System.out.println(Simple9.test());// Void type not allowed here
	}
}

Output:

Erroneous tree type:

Note:

If the methods Return type is void, we cannot call it in “System.out.println” or having the “System.out.println” we can only call those methods which will return some value (non-void method).

When we opt for void method?

Whenever we are not expecting any return value from the method after processing then we should develop those methods with return type.

When we opt for non-void method?

Whenever we are expecting the return value from the method and based on that return value if we want to do further processing then we should choose non-void method.

Example: Given 2 integers return true (boolean) if sum of them is 30 or one of them is 30.

package com.gs.ilp.corejava.Methods;

public class Simple10 {
	static boolean test(int n1, int n2) {
		if (n1 + n2 == 30 || n1 == 30 || n2 == 30) {
			return true;
		} else {
			return false;
		}
	}

	public static void main(String[] args) {
		System.out.println("Result is " + Simple10.test(10, 20));
		System.out.println("Result is " + Simple10.test(20, 20));
	}
}

Output:

Result is true

Result is false

Example: Given 2 integers return twice their sum if both are same otherwise return their sum.

package com.gs.ilp.corejava.Methods;

public class Simple11 {
	static int twiceSum(int a, int b) {
		if (a == b) {
			return 2 * (a + b);
		} else
			return (a + b);
	}

	public static void main(String[] args) {
		System.out.println("Result is :" + Simple11.twiceSum(10, 20));
		System.out.println("Result is :" + Simple11.twiceSum(10, 20));
		System.out.println("Result is :" + Simple11.twiceSum(10, 10));
	}
}

Output:

Result is :30

Result is :30

Result is :40

Example: There are 2 monkeys, if both the monkeys are smiling then we are in trouble, if both the monkeys are not smiling then also we are in trouble, Return true if we are in trouble.

package com.gs.ilp.corejava.Methods;

public class Simple12 {
	static boolean trouble(boolean a, boolean b) {
		if (a == true && b == true) {
			return true;
		} else if (a == false && b == false) {
			return true;
		} else {
			return false;
		}
	}

	public static void main(String[] args) {
		System.out.println("Result is:" + Simple12.trouble(true, true));
		System.out.println("Result is:" + Simple12.trouble(false, false));
		System.out.println("Result is:" + Simple12.trouble(true, false));
		System.out.println("Result is:" + Simple12.trouble(false, true));
	}
}

Output:

Result is:true

Result is:true

Result is:false

Result is:false

Last updated