Methods in Java with examples

With the help of examples, we will learn about Java methods, define them, and utilize them in Java programs in this article. A method is a piece of code that accomplishes a specific goal. Generally, a method is a collection of statements or statements organized together to conduct a particular 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 easy code modification and readability by simply adding or removing code chunks. Only when we call or invoke the method is it executed. The main() method is the most significant method in Java.

Assume you need to make a program to draw a circle and color it. To overcome this difficulty, you can devise two approaches:

  • a method for drawing a circle
  • a method for coloring the circle

Values or arguments can be inserted inside methods, and they will only be executed when the method is called. Functions are another name for them. The following are the most common usage of methods in Java:

  • It allows for code reuse (define once and use multiple times)
  • An extensive program can be broken down into smaller code parts.
  • It improves the readability of code.

Methods in Java

By breaking down a complex problem into smaller bits, you can create an easier to comprehend and reuse program. There are two sorts of methods in Java: static and dynamic.

User-defined Methods: We can develop our method based on our needs.

Standard Library Methods: These are Java’s built-in methods that can be used.

Declaration of the Method

Method properties such as visibility, return type, name, and parameters are all stated in the method declaration. As seen in the following diagram, it consists of six components known as method headers.

(Access Specifier)  (Return Type) (Method Name) (Parameter List) --> Method Header

{
 // Method Body
}

For example:

public int sumValues(int x, int y){
// method body
}

Where sumValues(int x, int y) is the Method signature

Method Signature: A method signature is a string that identifies a method. It’s included in the method declaration. It contains the method name as well as a list of parameters.

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 utilize the public specifier in our application, all classes can access the method.
  • Private: The method is only accessible in the classes declared when using a private access specifier.
  • Protected: The method is accessible within the same package or subclasses in a different package when using 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. For example, it could be a primitive data type, an object, a collection, or avoid. 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 method’s name 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. Further, it is protected by a pair of curly braces.

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. Consider the following scenario:

  • sum(), area() are two single-word methods
  • areaOfCircle(), stringComparision() are two multi-word methods

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

User-defined methods

Let’s start by looking at user-defined methods. To declare a method, use the following syntax:

returnType methodName() {
  // method body
}

As an example,

int sumValues() {
// code
}

The method above is named sumValues(), whose return type is an int. The syntax for declaring a method is as follows. The complete syntax for declaring a method, on the other hand, is

modifier static returnType nameOfMethod (parameter1, parameter2, ...) {
  // method body
}

Here,

modifier – It specifies the method’s access kinds, such as public, private, etc. Visit Java Access Specifier for further information.

static -It can be accessed without creating objects if we use the static keyword.

The sqrt() method in the standard Math class, for example, is static. As a result, we may call Math.sqrt() without first establishing a Math class instance. The values parameter1/parameter2 are supplied to a method. A method can take any number of arguments.

Method call in Java

We’ve declared a method called sumValues() in the previous example. To use the method, we must first call it. The sumValues() method can be called in the following way.

// calls the method
sumValues();

Example: Using Methods in Java

class Codeunderscored {

  // create a method
  public int sumValues(int num_1, int num_2) {
    int sumVal = num_1 + num_2;
    // return the results
    return sumVal;
  }

  public static void main(String[] args) {
    
    int num1 = 67;
    int num2 = 33;

    // create an object of  Codeunderscored
    Codeunderscored code = new Codeunderscored();

    // calling method
    int resultVal = code.sumValues (num1, num2);
    System.out.println("The resultant sum  value is: " + resultVal);
  }
}

We defined a method called sumValues() in the previous example. The num_1 and num_2 parameters are used in the method. Take note of the line,

int resultVal = code.sumValues (num1, num2);

The procedure was invoked by giving two arguments, num_1 and num_2. We’ve placed the value in the result variable because the method returns a value. It’s worth noting that the method isn’t static. As a result, we’re utilizing the class’s object to invoke the method.

The keyword void

We can use the void keyword to create methods that don’t return a value. In the following example, we’ll look at a void method called demoVoid. It is a void method, which means it returns nothing. A statement must be used to call a void method, such as demoVoid(98);. As illustrated in the following example, it is a Java statement that concludes with a semicolon.

public class Codeunderscored {

   public static void main(String[] args) {
      demoVoid(98);
   }

   public static void demoVoid(double points) {
      if (points >= 100) {
         System.out.println("Grade:A");
      }else if (points >= 80) {
         System.out.println("Grade:B");
      }else {
         System.out.println("Grade:C");
      }
   }
}

Using Values to Pass Parameters

Arguments must be passed while working on the calling procedure. These should be listed in the method specification in the same order as their corresponding parameters. Generally, parameters can be given in two ways: a value or a reference.

