Methods in Java

Till now, we have created so many Java applications/programs, which included different Java classes, which further consisted of instance variables and methods. Also, we have seen most of the work in the Java programs is done through methods. Even the main driver of every program is also a method - the main method. In this tutorial, we'll be focussing upon methods, What are methods, How to declare methods in Java, How to call Java methods and Types of Methods in Java

What are methods in Java?

Methods are generally a group of statements that perform a specific task or operation only when called for execution. These are the most flexible and powerful aspects of any programming language. They are used to provide re-usability to the code as a method(technically with public access mode) written in any class of a java program, can be used by any other class of a other program also. This reduces the re-writing of code, thus increasing efficiency and saving time. 

Java also enables us to pass data or values as parameters to the method, this makes Java pass by value. As Java only passes objects by values, not by reference.

It also enables easy modification, that means if we have to change something in a code, we only have to make changes in the method and those changes would be reflected in the whole program. And even spotting the errors would also be easy with such approach. 

In other languages, methods are also regarded as functions. They also have the same task of making the code efficient and reusable. 

Types of methods in Java

There are 2 types of methods in Java : Pre-defined methods and User-defined methods

Predefined methods in Java

Predefined methods are built-in Java methods that are already defined in the different Java class libraries. These are also known Standard library methods. There main advantage is that, they are already defined and we can call them at anytime anywhere in the program. These predefined methods are defined in specific Java classes. 

Examples of predefined Java methods defined in the java.math class : abs(), acos(), asin(), floor(), hypot() etc. 

The following program describes the usage of Math.sqrt() method, which is used to find the square root of the number passed to it. It returns a double value.

Program: 
public class squareRoot {
   public static void main(String[] args) {
      double x = 9;
      System.out.println("Math.sqrt(" + x + ")= " + Math.sqrt(x));
   }
}


OUTPUT

Math.sqrt(9)= 3.0

User defined methods in Java

These are Java methods that the users/programmers define themselves for their sake of simplicity. These are not already defined in the Java classes, users can create any method any time for any particular operation. And these methods are known as User-defined Java methods.
These are very much helpful as they break complex programs into smaller pieces, decreasing the complexity and increasing efficiency.

The following topics are about declaring and calling User-defined Java methods.

Declaring a method in Java

In Java, Methods must be declared inside Classes. Method declaration in Java is also very simple like other programming languages. 

While declaring methods in Java, we have to specify the following aspects:

> Access modifier : Specifying whether the method has public visibility, private visibility or protected visibility or default. These various modes defines, where all the method would be available for use.
  • Public mode : Something declared with public access mode, will be accessible from anywhere in the same package and also even in other packages(all classes and subclasses).
  • Protected mode : Anything marked as protected is accessible only in the same package(in all classes and subclasses) and also accessible in those sub-classes of the class(marked as protected) which lie in other packages.
  • Private mode : Something marked as private is accessible only in the given class. 
  • Default mode : When no mode is specified, then the default mode is used. It visibility is only inside the same package

> Return type : Every method returns some sort of value, and the type of value it returns is the return type of the method. The return type may be an int, float, double or other primitives or even objects or collections also. If it returns nothing, then the return type is void.

> Method name : Each method has a unique name to recognise it. This method name can be any valid identifier. Method names should be descriptive, according to the general conventions. This means the method name should depict what the method is going to do. 
Example: If a method finds the factorial of a number, then the method name should be fact() or factorial() or anything like this. 

Or if the method name contains more than 1 word, then write the name in Camel Casing convention. For example : areaOfTriangle(), comparingTwoWords() etc.

> Parameter List : It is the list of the parameters along with their name and data type, that the method would accept. It should be in closes parenthesis. It can also be left empty if no parameters are accepted by the method.

> Method body : It should be enclosed by curly brackets({}). All the statements of the method should go in these parenthesis. These statements are main code that will be executed when method would be called.

> Return statement : There should also be a return statement at the end of the method inside the braces, which should return a value of the same type as of above mentioned data-type

Syntax : 
access-modifier return-type methodName (parameter-list){
/* method body */
}

Example : 
public int findMaxNumber(int a, int b){
    int max = a>b?a:b;
    return max;
    }

* This method has public access mode and integer as the return type, and accepts 2 integer type parameters. And return the integer type variable sum.

