C
C
Core Java
Search…
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:
1
myMethod();
Copied!
This statement calls the myMethod() method that was declared earlier.
How method call works in Java?
    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.
1
class Main {
2
3
public static void main(String[] args) {
4
System.out.println("About to enter a method.");
5
6
// method call
7
printSomething();
8
9
System.out.println("Method was executed successfully!");
10
}
11
12
// method definition
13
private static void printSomething(){
14
System.out.println("Printing from inside printSomething()!");
15
}
16
}
Copied!
When you run the program, the output will be:
1
About to enter a method.
2
Printing from inside printSomething()!
3
Method was executed successfully!
Copied!
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.
1
class Main {
2
3
public static void main(String[] args) {
4
5
Output obj = new Output();
6
System.out.println("About to encounter a method.");
7
8
// calling myMethod() of Output class
9
obj.myMethod();
10
11
System.out.println("Method was executed successfully!");
12
}
13
}
14
15
class Output {
16
17
// public: this method can be called from outside the class
18
public void myMethod() {
19
System.out.println("Printing from inside myMethod().");
20
}
21
}
Copied!
When you run the program, the output will be:
1
About to encounter a method.
2
Printing from inside myMethod().
3
Method was executed successfully!
Copied!
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.
1
class SquareTest {
2
public static void main(String[] args) {
3
int result;
4
result = square();
5
System.out.println("Squared value of 12 is: " + result);
6
}
7
8
public static int square() {
9
// return statement
10
return 12 * 12;
11
}
12
13
}
Copied!
When you run the program, the output will be:
1
Squared value of 12 is: 144
Copied!
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.
Returning Value from a Method in Java
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

1
public class SquareMain {
2
3
public static void main(String[] args) {
4
int result, n;
5
6
n = 3
7
result = square(n);
8
System.out.println("Square of 3 is: " + result);
9
10
n = 4
11
result = square(n);
12
System.out.println("Square of 4 is: " + result);
13
}
14
15
static int square(int i) {
16
return i * i;
17
}
18
}
Copied!
When you run the program, the output will be:
1
Squared value of 3 is: 9
2
Squared value of 4 is: 16
Copied!
Now, the square() method returns the squared value of whatever integer value passed to it.
Passing arguments and returning a value from a method in Java
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.
1
result = getSquare(n);
Copied!
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,
1
public class Calculator{
2
3
public static int calculateSum (int a, int b) {
4
return a + b;
5
}
6
7
public static int calculateProduct(int x, int y) {
8
return x * y;
9
}
10
11
public static void main(String[] args) {
12
System.out.println("10 + 20 = " + calculateSum (10, 20));
13
System.out.println("20 x 40 = " + calculateProduct(20, 40));
14
}
15
}
Copied!
When you run the program, the output will be:
1
10 + 20 = 30
2
20 x 40 = 800
Copied!
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

1
public class Utility {
2
3
// method defined
4
private static int getSquare(int x){
5
return x * x;
6
}
7
8
public static void main(String[] args) {
9
for (int i = 1; i <= 6; i++) {
10
11
// method call
12
result = getSquare(i)
13
System.out.println("Square of " + i + " is : " + result); }
14
}
15
}
Copied!
When you run the program, the output will be:
1
Square of 1 is : 1
2
Square of 2 is : 4
3
Square of 3 is : 9
4
Square of 4 is : 16
5
Square of 5 is : 25
6
Square of 6 is : 36
Copied!
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.
1
result = getSquare(i);
Copied!
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:
1
package com.gs.ilp.corejava.Methods;
2
3
public class Simple2 {
4
static void cube(int num) {
5
int c = num * num * num;
6
System.out.println("Result is: " + c);
7
}
8
9
public static void main(String[] args) {
10
Simple2.cube(3);
11
}
12
}
Copied!
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
1
package com.gs.ilp.corejava.Methods;
2
3
public class Simple5 {
4
static test()// Return type required
5
{
6
System.out.println("Running test method()");
7
}
8
9
public static void main(String[] args) {
10
Simple5.test();
11
}
12
}
Copied!
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
1
package com.gs.ilp.corejava.Methods;
2
3
public class Simple6 {
4
static int square(int num) {
5
int sq = num * num;
6
return sq;
7
}
8
9
public static void main(String[] args) {
10
int res = Simple6.square(9);
11
System.out.println("Result is :" + res);
12
}
13
}
Copied!
Output:
Result is :81
Example:
1
package com.gs.ilp.corejava.Methods;
2
3
public class Simple7 {
4
static int test() {
5
return 90;
6
}
7
8
public static void main(String[] args) {
9
int res = Simple7.test();
10
System.out.println("Result is :" + res);
11
}
12
}
Copied!
Output:
Result is :90
Example:
1
package com.gs.ilp.corejava.Methods;
2
3
public class Simple8 {
4
static double test() {
5
return 90.5;
6
}
7
8
public static void main(String[] args) {
9
System.out.println(Simple8.test());
10
}
11
}
Copied!
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”
1
package com.gs.ilp.corejava.Methods;
2
3
public class Simple9 {
4
static void test() {
5
return;
6
}
7
8
public static void main(String[] args) {
9
System.out.println(Simple9.test());// Void type not allowed here
10
}
11
}
Copied!
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.
1
package com.gs.ilp.corejava.Methods;
2
3
public class Simple10 {
4
static boolean test(int n1, int n2) {
5
if (n1 + n2 == 30 || n1 == 30 || n2 == 30) {
6
return true;
7
} else {
8
return false;
9
}
10
}
11
12
public static void main(String[] args) {
13
System.out.println("Result is " + Simple10.test(10, 20));
14
System.out.println("Result is " + Simple10.test(20, 20));
15
}
16
}
Copied!
Output:
Result is true
Result is false
Example: Given 2 integers return twice their sum if both are same otherwise return their sum.
1
package com.gs.ilp.corejava.Methods;
2
3
public class Simple11 {
4
static int twiceSum(int a, int b) {
5
if (a == b) {
6
return 2 * (a + b);
7
} else
8
return (a + b);
9
}
10
11
public static void main(String[] args) {
12
System.out.println("Result is :" + Simple11.twiceSum(10, 20));
13
System.out.println("Result is :" + Simple11.twiceSum(10, 20));
14
System.out.println("Result is :" + Simple11.twiceSum(10, 10));
15
}
16
}
Copied!
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.
1
package com.gs.ilp.corejava.Methods;
2
3
public class Simple12 {
4
static boolean trouble(boolean a, boolean b) {
5
if (a == true && b == true) {
6
return true;
7
} else if (a == false && b == false) {
8
return true;
9
} else {
10
return false;
11
}
12
}
13
14
public static void main(String[] args) {
15
System.out.println("Result is:" + Simple12.trouble(true, true));
16
System.out.println("Result is:" + Simple12.trouble(false, false));
17
System.out.println("Result is:" + Simple12.trouble(true, false));
18
System.out.println("Result is:" + Simple12.trouble(false, true));
19
}
20
}
Copied!
Output:
Result is:true
Result is:true
Result is:false
Result is:false
Last modified 2yr ago
Copy link