Calling a method with a parameter is known as passing parameters by value. The argument value is provided to the parameter this way. The program below demonstrates how to pass a parameter by value. Even after using the procedure, the arguments’ values stay unchanged.

public class Codeunderscored {

   public static void main(String[] args) {
      int x = 20;
      int y = 62;
      System.out.println("Items initial order, x = " + x + " and y = " + y);

      // Invoking the swap method
      swapValues(x, y);
      System.out.println("\n**Order if items, before and after swapping values **:");
      System.out.println("Items after swapping, x = " + x + " and y is " + y);
   }

   public static void swapValues(int a, int b) {
      System.out.println("Items prior to swapping(Inside), x = " + x + " y = " + y);
      
      // Swap n1 with n2
      int temp = x;
      x = y;
      y = temp;
      System.out.println("Items post swapping(Inside), x = " + x + " y = " + y);
   }
}

Overloading of Methods

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, etc.

Consider the example of finding the smallest integer numbers. Let’s say we’re looking for the smallest number of double types. Then, to build two or more methods with the same name but different parameters, the notion of overloading will be introduced.

The following example clarifies the situation:

public class Codeunderscored {

   public static void main(String[] args) {
      int x = 23;
      int y = 38;
      double numOne = 17.3;
      double numTwo = 29.4;

      int resultOne = smallestValue(x, y);
      
      // invoking function name with different parameters
      double resultTwo = smallestValue(numOne, numTwo);

      System.out.println("The Minimum number is: = " + resultOne);
      System.out.println("The Minimum number is: = " + resultTwo);
   }

   // for integer
   public static int smallestValue(int numOne, int  numTwo) {
      int smallestVal;
      if ( numOne > numTwo)
         smallestVal = numTwo;
      else
         smallestVal = numOne;

      return smallestVal;
   }
   
   // for double
   public static double smallestValue(double numOne, double numTwo) {
     double smallestVal;
      if ( numOne > numTwo)
         smallestVal = numTwo;
      else
         smallestVal = numOne;

      return smallestVal;
   }
}

Overloading methods improve the readability of a program. Two methods with the same name but different parameters are presented here. The result is the lowest number from the integer and double kinds.

Using Arguments on the Command Line

When you execute a program, you may want to feed some information into it. It is performed by invoking main() with command-line arguments.

When a program is run, a command-line argument is information that appears after the program’s name on the command line. It’s simple to retrieve command-line parameters from within a Java program. They’re saved in the String array supplied to main() as strings. The following program displays all of the command-line arguments that it is invoked.

public class Codeunderscored {

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

‘This’ keyword

A Java keyword is used to reference the current class’s object in an instance method or constructor. You can use this to refer to class members like constructors, variables, and methods. It’s worth noting that the keyword this is only used within instance methods and constructors.

In general, the term this refers to:

  • Within a constructor or a method, distinguish instance variables from local variables if their names are the same.
class Employee {
   int age;   
   Employee(int age) {
      this.age = age;	
   }
}
  • In a class, call one sort of constructor (parametrized constructor or default constructor) from another. Explicit constructor invocation is what it’s called.
class Employee {
   int age
   Employee() {
      this(20);
   }
   
   Employee(int age) {
      this.age = age;	
   }
}

This keyword is used to access the class members in the following example. Copy and paste the program below into a file called thisKeyword.java.

public class Codeunderscored {
   // Instance variable num
   int num = 10;
	
   Codeunderscored() {
      System.out.println("This is a program that uses the keyword this as an example. ");	
   }

   Codeunderscored(int num) {
      // Using the default constructor as a starting point
      this();
      
      // num is assigned to the instance variable num by assigning the local variable num to the instance variable num.
      this.num = num;	   
   }
   
   public void greet() {
      System.out.println("Hello and welcome to Codeunderscored.com. ");
   }
      
   public void print() {
      // declaration of the num Local variable
      int num = 20;
      
      // The local variable is printed.
      System.out.println("num is the value of a local variable. : "+num);
      
      // The instance variable is printed.
      System.out.println("num is the value of the instance variable.  : "+this.num);
      
      // Invoking a class's greet method
      this.greet();     
   }
   
   public static void main(String[] args) {
      // Creating an instance of the class
      Codeunderscored code = new Codeunderscored();
      
      // The print technique is used to print a document.
      code.print();
	  
      // Through a parameterized constructor, a new value is passed to the num variable.
      Codeunderscored codeU = new Codeunderscored(30);
      
      // Using the print technique once more
      codeU.print();
   }
}

Arguments with Variables (var-args)

You can give a variable number of parameters of the same type to a method in JDK 1.5. The method’s parameter is declared as follows:

typeName... parameterName

You specify the type followed by an ellipsis in the method definition (…). In a method, just one variable-length parameter can be supplied, and it must be the last parameter. Any regular parameters must precede it.

public class VarargsCode {

