JAVA: CONCEPT OF METHODS IN JAVA🍵

JAVA: CONCEPT OF METHODS IN JAVA🍵

A BRIEF INTRODUCTION TO METHODS IN JAVA

Introduction

Many times, while programming big programs in Java, we use multiple logic, variables, and conditional statements. As our program grows in size, we want our code to look neat, understandable, and less crowded. We want our program to execute more tasks in less code. To reuse code, define the code once, and use it many times, Java uses methods. Let us begin this article by understanding what is method

What are METHODS in Java🍵

A method is a block of code that only runs when it is called.

Methods are used to perform certain actions, and they are also known as functions. You can pass data, known as parameters, into a method. Programmers felt the need to separate specific logic (according to the program) from the logic of the main method to other methods, and this makes code better to understand and clean. We can call the method whenever that specific logic is needed to be executed.

SYNTAX OF A METHOD

Java is an object-oriented programming language. Hence methods are written inside the same class. Methods are used to perform certain actions, and they are also known as functions. It is defined with the name of the method, followed by parentheses (). The syntax of a method is written as follow:

package com.company;
public class Main {
    public static void main(String[] args){
  static void firstMethod( ) {
    // your code
         }
     }
}

Explanation:

  • 'firstMethod( )' is the name of the method. It should be written in camelCase.
  • 'static' means that the method belongs to the Main class and not an object of the Main class.
  • 'void' means that this method does not have a return value.

The following methods return the product of two values:

package com.company;
public class Main {
    public static void main(String[] args){
       int  productMethod( int a, int b){
          int c;
           c = a * b;
          return c;
         }
     }
}

Calling a Method

A method can be called by creating an object of the class in which the method exists followed by the method call:

package com.company
class Base{
       public void int mySum(int a, int b){
               int c = a + b;
               System.out.println("The value of the product is : " + c)
                  }

public class main{
        public static void main(String[] args){
              Base obj = new Base();
              obj.mySum(2, 3);    // Returns 5 as output
          }
    }

The values from the method call (2, 3) are copied to the int a and int b of the function mySum(int a, int b). Even if we modify the values of a and b inside the Method, the values in the main method will not change. The method can be called without creating an object, but it has to be in the same class. See the example below:

public class Main {
  static void myMessage() {
    System.out.println("Enjoy your life!");
  }

  public static void main(String[] args) {
    myMessage();  // Output is - Enjoy your life!
  }
}

Void RETURN TYPE

When we don't want our method to return any value, we use void as the return type. When we want our method to print the value instead of returning it back, we use 'void' as our return type.

static Keyword

'static' is used to associate a method of a given class with the class rather than the object. 'static' method in a class is shared by all the objects.

Parameters and Arguments

Parameters are specified after the method name, inside the parentheses ( ). You can add as many parameters as you want, just separate them with a comma.

public class Main {
  static void myMethod(String name) {
    System.out.println(name + " car ");
  }

  public static void main(String[] args) {
    myMethod("Tesla");  // Outputs Tesla car
    myMethod("Porsche");  // Outputs Porsche car
    myMethod("Maserati");  // Outputs Maserati car
  }
}

When a parameter is passed to the method, it is called an argument. So, from the example above: name is a parameter, while Tesla, Porsche & Maserati are arguments.

Multiple Parameters

Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.

public class Main {
  static void myMethod(String name, int speed) {
    System.out.println(name + " car's top speed is " + speed + "mph");
  }

  public static void main(String[] args) {
    myMethod("Tesla", 216);   // Tesla car's top speed is 216 mph
    myMethod("Porsche", 182);   // Porsche car's top speed is 182 mph
    myMethod("Honda", 137 );    // Honda car's top speed is 132 mph
  }
}

METHOD OVERLOADING IN JAVA

Two or more methods can have the same name, but different parameters. Such methods are called overloaded methods. Consider the following example, which has two methods that add number of a different types:

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

static double plusDouble(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusInt(8, 5);
  double myNum2 = plusDouble(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

JAVA SCOPE

In Java, variables are only accessible inside the region they are created. This is called the scope of that variable.

Variables declared directly inside a method are available anywhere in the method. See the following example:


public class Main {
  public static void main(String[] args) {

    // Code here CANNOT use x

    int x = 100;

    // Code here can use x
    System.out.println(x);
  }
}

Variables declared inside blocks of code are only accessible by the code between the curly braces{ }, which follows the line in which the variable was declared:

public class Main {
  public static void main(String[] args) {

    // Code here CANNOT use x

    { // This is a block

      // Code here CANNOT use x

      int x = 100;

      // Code here CAN use x
      System.out.println(x);

   } // The block ends here

  // Code here CANNOT use x

  }
}

RECURSION

When a function in Java calls itself, such a calling is called Recursion. Let us understand recursion through an example, as understand it may be a bit difficult at the beginning. The best way to figure out how it works is to experiment with it. Let us find out the factorial of a number using recursion.

package com.comapny;

public class recursion {
         //factorial(n) = n*n-1......*1;
        //factorial(5) = 5*4*3*2*1
        static int factorial(int n){
        if(n==0 ||  n==1){
            return 1;
        }
        else{
            return n*factorial(n-1);
        }

    }

    public static void main(String[] args) {
            int n = 4;
        System.out.println("The value of factorial n is : " + factorial(n));
    }
}

THAT'S A WRAP!

Thank you for Reading my Article📄 Hope it adds value to the community💙

Follow me on Twitter @vinayakstwt🕊️

Follow me on Hashnode VINAYAK PANCHAL