You are currently viewing Java Methods with Example

Java Methods with Example

In general, a method is a manner of accomplishing a goal. In Java, a method is a collection of instructions that accomplishes a specified goal. It ensures that code can be reused. Methods can also be used to easily alter code. We’ll study what a method is in Java, the different sorts of methods, how to declare a method, and how to invoke a method in Java in this part.

what is a method?

A method is a collection of statements or a series of statements organised together to conduct a specific task or action. It’s a technique for making code more reusable. We create a method once and then use it repeatedly. We don’t have to write code over and over again. It also allows for easy code modification and readability by simply adding or removing code chunks. Only when we call or invoke the method is it executed.

methods in java,methods in java,methods in java,methods in java,methods in java,methods in java, methods in java,methods in java,methods in java,methods in java,methods in java,methods in java , methods in java,methods in java,methods in java,methods in java,methods in java,methods in java , methods in java,methods in java,methods in

Declaration of the Method

Method properties such as visibility, return-type, name, and parameters are all stated in the method declaration.

Syntax

public static int Sample(int x, int y) {
// body
}


Here,

  • public static − modifier
  • int − return type
  • Sample − name of the method
  • x, y − formal parameters
  • int x, int y − list of parameters

The syntax presented above contains the following:

  • It is unnecessary to use the modification because it defines the method’s access type.
  • returnType is a kind of method that can return a value.
  • The name of the method is nameOfMethod. The method name and parameter list make up the method signature.
  • The type, order, and number of parameters in a method are all listed in the parameter list. These are optional; the method could have no parameters.
  • The method body specifies how the method interacts with the statements.

Access Specifier

The method’s access specifier, also known as a modifier, determines the method’s access type. It specifies the method’s visibility.

There are four different types of access specifiers in Java: 

  • Public: When we utilise the public specifier in our application, all classes can access the method.
  • Private: The method is only accessible in the classes in which it is declared when we use a private access specifier.
  • Protected: The method is accessible within the same package or subclasses in a different package when we use the protected access specifier.
  • Default: When no access specifier is specified in the method declaration, Java uses the default access specifier. It can only be seen from the same package.

Return Type: The return type of a method is the data type it returns. It could be a primitive data type, an object, a collection, or void, for example. The void keyword is used when a method does not return anything.

Method Name: The name of a method is defined by its method name, which is a unique name. It must be appropriate for the method’s functionality. If we’re making a method for subtracting two numbers, the name of the method must be subtraction (). The name of a method is used to call it.

Parameter List: The parameter list is a collection of parameters separated by a comma and wrapped in parentheses. It specifies the data type as well as the name of the variable. Leave the parenthesis blank if the method has no parameters.

Method Body: The method declaration includes a section called the method body. It contains all of the actions that must be completed. It is protected by a pair of curly braces.

In Java, calling a method

To use the method, we must first call it.

The addNumbers() method can be called in the following way.

//calls the methods
sample();

Example 1: Java Methods

class Main {

  // create a method
  public int Sample(int a, int b) {
    int sum = a + b;
    // return;
    return sum;
  }

  public static void main(String[] args) {
    
    int x = 5;
    int y = 5;

    // create an object of Main
    Main object = new Main();
    // calling method
    int total = object.Sample(x, y);
    System.out.println("Sum is: " + total);
  }
}

Output:

Sum is: 10

In the preceding example, we created a Sample() method. The x and y parameters are used in the method. 
int total = object.Sample(x, y);

The method was invoked by giving two arguments, x and y. We’ve placed the value in the total variable because the method returns a value.

Return Type of a Java Method

The function call may or may not get a value from a Java method. The return statement is used to return any value. As an example:

int Sample() {
//…
return total;
}

class Main {

// create a method
  public static int Sample(int x) {

    // return statement
    return x * x;
  }

  public static void main(String[] args) {
    int total;

   
    total = Sample(5);

    System.out.println("Sample value of 10 is: " + total);
  }
}

Output:

Sample value of 5 is: 25

Choosing a Method Name

When naming a method, keep in mind that it must be a verb and begin with a lowercase letter. If there are more than two words in the method name, the first must be a verb, followed by an adjective or noun. Except for the first word, the initial letter of each word in the multi-word method name must be in uppercase.

  • add() are single-word methods ()
  • sampleDemo() are multi-word methods ()

It’s also conceivable for a method to have the same name as another method in the same class, this is referred to as method overloading.

Types of Method

In Java, there are two types of methods:

  • Predefined Method
  • User-defined Method

Predefined Method

Predefined methods in Java are methods that are previously defined in the Java class libraries. It’s also known as the built-in method or the standard library approach. We can use these methods directly by calling them at any time in the application. printf(), Scanf(),  equals(), compareTo,  and other pre-defined methods are examples. When we call any of the predefined methods in our software, a set of codes relevant to that method run in the background, which are already saved in the library.

Let’s have a look at a predefined method:

public class Demo   
{  
public static void main(String[] args)   
{  
// using the Math class min() method
System.out.print("The maximum number is: " + Math.min(1,7));  
}  
}  

Output:

The manimum number is: 1

We utilised three predefined methods in the preceding example: main(), print(), and min(). Because these methods are predefined, we have utilised them without declaring them. The PrintStream class has a print() function that prints the result to the console. The smaller of two numbers is returned by the min() function of the Math class.

User-defined Method

A user-defined method is a method that is written by the user or programmer. These strategies are tweaked to meet the needs of the situation.

Let’s build a user-defined mechanism for determining whether an integer is even or odd. We’ll start by defining the method.

//user defined method  
public static void sample(int x)  
{  
//method body  
if(x%2==0){
System.out.println(x+" is even");  
} 
else   {
System.out.println(x+" is odd");  
}
}  

The above method, entitled sample(), has been defined. It has an int-type parameter called x. We used void because the method does not return any value. The procedures to determine whether a number is even or odd are contained in the method body. If the number is even, it will be printed as even,otherwise, it will be printed as odd.

Method Overloading

Method overloading occurs when a class contains two or more methods with the same name but distinct parameters. It’s not the same as overriding. When a method is overridden, it has the same name, type, number of parameters, and so on.


You might like:

Java Object and Java Class with Example

We hope that this article will assist you in understanding all about Java Methods with Example. We have concentrated on making a basic, meaningful, and easy-to-learn guide to the concepts. Still, if you have any problems regarding this, please post them in the comment section, we will be glad to assist you.

This Post Has One Comment

Leave a Reply