If you want to use keywords like static, final etc(non-access Java modifiers) with methods, you can apply them after the access modifier and before the return type. 
Example: public static void main(){ //method body }

** You can also create different methods having same name in a class, but all these should have varying number of parameters and varying return types, this is known as Method Overloading.
Example: 
void add();
int add(int a, int b);
int add(float a, int b);

Calling a method in Java

Before calling a user-defined method in Java, it must be defined. In order to call or invoke a method, just write its name with a pair of round brackets and then a semicolon in the main method of your program. You can also pass the arguments in the round brackets, each argument separated by commas.

Examples:

add(4,3);
findMaxNumber(23.3,43,1331,0);
showOutput();

In order to call an overloaded Java method, just write the method name and then in the parameter list, write the required parameters, the compiler will automatically select the desired method, having similar parameters. 

Whenever a method is called, the control is shifted from the calling statement to the part where the method was declared and all the statements inside the method block are executed one by one.

public class methodOverloadingExample{
    public static void main(String args[]){
        myClass ob1 = new myClass();
        ob1.sum();
        System.out.println("Sum of 3 and 4 is "+ ob1.sum(3,4));
        System.out.println("Sum of 1.223 and 2.132 is "+ ob1.sum(1.2f,2.132f));

    }
}
class myClass{
    void sum(){
        System.out.println("Enter the parameters!");
    }
    public int sum(int a, int b){
        return a+b;
    }
    public float sum(float a,float b){
        return a+b;
    }
}

OUTPUT

Enter the parameters!
Sum of 3 and 4 is 7
Sum of 1.223 and 2.132 is 3.355


Sample Programs

Program 1: Finding factorial of the number 'n' (taking a number as input from the user)?
Solution : 
import java.util.Scanner;
public class factorial{
    static public int findFactorial(int n){
        int fact=1;
        for(int i=n;i>=1;i--){
            fact=fact*i;
        }
        return fact;
    }
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        System.out.println("Factorial of "+n+" is "+factorial.findFactorial(n));
    }
}


OUTPUT
5
Factorial of 5 is 120

Scanner class in Java is used to take inputs. Before using Scanner class you have to import java.util.Scanner class in your program. And then in the main method, create an object of scanner class. 
In this case, our Scanner class object in input. And we have to enter a integer value, so we are using nextInt() method. It takes only integer inputs. 

If we had to input float. then the statement would have been -
input.nextFloat();

Program 2: Find the hypotenuse of the given triangle?
Solution:
import java.util.Scanner;
class Hypotenuse 
{
public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        double side1, side2, hypo;                 
        System.out.print("Enter a value for Side 1: ");
        side1 = input.nextDouble();     
        System.out.print("Enter a value for Side 2: ");
        side2 = input.nextDouble();      
        hypo =findHypotenuse(side1,side2); 
        System.out.println("The length of the hypotenuse is: " + hypo);
    }
static double findHypotenuse(double s1,double s2)
{
    return Math.sqrt(Math.pow(s1, 2) + Math.pow(s2, 2));
}

OUTPUT
Enter a value for Side 1: 4.1111
Enter a value for Side 2: 21.3333
The length of the hypotenuse is: 25.4444

Here also we have used Scanner class for taking inputs. Here the value of a side of triangle can be any decimal value also. So we taken a double type input. And for this, we have used nextDouble() method for taking double input.

Math.sqrt() is an in-built method is used to find the square root of the expression placed in the brackets

Math.pow() is also an inbuilt method of Math class for finding the power of a number. It has the following format
Syntax: Math.pow(a,b); 
It will give return us a double value, a raise to power b.
Example: Math.pow(2,3);
It will give 8.0

FAQs

Ques 1. What are packages in Java?
Ans. Packages are group of classes, sub-packages and interfaces. It is like a folder containing the source codes of all the programs. These are of 2 types : Built-in packages and User-defined packages. For more information, go to https://www.javatpoint.com/package

Ques 2. What is a subclass in Java?
Ans. A class which is derived from another class is known as subclass. It is also known as extended class, child class or derived class. And the class from which the subclass is derived is known as superclass.

Ques. 3 What are primitive data types in Java?
Ans.  Data types like int, float, char, double, long etc that are already defined in Java.

Ques 4. What is method overloading in Java?
Ans. In Java, if 2 methods have same name and they differ in number of parameters or the return type. Then they are called overloaded Java methods and this feature is called method overloading in Java.

Ques 5. Define Scanner class in Java?
Ans. The Scanner class is used to get input from the user in the program and it belongs to java.util package. For more information, go to https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Ritish

Just a novice blogger

Post a Comment (0)
Previous Post Next Post