×

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases.

The method consists of the block of code to perform a task. The methods are used for the Reusability feature i.e., We can be able to call the methods for number of times according to our problem instead of writing the same code for a greater number of times.

The main() method in Java is the most important method as the execution of a Java program start with the main method.

Declaration of Methods in Java

The Method declaration or the Method Signature has the following components

  • Return data type
  • Name of Method
  • Parameters

We can also include the access modifiers, if not mentioned it takes the “Default access modifier/ specifier”.

Syntax:

Access_modifer return_datatype  Method_Name(Parameters)

Example:

public int Matrix (int a , int b)

Calling a Method in Java

The method is executed only when the method is called. The basic way of calling method is, writing the method name then parenthesis i.e. ().

Example:

import java.io.*;
class MethodDemo
{
static void Method()
{
System.out.println(“Method Invoked”);
}
public static void main (String args[])
{
Method();
}
}   

Output:

Method Invoked

The method which doesn’t return any value is declared by the void data type.

Passing parameters in Methods

In the process of Calling a method, we can give the parameters inside the parenthesis ().

//Example program for the Parameterized Method
import java.io.*;
class MethodDemo
{
static void method(int a)
{
System.out.println(“The Number is”+a);
} 
public static void main(String args[])
{
method(10);
}
} 

Output:

The Number is 10

Types of Methods

There are two types of Methods they are,

  • Predefined Methods.
  • User- defined Methods.

Predefined Methods:

The predefined methods in Java are the methods which are prewritten in the Java libraries. It is also called as built-in Method. Examples of Predefined methods are length() , sqrt(), equals() etc.

Example:

class PreMethod
{
public static void main(String args[])
{
System.out.println(“Max Number is ”+Math.max(9,7));
}
}

Output:

Max Number is 9  

User-defined Methods

The user-defined methods are the methods which are written by the user/programmer.

Creation of User-defined method

Example Program for User defined method checking a person is eligible for vote or not.

Code:

class MDemo
{
public static void Elec(int x)
{
if(x>18)
{
System.out.println(“Eligible”);
}
else
{
System.out.println(“Not- Eligible”);
}
}  
// calling the method in main method
public static void main(String args[])
{
Elec(20); // calling method 
}
}  

Output:

Eligible

The above program consists of method Elec which is used to check the eligibility for casting the vote or not. The Elec method is being called in the Main method with parameters “x”.

Method Overloading

If the class consists of multiple methods with the same name, then it is called “Method Overloading”.

Example:

public class Ex
{
public static void main(String args[])
{
int A =10;
int B=12;
double d1 = 10.25;
double d2 = 18.50;
Max(A,B);
Max(d1,d2);
}
public static void Max(int x , int y)
{
if(x>y)
{
System.out.println(“Maximum Number : ”+x);
}
else
{
System.out.println(“Maximum Number : ”+y);
}
}
public static void Max(double i, double j)
{
if(i>j)
{
System.out.println(“Maximum Number : ”+i);
}
else
{
System.out.println(“Maximum Number : ”+j);
}
}


} 

Output:

Maximum Number: 12
Maximum Number: 18.50

In the example, we have created the two methods with the same name “Max” and the parameters of the two methods are different i.e., the first method parameters are given as integer datatype and second method parameters are given as double datatype. The program executes perfectly without any errors.

Abstract Methods

The abstraction is the process of hiding the unnecessary information or code to the user. To achieve the abstraction, we use the abstract methods.

For Example, if the user doesn’t want to see any information about the code and all the clumsy stuff in the code so we use the abstraction to show the relevant details to the user which are useful to them.

Creating the Abstract Methods

The Abstract methods are declared by using the “abstract” keyword before creating a method.

The Abstract class can consist of both Abstract method and Concreate methods. The Concrete methods are the just the regular methods.

The Abstract methods doesn’t create any new object, but they can be able to create the references.

The Abstraction is done by the concept of using the inheritance.

Example:

abstract class Dem
{
public abstract void connect();
public void check()
{
System.out.println(“Checking Connections”);
}
} 
class Be extends Dem
{
public void connect()
{
System.out.println(“Bluetooth Connected”);
}
}
class Mainn 
{
public static void main(String args[])
{
Be b = new Be();
b.check();
b.connect();
}
}

Output:

Checking Connections
Bluetooth Connected

Summary

The methods in Java are the collection of statements which are enclosed in the block i.e., {} are executed by the call of the method. There are two types of methods they are, Predefined methods and User defined methods. In the predefined methods the methods are already prewritten the Java libraries. The User defined methods are the methods which are written by the user or the Programmer. There is a special type of method that is abstract method, the abstract method is used to achieve the abstraction in the program.


Related Topics

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

How to find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Java Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find...

3 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.