Learn method in java

Hey guys!! Welcome to flower brackets blog. Today we are going to learn method in java.

Learn method in java

A method is a group of statements which executes some logic and can be used multiple times.

Also read – Difference between == and equals method in java

Let’s see syntax of a method,

modifier returnType methodName(Parameter List) 
{
   // method body
}

public static int firstMethod(int x, int y)
{
 
}

In the above syntax, we have “public static” modifier. public static can be only private or private static or protected.

Click here to learn static keyword

“int” return type returns integer. “firstMethod” is name of the method and “int x” and “int y” are parameters. They can be left empty or you can pass parameters. Now let’s see an example,

public static int sum(int x, int y)
{
   return x + y;
}

method sum has two parameters “int x” and “int y” and returns its sum.


Calling a method

There are two ways to call a method, one, method that returns a value and another returning void or nothing.

So when main method calls or invokes a method, control gets shifted to the called method then the return type returns to the caller.

class MethodDemo
{
   public static void main(String[] args)
   {
      int x = 5;
      int y = 3;
      int result = multiply(x, y);
      System.out.println(result);
   }
   public static int multiply(int a, int b)
   {
      return a * b;
   }
}

Output:

15


On void return type

Void is a keyword in java. Void is generally used if a method simply executes a block of statements which do not return any value.

public class VoidDemo 
{
   public static void main(String[] args) 
   {
      // calling void method
      // this is a statement
      grade(98);
   }
   public static void grade(int percent) 
   {
      if(percent >= 95) 
      {
         System.out.println("Rank");
      }
      else if(percent >= 80) 
      {
         System.out.println("Distinction");
      }
      else 
      {
         System.out.println("Average");
      }
   }
}

Output:

Rank


In java, we can pass the values to method in two ways, one, passing by value and another passing by reference.

Passing parameters by value

Passing by value is, when method is called with parameter. Here method parameters are of java primitive type that is, integer, float, char, boolean.

Also read – how to remove element from arraylist in java

If value is changed in “called” method, that change will not reflect in “calling” method. Here variables will be stored in different memory locations and independent of each other.

public class PassingByValue 
{
   public static void main(String[] args) 
   {
      int x = 5;
      System.out.println("Before calling add method : " + x);
      add(x);
   }
   public static void add(int a)
   {
      System.out.println("In add method : " + a);
      a = 2; // value changed here will not affect variable x
      System.out.println("In add method : " + a);
   }
}

Output:

Before calling add method : 5
In add method : 5
In add method : 2

Passing parameters by reference

Now here, when we pass non java primitive type to a method then reference will be passed. For example,

public class PassingByReference 
{
   public static void main(String[] args) 
   {
      int arr[] = {66, 56, 89};
      System.out.println("Before calling add method : " + arr[1]);
      add(arr);
      System.out.println("After calling add method : " + arr[1]);
   }
   // when arr[] is passed to add method, at this point
   // memory address of arr[] is passed to method parameter i.e., num[].
   // Hence memory address of arr[] will be stored in num[] and
   // arr[] and num[] will be pointing to same memory location.
   public static void add(int num[])
   {
      System.out.println("First element : " + num[1]);
      num[1] = 23;
      System.out.println("First element : " + num[1]);
   }
}

Output:

Before calling add method : 56
First element : 56
First element : 23
After calling add method : 23


Method overloading in java

Method overloading in java is when a class having different methods with same name but with different parameters or signature. Method overloading makes a program more readable. Here’s an example,

class Multiply
{
   static int multiply(int a, int b)
   {
      return a * b;
   }
   // same name different parameters
   static double multiply(double a, double b)
   {
      return a * b;
   }
}

public class MethodOverloadingDemo 
{
   public static void main(String[] args) 
   {
      System.out.println(Multiply.multiply(6, 6));
      System.out.println(Multiply.multiply(56.5, 89.8));
   }
}

Output:

36
5073.7

Command line arguments

Command line arguments helps in passing information to java program main() method.

We have come across one common argument which we pass in main method, that is, variable “String args”. Let’s see an example,

class Demo
{
   // here variable args can be of any name
   // like var, a or str
   public static void main (String args[])
   {
      System.out.println("Argument : " + args[0]);
   }
}

Here we are printing argument passed by the user. After saving this file program is compiled,

javac Demo.java

After successful compilation we get,

Demo.class

For execution we write

java Demo output

So the output will be,

Argument output

“output” gets stored in args[0] and appends with Argument. We can add any number of arguments using “for loop”. For example,

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

Output:

args[0] : Hello

args[1] : World

args[2] : Java

Also read – learn this keyword in java


Var-args (Variable arguments in java)

If user doesn’t know how many parameters or arguments to pass to a method then var-args or variables arguments is used. For example,

public class VargsDemo 
{
   public static void main(String[] args) 
   {
      Demo obj = new Demo();
      obj.print(8, 6, 2);
   }
}

class Demo
{
   // only one variable parameter specified
   public void print(int... x)
   {
      for(int a : x)
      {
         System.out.println(a);
      }
   }
}

Output:

8
6
2

Here the syntax for varargs is,

datatypeName... parameterName

Please note that after “datatypeName” there are three dots and there should be only three dots. Else program will not execute.

Also data type should be same as calling method. In the above program we have used enhanced “for loop” to print values because we are passing three integer values.

If we are passing one value then we can use “System.out.println” to print value.


finalize method in java

In java when we create an object using “new” keyword it occupies certain memory to store data.

After its purpose is completed it should be released. For this in java we have garbage collector which by default releases these objects.

So that memory released will be used by another object. Normally garbage collector is called explicitly because it executes by itself to release resources and provide this memory to another object.

But in java, before garbage collector is called finalize() method is called. This method is used to perform closing operation.

finalize() method is available in java.lang.object class and its syntax is,

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

This method has one disadvantage, that is, when finalize method is called? Since finalize() method access specifier is “protected” we cannot access outside class and we don’t know garbage collector will call this method or not.

Instead we can use other methods like close() and destroy().

Related Posts