WEB DEVELOPER SITE
PHP7
 

Java Methods


Method is a set of statements to perform an operation, methods are also known as procedures or functions.


Creating Method

following example to explain the syntax of a method −

Syntax

public static int methodName(int x, int y) {
   // body
}
Here,
  • public static − modifier
  • int− return type
  • methodName− name of the method
  • x, y− formal parameters
  • int x, int y− formal parameters

Syntax

modifier returnType nameOfMethod (Parameter List) {
   // method body
}
The syntax shown above includes −
  • modifier: It state that access type of the method and it is optional to use.
  • returnType : It defines Method may return a value.
  • nameOfMethod: It defines method name. signature consists of the method name and the parameter list.
  • Parameter List : It define the type, order, and number of parameters of a method
  • method body: The method body defines what the method does with the statements.
Example Here is the source code of the above defined method called min().
by using this method takes two parameters num1 and num2 and returns the maximum between the two
/** the snippet returns the minimum between two numbers */

public static int minFunction(int x1, int y2) {
   int min;
   if (x1 > y2)
      min = x2;
   else
      min = x1;

   return min; 
}


Method Calling

Method returns a value or returning nothing it mean no return value.
When a program invokes a method, the program control gets transferred to the called method
returns control to the caller in two conditions such as:
  • the return statement is executed.
  • it reaches the method ending closing brace.
System.out.println("This is welookups.com!");
Following is the example to demonstrate we can define a method and we call it
public class ExampleMinNumber {
   
   public static void main(String[] args) {
      int x = 22;
      int y = 14;
      int z = minFunction(x, y);
      System.out.println("Minimum Value = " + z);
   }

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

      return min; 
   }
}

Run example »
Output Minimum Value = 14

The void Keyword

void keyword do not return any value. it call to a void method must be a statement.

Example
public class ExampleVoid {

   public static void main(String[] args) {
      methodchoosePoints(221.2);
   }

   public static void methodchoosePoints(double points) {
      if (points >=198.4) {
         System.out.println("Choose:B1");
      }else if (points >= 190.5) {
         System.out.println("Choose:B2");
      }else {
         System.out.println("Choose:B3");
      }
   }
}
Run example »
Output Choose:B1

Passing Parameters by Value

Passing by value means calling a method with a parameter (argument). Example
public class swappingExample {

    public static void main(String[] args) {
        int x = 12;
        int b = 24;
        System.out.println("Before swapping, x = " + x + " and b = " + b);

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

    public static void swapFunction(int x, int b) {
        System.out.println("Before swapping(Inside), x = " + x + " b = " + b);

        // Swap n1 with n2
        int c = x;
        x = b;
        b = c;
        System.out.println("After swapping(Inside), x = " + x + " b = " + b);
    }
}

Run example »
output
Before swapping, x = 12 and b = 24
Before swapping(Inside), x = 12 b = 24
After swapping(Inside), x = 24 b = 12
**Now, Before and After swapping values will be same here**:
After swapping, x = 12 and b is 24

Method Overloading

Method Overloading define as Two or more methods having the same method name and same arugment but different parameters. A method has the same method name, type, number of parameters, etc.
Example
public class ExampleOverloading {

   public static void main(String[] args) {
      int a = 18;
      int x = 2;
      double z = 4.2;
      double d = 6.8;
      int result1 = minFunction(a, x);
      
      // same function name with different parameters
      double result2 = minFunction(z, d);
      System.out.println("Minimum Value = " + result1);
      System.out.println("Minimum Value = " + result2);
   }

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

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

      return min; 
   }
}


Run example »
Output
Minimum Value = 2
Minimum Value = 4.2


The minimum number from integer and double types is the result type.

Using Command-Line Arguments

If you want to pass some information into a program when you run it.This can be done by passing command-line arguments to main( ).

command-line arguments inside a Java program stored as strings in the String array passed to main( )

Example public class CommandLine { public static void main(String args[]) {
for(int i = 0; i System.out.println("args[" + i + "]: " + args[i]);
}
}
}
Try executing this program as shown here −
$java CommandLine this is simple command  line 258 

This will produce the following result
Output
args[0]: this
args[1]: is
args[2]: simple
args[3]: command
args[4]: line
args[5]: 258

The Constructors

Constructor has the same name as that of class,it invokes when an object of class is created and can't called explicitly. A constructor is declared like a method, but it has no return type. Example
// A simple constructor.
class MyMembers {
   int y;

   // Following is the constructor
   MyMember() {
      y = 25;
   }
}

You will have to call constructor to initialize objects as follows −
public class ConsDemo {

   public static void main(String args[]) {
      MyMember t1 = new MyMember();
      MyMember t2 = new MyMember();
      System.out.println(t1.y + " " + t2.y);
   }
}

Output

25 25

Parameterized Constructor

First constructor that accepts one or more parameters.Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor's name.
// A simple constructor.
class MyMember {
   int a;
   
   // Following is the constructor
   MyMember(int i ) {
      a = i;
   }
}
You will need to call a constructor to initialize objects as follows −


public class ConsDemo {

   public static void main(String args[]) {
      MyMember a1 = new MyMember( 40 );
      MyMember a2 = new MyMember( 50 );
      System.out.println(a1.x + " " + a2.x);
   }
}
 

Output
40 50

Variable Arguments(var-args)

public class VarargsDemo {

   public static void main(String args[]) {
      // Call method with variable args  
	   printMax(18, 1, 2, 4, 12.9);
      printMax(new double[]{4, 5, 6});
   }

   public static void printMax( double... numbers) {
      if (numbers.length == 0) {
         System.out.println("No argument passed");
         return;
      }

      double result = numbers[0];

      for (int i = 1; i <  numbers.length; i++)
      if (numbers[i] >  result)
      result = numbers[i];
      System.out.println("The max value is " + result);
   }
}
Output
The max value is 18.0
The max value is 6.0

The finalize( ) Method

inalize method in java is a special method much like the Main method in java. finalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc.
protected void finalize( ) {
   // finalization code here
}