   public static void main(String args[]) {
      // Calling of a method with variable args  
      
      showMax(54, 23, 23, 22, 76.5);
      showMax(new double[]{21, 22, 23});
   }

   public static void showMax( double... numbers) {
      if (numbers.length == 0) {
         System.out.println("No argument passed");
         return;
      }

      double result = numbers[0];

      for (int i = 1; i <  numbers.length; i++)
      if (numbers[i] >  result)
      result = numbers[i];
      System.out.println("The max value is " + result);
   }
}

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 sumValues() {
...
return sumVal;
}

The variable sumVal is returned in this case. Because the function’s return type is int, the type of the sumVal variable should be int. Otherwise, an error will be generated.

// Example : Return Type of a Method

class Codeunderscored {

// creation of a static method
  public static int squareValues(int numVal) {

    // return statement
    return numVal * numVal;
  }

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

    // call the method
    // store returned value to result
    resultVal = squareValues(13);

    System.out.println("The Squared value of 13 is: " + resultVal);
  }

}

In the preceding program, we constructed a squareValues() method. The method accepts an integer as an input and returns the number’s square. The method’s return type has been specified as int here.

As a result, the method should always return a positive number. Note that we use the void keyword as the method’s return type if the method returns no value.

As an example,

public void squareValues(int i) {
  int resultVal = i * i;
  System.out.println("The Square of the given number is: " + resultVal);
}

Java method parameters

A method parameter is a value that the method accepts. A method, as previously stated, can have any number of parameters. As an example,

// method with two parameters
int sumValues(int x, int y) {
  // code
}

// method with no parameter
int sumValues(){
  // code
}

When calling a parameter method, we must provide the values for those parameters. As an example,

// call to a method with two parameters
sumValues(29, 21);

// call to a method with no parameters
sumValues()

Example : Method Parameters

class Codeunderscored {

  // method with no parameter
  public void methodWithNoParameters() {
    System.out.println("Method without parameter");
  }

  // method with single parameter
  public void methodWithParameters(int a) {
    System.out.println("Method with a single parameter: " + a);
  }

  public static void main(String[] args) {
    
    // create an object of  Codeunderscored
    Codeunderscored code = new Codeunderscored();

    // call to a  method with no parameter
    code.methodWithNoParameters ();
    
    // call to a method with the single parameter
    code.methodWithParameters (21);
  }
}

The method’s parameter is int in this case. As a result, the compiler will throw an error if we pass any other data type than int. Because Java is a tightly typed language, this is the case. The actual parameter is the 32nd argument supplied to the methodWithParameters() method during the method call.

A formal argument is the parameter num that the method specification accepts. The kind of formal arguments must be specified. Furthermore, the types of actual and formal arguments should always be the same.

Static Method

A static method has the static keyword. In other terms, a static method is a method that belongs to a class rather than an instance of that class. We can also construct a static method by prefixing the method name with the term static.

The fundamental benefit of a static method is that it can be called without requiring the creation of an object. It can change the value of static data members and access them. It is employed in the creation of an instance method. The class name is used to call it. The main() function is the best example of a static method.

public class Codeunderscored  
{  
public static void main(String[] args)   
{  
displayStatically();  
}  
static void displayStatically()   
{  
System.out.println("Codeunderscored example of static method.");  
}  
}  

Instance Method in Java

A class method is referred to as an instance method. It is a class-defined non-static method. It is essential to construct an object of the class before calling or invoking the instance method. Let’s look at an instance method in action.

public class CodeunderscoredInstanceMethod
{  
public static void main(String [] args)  
{  
//Creating an object of the class  
CodeunderscoredInstanceMethod code = new CodeunderscoredInstanceMethod();  
//invoking instance method   
System.out.println("The  numbers' sum is: "+code .sumValues(39, 51));  
}  
int s;  
//user-defined method because we have not used static keyword  
public int sumValues(int x, int y)  
{  
resultVal = x+y;  
//returning the sum  
return resultVal;  
}  
}  

Instance methods are divided into two categories:

  • Mutator Method
  • Accessor Method

Accessor Method

The accessor method is the method(s) that reads the instance variable(s). Because the method is prefixed with the term obtain, we can recognize it. Getters is another name for it. It returns the private field’s value. It’s used to get the private field’s value.

public int getAge()    
{    
return age;    
}   

Mutator Method

The method(s) read and modify the instance variable(s) values. Because the method preceded the term set, we can recognize it. Setters or modifiers are other names for it. Even though it doesn’t give you anything, it accepts a field-dependent parameter of the same data type. It’s used to set the private field’s value.

public void setAge(int age)   
{  
this.age = age;  
}  

Example: Instance methods – Accessor & Mutator

