java

Java Methods


What is Methods?

Methods are blocks of code that perform a specific task  and are defined within classes.

Syntax

access_modifier return_type method_name(parameter_list) {

	// code to perform the task
    // return statement if the method has a return type
}

Note :- method executes only when it is called or invoked by another part of the program. 

 

Why we use methods?

Modularity: Breaking down code into manageable units.
Reusability: Using the same code in different parts of a program.
Encapsulation: Bundling code and data into a single unit.
Parameterization: Accepting different data sets as input.
Return Values: Communicating results back to the calling code.
Code Organization: Structuring code logically for readability.
Maintainability: Facilitating efficient updates and changes.
Testing and Debugging: Simplifying testing and debugging efforts.

 

Example

public class MethodsProgram {

    // Method to add two numbers and return the result
    public static int add(int num1, int num2) {
        return num1 + num2;
    }

    // Method to greet a person
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    // Main method where the program starts execution
    public static void main(String[] args) {
    
        // Calling the add method and storing the result
        int sum = add(5, 3);

        // Printing the result of the addition
        System.out.println("Sum: " + sum);

        // Calling the greet method
        greet("Welcome");
    }
}

 

 

Methods Types

Pre-defined Methods:- Predefined methods, also known as built-in or standard library methods, are methods that come with the Java programming language and are part of the Java Standard Library (Java API).

Example

import java.util.*;

public class PredefinedMethodsExample {

	public static void main(String[] args) {
        // Mathematics
        double sqrtResult = Math.sqrt(25.0);    // Here, sqrt() is a predefined method
        System.out.println("Square Root: " + sqrtResult);

        // String Manipulation
        String message = "Hello, Java!";
        int length = message.length();   // Here, length() is a predefined method
        System.out.println("String Length: " + length);
 
        // Input/Output
        System.out.print("Enter a number: ");
        Scanner scanner = new Scanner(System.in);
        int number = scanner.nextInt();    // Here, nextInt() is a predefined method
        System.out.println("Result: " + number);

      
	// Arrays
        int[] intArray = {3, 1, 4, 1, 5, 9};
        
        Arrays.sort(intArray);    //  Here, sort() is a predefined method
        System.out.println("Sorted Array: " + Arrays.toString(intArray));
         
        int searchResult = Arrays.binarySearch(intArray, 4);  // Here, binarySearch() is a predefined method


		System.out.println("Binary Search Result: " + searchResult);

        // Date and Time
        Date currentDate = new Date();   // Here, Date() is a predefined method
        System.out.println("Current Date: " + currentDate);
    }
}

 

User-defined Methods:- User-defined methods in Java are methods that are created by the programmer (user) to perform a specific task or set of tasks within a Java program.

 

There are five ways in which you can write user defined methods in Java and use them in your work.

1. Instance Methods:

Associated with an instance of a class.
Invoked using an object of the class.
Non-static methods are instance methods by default.

Example

public class InstanceMethod {

    public void addNumbers(int num1, int num2) {
        int sum = num1 + num2;
        System.out.println("Instance Method Sum: " + sum);
    }

    public static void main(String[] args) {
        InstanceMethod obj = new InstanceMethod();
        obj.addNumbers(5, 3);
    }
}

 

2. Static Methods:

Belong to the class rather than instances of the class.
Can be called using the class name without creating an object.
Cannot directly access instance variables or non-static methods.

Example

public class StaticMethod {

    public static void addNumbers(int num1, int num2) {
        int sum = num1 + num2;
        System.out.println("Static Method Sum: " + sum);
    }

    public static void main(String[] args) {
        StaticMethod.addNumbers(7, 2);
    }
}

 

3. Getter and Setter Methods:

Used to get (retrieve) and set (modify) the values of private instance variables.
Encapsulates access to class fields.

Example

public class GetterSetterAddition {

    int result;
    
    public int getResult() {
        return result;
    }

    public void setResult(int result) {
        this.result = result;  // sending output by using this keyowrd to getResult()
    }

    public static void main(String[] args) {
        GetterSetterAddition obj = new GetterSetterAddition();
        int num1 = 10, num2 = 8;
        obj.setResult(num1 + num2);
        System.out.println("Using Getter and Setter Methods: " + obj.getResult());
    }
}

 

4. Constructor Methods:

Special methods used to initialize objects when they are created.
Have the same name as the class.
Executed automatically when an object is instantiated.

Example

public class ConstructorAddition {

    int result;

    public ConstructorAddition(int num1, int num2) {
       result = num1 + num2;
       System.out.println("Constructor Method Sum: " + result);
    }

    public static void main(String[] args) {
        ConstructorAddition obj = new ConstructorAddition(3, 4);
     
    }
}

 

5. Overloaded Methods:

Multiple methods in the same class with the same name but different parameter lists (number or types of parameters).
Enables a class to perform similar tasks with different inputs.

Example

public class OverloadedAddition {

    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        OverloadedAddition obj = new OverloadedAddition();
        int resultInt = obj.add(3, 4);
        double resultDouble = obj.add(2.5, 3.5);

        System.out.println("Overloaded Method (int): " + resultInt);
        System.out.println("Overloaded Method (double): " + resultDouble);
    }
}