13) Methods
Last updated
Last updated
A method is a group of statements identified with a name. Methods are used to define the behavior of an object.
Now you defined a method, you need to use it. For that, you have to call the method. Here's how:
This statement calls the myMethod()
method that was declared earlier.
While Java is executing the program code, it encounters myMethod();
in the code.
The execution then branches to the myFunction()
method, and executes code inside the body of the method.
After the codes execution inside the method body is completed, the program returns to the original state and executes the next statement.
Let's see a Java method in action by defining a Java class.
When you run the program, the output will be:
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.
When you run the program, the output will be:
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.
Let's take an example of method returning a value.
When you run the program, the output will be:
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.
When you run the program, the output will be:
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.
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,
When you run the program, the output will be:
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.
When you run the program, the output will be:
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.
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?
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.
Part-1:
The following process takes place when we execute a program:
Program execution happens in RAM.
RAM memory is divided into 2 types,
Stack: For execution purpose.
Heap: For Storage purpose.
JVM will be loaded onto stack automatically.
JVM will call class loader (Built-in Library).
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:
JVM will check the availability of main method in the static pool, if its available, JVM will load the main method for execution purpose.
JVM will pass the control to main method so that main method can execute its statement.
Part-3:
From main method, some method is called by using static pool name i.e.,
Classname.someMethod(1);
someMethod() will be loaded onto the stack.
Control will pass to the someMethod(), so it can executes its statement.
someMethod() after its execution will return the control back to main method.
someMethod() will be erased from the stack.
Main method resume its execution and finally it will return the control back to JVM.
Main method will be erased from stack.
JVM will call Garbage Collector(Daemon Thread).
Garbage Collector will clear the contents from the HEAP memory.
JVM will exit from the stack.
More Examples:
Example:
Output:
Result is: 27
Note:
void means return no value but return control.
If the method return-type is void, then that method cannot return any value after processing.
If any methods return-type is void, then developing return statement is not mandatory.
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.
Developing methods with arguments is not mandatory i.e., we can develop methods without arguments.
The methods without arguments cannot receive any input at the time of method invocation.
Example: Interview Question
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
Output:
Result is :81
Example:
Output:
Result is :90
Example:
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”
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.
Output:
Result is true
Result is false
Example: Given 2 integers return twice their sum if both are same otherwise return their sum.
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.
Output:
Result is:true
Result is:true
Result is:false
Result is:false