# 13) Methods

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LajnLQDzdlBU6SG_MT7%2F-Lajo8gdtBqMsrW1wQJX%2FScreen%20Shot%202019-03-24%20at%206.36.19%20PM.png?alt=media\&token=a1775d12-5c32-449b-beb0-b42d7dda30a9)

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

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTOJqBOl2jDzohF3hJT%2F-LTOKCMjld0mEOVYeHlg%2FScreen%20Shot%202018-12-10%20at%2011.44.51%20PM.png?alt=media\&token=71e7f8ff-0b46-4137-b083-73dde951c70b)





![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTOJqBOl2jDzohF3hJT%2F-LTOKG24lAnmDJYoEcEV%2FScreen%20Shot%202018-12-10%20at%2011.45.03%20PM.png?alt=media\&token=b83f3037-5243-46fa-b400-6f2b1473d582)







#### 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.

![How method call works in Java?](https://cdn.programiz.com/sites/tutorial2program/files/calling-function-java.jpg)

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.

```java
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.

```java
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.

```java
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.

![Returning Value from a Method in Java](https://cdn.programiz.com/sites/tutorial2program/files/returning-value-from-method.jpg)

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

```java
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.

![Passing arguments and returning a value from a method in Java](https://cdn.programiz.com/sites/tutorial2program/files/passing-arguments-returning-value.jpg)

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,

```java
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

```java
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.&#x20;
2. RAM memory is divided into 2 types,&#x20;
   1. Stack: For execution purpose.&#x20;
   2. Heap: For Storage purpose.&#x20;
3. JVM will be loaded onto stack automatically.&#x20;
4. JVM will call class loader (Built-in Library).&#x20;
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.&#x20;

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.&#x20;

**Part-3:**

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

Classname.someMethod(1);&#x20;

1. someMethod() will be loaded onto the stack.&#x20;
2. Control will pass to the someMethod(), so it can executes its statement.&#x20;
3. someMethod() after its execution will return the control back to main method.&#x20;
4. someMethod() will be erased from the stack.&#x20;
5. Main method resume its execution and finally it will return the control back to JVM.&#x20;
6. Main method will be erased from stack.&#x20;
7. JVM will call Garbage Collector(Daemon Thread).&#x20;
8. Garbage Collector will clear the contents from the HEAP memory.&#x20;
9. JVM will exit from the stack.&#x20;

**More  Examples:**

**Example:**

```java
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.&#x20;
2. If the method return-type is void, then that method cannot return any value after processing.&#x20;
3. If any methods return-type is void, then developing return statement is not mandatory.&#x20;
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.&#x20;
5. Developing methods with arguments is not mandatory i.e., we can develop methods without arguments.&#x20;
6. The methods without arguments cannot receive any input at the time of method invocation.&#x20;

**Example:** **Interview Question**&#x20;

```java
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**&#x20;

```java
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:**

```java
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:**

```java
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”&#x20;

```java
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:**

**I**f 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.**&#x20;

```java
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.**&#x20;

```java
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.**

```java
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