public class Employee   
{  
private int empID;  
private String name;  
public int getEmpID()    //accessor method  
{  
return empID;  
}  
public void setEmpID(int empID) //mutator method  
{  
this.empID = empID;  
}  
public String getName()   
{  
return name;  
}  
public void setName(String name)   
{  
this.name = name;  
}  
public void display()  
{  
System.out.println(" Your Employee NO is.: "+empID);  
System.out.println("Employee name: "+name);  
}  
}  

Methods for a Standard Library

The standard library methods are Java built-in methods that can be used immediately. These standard libraries are included in a Java archive (*.jar) file with JVM and JRE and the Java Class Library (JCL).

Examples include,

  • print() is a java.io method.
  • In PrintSteam, the print(“…”) method displays a string enclosed in quotation marks.
  • sqrt() is a Math class method. It returns a number’s square root.

Here’s an example that works:

// Example: Method from the Java Standard Library

public class Codeunderscored {

  public static void main(String[] args) {
    
    // the sqrt() method in action
    System.out.print("The Square root of 9 is: " + Math.sqrt(9));
  }
}

Abstract Method

An abstract method does not have a method body. In other terms, an abstract method does not have an implementation. It declares itself in the abstract class at all times. If a class has an abstract method, it must be abstract itself. The keyword abstract is used to define an abstract procedure.

The syntax is as follows:

abstract void method_name();  
abstract class CodeTest //abstract class  
{  
//abstract method declaration  
abstract void display();  
}  
public class MyCode extends CodeTest  
{  
//method impelmentation  
void display()  
{  
System.out.println("Abstract method?");  
}  
public static void main(String args[])  
{  
//creating object of abstract class  
CodeTest code = new MyCode();  

//invoking abstract method  
code.display();  
}  
}  

Factory method

It’s a method that returns an object to the class where it was created. Factory methods are all static methods. A case sample is as follows:

NumberFormat obj = NumberFormat.getNumberInstance().

The finalize( ) Method

It is possible to define a method that will be called immediately before the garbage collector destroys an object. This function is called finalize(), ensuring that an object is terminated correctly. Finalize(), for example, can be used to ensure that an open file held by that object is closed.

Simply define the finalize() method to add a finalizer to a class. When the Java runtime recycles an object of that class, it calls that method. In the finalize () method, you’ll specify the actions that must be completed before an object is destroyed in the finalize() method.

This is the general form of the finalize() method:

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

The keyword protected is a specifier that prevents code declared outside the class from accessing finalize(). It implies you have no way of knowing when or if finalize() will be called. For example, if your application stops before garbage collection, finalize() will not be called.

What are the benefits of employing methods?

The most significant benefit is that the code may be reused. A method can be written once and then used several times. We don’t have to recreate the code from scratch every time. Think of it this way: “write once, reuse many times.”

Example 5: Java Method for Code Reusability

public class Codeunderscored {

  // definition of the method
  private static int calculateSquare(int x){
    return x * x;
  }

  public static void main(String[] args) {
    for (int i = 5; i <= 10; i++) {

      //calling the method
      int resultVal = calculateSquare(i);
      System.out.println("The Square of " + i + " is: " + resultVal);
    }
  }
}

We developed the calculateSquare() method in the previous program to calculate the square of a number. The approach is used to find the square of numbers between five and 10 in this case. As a result, the same procedure is employed repeatedly.

  • Methods make the code more readable and debuggable.

The code to compute the square in a block is kept in the calculateSquare() method. As a result, it’s easier to read.

Example: Calling a Method several times

public class Codeunderscored {
  static void showCode() {
    System.out.println("I am excited about CodeUnderscored!");
  }

  public static void main(String[] args) {
    showCode();
    showCode();
    showCode();
    showCode();
  }
}

//  I am excited about CodeUnderscored!
//  I am excited about CodeUnderscored!
//  I am excited about CodeUnderscored!
//  I am excited about CodeUnderscored!

Example: User-Defined Method

import java.util.Scanner;  
public class Codeunderscored  
{  
public static void main (String args[])  
{  
//creating Scanner class object     
Scanner scan=new Scanner(System.in);  
System.out.print("Enter the number: ");  
//reading value from user  
int num=scan.nextInt();  
//method calling  
findEvenOdd(num);  
}  
//user defined method  
public static void findEvenOdd(int num)  
{  
//method body  
if(num%2==0)   
System.out.println(num+" is even");   
else   
System.out.println(num+" is odd");  
}  
}  

Conclusion

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. In addition, Methods can also be used to alter code quickly.

A method is a section of code that only executes when invoked. It has Parameters which are data that can be passed into a method. Methods, often known as functions, carry out specific tasks. Further, some of the benefits of using methods include code reuse, creating it once, and using it multiple times.

Within a class, a method must be declared. It is defined by the method’s name, preceded by parenthesis(). Although Java has several pre-defined ways, such as System.out.println(), you can also write your own to handle specific tasks.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *