Method

A class defines state and behavior for a group of objects. States of an objects are represented by instance variables whereas behaviors are represented by methods. A method in java is group of statements which are used to perform a particular task. Methods are similar to functions in C.

Methods appear inside class bodies. They contain local variable declarations and other Java statements which are expected to be executed in response of a behavior of the objects. Methods are how we communicate with objects. When we invoke or call a method we are asking the object to carry out a task.

Creating methods has several advantages such as code reusability, modularity and an optimized coding model.


Syntaxfor methods: 
<Access Specifier><Modifier><Return Type><Method Name> (list of parameter) 
{ 
 //body of the method 
} 

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

Access Specifiers:

The Access Specifiers are optional (if not specified default will be taken) in method definition. They are used to define the visibility of the methods. The Access Specifiers such as public, private or protected can be used for the same.

Modifiers::

The modifier, which is optional, tells the compiler how to call the method. The modifiers such as static, final or abstract can be can be while defining a method.

Return Type:

A method may return a value. The return type is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the return type is the keyword void.

Method Name:

This is the actual name of the method which can be used to call or invoke the method when required. The method name and the parameter list together constitute the method signature.

Parameters:

A parameter is like a placeholder. When a method is invoked, we pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.

Method Body:

The method body contains a collection of statements that define what the method does. It may include simple statement to complex computations or any programming constructs such as conditional constructs, looping constructs etc.

Example :
Here is a method inside a class which add two numbers and display the result.


class Sum 
{ 
	//instance variables 
	int number1,number2,number3; 
	//method without parameter and without returning value 
	public void add() 
	{  	
		number1=25; 
		number2=30;  
		number3=number1+number2;  
		System.out.println(“Sum of ?+number1+? and ?+number2+? is ?+number3); 
	} 
} 

The above problem can also be solved using a method with returning value and accepting parameters


class Sum
{ 
	public int add(int a,int b)  
	{   
		return a+b;  
	}
} 
 
 
 // Output: 
 Sum of 25 and 30 is 55.

When any return type is specified (except void) in a method definition the method must explicitly return a value of the specified type. All code path inside the method should include a return statement. For example if a method is using conditional statements such as if…else, where either if block is executed or else is executed and method has to return a value then both the block must specify a return statement.

Example:


class Maximum 
{   
	public int max(int a, int b)   
	{   
		if(a>b)     
		return a;   
		else     
		return b;   
	} 
} 

Note that the return statement is the last statement executed by the method. Return statement causes control to get out of the method body with returning value to calling method.

Static Methods

Methods which are declared with static modifiers are called as static or class methods. Static methods does not need to be invoked through the instance of the class. They can be directly invoked by the class.

Defining any method or variable as static makes it associated with the class directly instead of the instances. Means that there exists only one copy of the method regardless of number of instance being created at runtime.

A static method can only make use of static variable. However a static variable can be used in a non-static method as well. All the variables declared inside a static method are implicitly static.

A static method in the java program can be defined in the following way:


Class Test 
{  
	public static void show()  
	{   
		System.out.println(“This is a static method?); 
	} 
	public static void main(String ar[]) 
	{
		Test.show(); // calling a static method show(). 
	} 
}

Method Calling

For using a method, it should be invoked. There are two ways to called a method i.e., method returns a value or returning nothing (no return value).

The simple process of method calling is, When a program called a method, the program control gets transferred to the called method. Then this called method returns control to the caller in two conditions, when −

  • return statement is executed.
  • And it reaches the method ending closing brace.

The methods returning void is considered as call to a statement. Lets consider an example −


System.out.println("This is a method!");

The method returning value can be understood by the following example − int result = sum(16, 19);

Following is the example to demonstrate how to define a method and how to call it −

Example:


public class ExampleMinNumber {
   
   public static void main(String[] args) {
      int a = 10;
      int b = 7;
      int c = minFun(a, b);
      System.out.println("Minimum Value is  = " + c);
   }

   /** returns the minimum of two numbers */
   public static int minFun(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}

This will produce the following output −


Minimum value is = 7

The void Keyword

The void keyword allows us to create methods which is not return a value. Here, in this below example we are considering a void method methodRank. This is a void method, which do not return any value.

Call to a void method that must be a statement i.e. methodRank (250.7);. It is a Java statement which ends with a semicolon.

Example:



public class ExampleVoidKey {

   public static void main(String[] args) {
      methodRank(250.7);
   }

   public static void methodRank(double points) {
      if (points >= 200.5) {
         System.out.println("Rank is:A1");
      }else if (points >= 120.4) {
         System.out.println("Rank is:A2");
      }else {
         System.out.println("Rank is:A3");
      }
   }
}

This will produce the following output;


Rank is :A1

Passing Parameters by Value

While work under the calling process, arguments are to be passed. These should be in same order as their respective parameters in method specification. Parameters can be passed by the value or by the reference.

Passing Parameters by the Value means calling a method with a parameter. Through, the argument value is passed to the parameter.

Example
The below program shows an example of passing parameter by the value. values of the arguments remains as the same even after the method invocation.


public class swapExample {

   public static void main(String[] args) {
      int a = 35;
      int b = 45;
      System.out.println("Before swapping number, a = " + a + " and b = " + b);

      // call the swap method
      swapFunction(a, b);
      System.out.println("\n**Now, Before and After swapping number values will be same here**:");
      System.out.println("After swapping number, a = " + a + " and b is " + b);
   }

   public static void swapFunction(int a, int b) {
      System.out.println("Before swapping(Inside)number , a = " + a + " b = " + b);
      
      // Swap n1 with n2
      int c = a;
      a = b;
      b = c;
      System.out.println("After swapping(Inside)number , a = " + a + " b = " + b);
   }
}

This will produce the following result −


Before swapping number, a = 35 and b = 45
Before swapping(Inside) number, a = 35 b = 45
After swapping(Inside)number , a = 45 b = 35

**Now, Before and After swapping number  values will be same here**:
After swapping number, a = 35 and b is 45

Method Overloading

When a class have two or more methods by the same name but different parameters, it is known as method overloading. It is different from the overriding. In overriding, a method has the same method name, type, and number of parameters, etc.

Let’s discussed example earlier for finding minimum numbers of integer type. If, we want to find the minimum number of double type. Then the concept of overloading will be introduced to create two or more methods with the same name but different parameters.

The following example explains it −

Example


public class ExampleOverloadingMethod {

   public static void main(String[] args) {
      int a = 11;
      int b = 6;
      double c = 7.3;
      double d = 9.4;
      int result1 = minFunction(a, b);
      
      // same function name but with different parameters
      double result2 = minFunction(c, d);
      System.out.println("Minimum Value is = " + result1);
      System.out.println("Minimum Value is = " + result2);
   }

   // for integer type
   public static int minFun(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
   
   // for double
   public static double minFun(double n1, double n2) {
     double min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}

This will produce the following result −


Minimum Value is = 6
Minimum Value is = 7.3

Overloading methods is make program readable. Here, two methods are given by the same name but with different parameters. The minimum number from integer type and double types is the result.

Using Command-Line Arguments

Sometimes you want to pass some information into a program when you run it. This is accomplished by passing command-line arguments to main( ).

A command line argument is the information that follows the name of the program directly on the command line when executed. It is easy to access the command line arguments within the Java program.

They are stored as strings in the String array and passed to main( ).

Example : this program displays all of the command-line arguments that −


public class CmdLine {

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


executing this program as shown −
$java CommandLine       this is a command line 300 -200
This will produce the following output −

Output
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 300
args[6]: -200

The this keyword

This is a keyword in java that is used as a reference to the object of the current class, in which there is an instance method or constructor. By using it you can refer to class members like creators, variables and methods.

Note – a keyword this is used only within instance and methods or constructors
this-keyword-in-java In general, the keyword this is used to −
• If they have the same names within the same constructor or method, separate the instance variable from the local variable

class Student {
   int age;   
   Student(int age) {
      this.age = age;	
   }
}

• Call one type constructor (parametric constructor or default) in one class from one to another. this is known as explicit constructor invocation.


class Student {
   int age
   Student() {
      this(20);
   }
   
   Student(int age) {
      this.age = age;	
   }
}

Example
Here's an example that uses this keyword to access members of the class. Copy and paste the following program in a file with the name, This_Example.java.


public class This_Example {
   // Instance variable is num
   int num = 10;
	
   This_Example() {
      System.out.println("This is an example of  keyword this");	
   }

   This_Example(int num) {
      // calling the default constructor
      this();
      
      // Assigning local variable num to the instance variable num
      this.num = num;	   
   }
   
   public void greet() {
      System.out.println("Hi Welcome to java");
   }
      
   public void print() {
      // here Local variable num
      int num = 20;
      
      // Print the local variable
      System.out.println("value of local variable num : "+num);
      
      // Print the instance variable
      System.out.println("value of instance variable num : "+this.num);
      
      // calling the greet method of a class
      this.greet();     
   }
   
   public static void main(String[] args) {
      // It Instantiating the class
      This_Example obj1 = new This_Example();
      
      // calling the print method
      obj1.print();
	  
      // Passing a new value to the num variable through the parametrized constructor
      This_Example obj2 = new This_Example(30);
      
      // calling the print method again
      obj2.print(); 
   }
}

This will produce the following output −


This is an example program of keyword this 
value of local variable num  : 20
value of instance variable num  : 10
Hi Welcome to Java
This is an example program of keyword this 
value of local variable num  : 20
value of instance variable num  : 30
Hi Welcome to Java

The finalize( ) Method

It is possible to define a method that will be called by the garbage collector right before the final destruction of the object

This method is called finalize( ), and It can be used to ensure that an object is clearly finished.

For example, you can use finalize( ) to make sure that the open file owned by that object is closed.

To add a finalizer to a class, you simply define the finalize( ) method. The Java Runtime calls to that method whenever it is going to recycle an object in that class.

Inside the finalize( ) method, You will specify actions that must be done before the object is destroyed.

The finalize( ) method has this general form –


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

Here, the keyword protected is a specifier one that prevents access to finalize( ) by the code defined outside of its class. This means that you cannot know when if finalize( ) will be executed.

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to chercher.tech@gmail.com for any queries

If you already registered then please do check your email for the Webex link
 
Join My Facebook Group