Java methods


In Java, methods are blocks of code that perform specific tasks and can be called (or invoked) to execute. Methods allow for code reusability and modularity, enabling you to break down a program into smaller, manageable parts. Every method belongs to a class or object and can return a value or perform an action.

Key Components of a Java Method:

  1. Method Signature: The method’s name and parameter list together form the method signature. This is used to identify and differentiate methods.

  2. Return Type: Specifies what type of data the method will return. If the method does not return any value, it is declared with the void keyword.

  3. Method Name: The name of the method, which is used to call it. Method names should be descriptive and follow naming conventions (camelCase).

  4. Parameter List: A method can accept input parameters enclosed in parentheses. If there are no parameters, the parentheses remain empty.

  5. Method Body: The block of code inside the method that defines what the method does.

  6. Access Modifier: Methods can be public, private, protected, or have package-level access (default), determining their visibility to other classes.

General Syntax of a Method in Java

accessModifier returnType methodName(parameterList) { // method body }
  • accessModifier: Determines the visibility of the method (e.g., public, private, protected).
  • returnType: Specifies the data type of the value returned by the method, or void if nothing is returned.
  • methodName: The name used to call the method.
  • parameterList: Contains the parameters (inputs) for the method, if any. Parameters are specified by their data type followed by their name.

Example of a Simple Method

public class Example { // Method to calculate the sum of two numbers public int add(int a, int b) { return a + b; // returns the sum } public static void main(String[] args) { Example obj = new Example(); // Create an instance of the Example class int result = obj.add(5, 3); // Call the 'add' method System.out.println("Sum: " + result); // Output: Sum: 8 } }

Explanation:

  • The method add has two parameters int a and int b.
  • The return type of add is int, meaning it will return an integer value.
  • The method body contains the logic to add the two parameters and return the result.
  • In the main method, we create an instance of the Example class and call the add method to compute the sum of 5 and 3.

Types of Methods in Java

  1. Instance Methods:

    • Belong to an instance of a class.
    • To call an instance method, you need to create an object of the class.
    • Example:
      public class MyClass { public void sayHello() { System.out.println("Hello, World!"); } } public class Main { public static void main(String[] args) { MyClass obj = new MyClass(); obj.sayHello(); // Output: Hello, World! } }
  2. Static Methods:

    • Belong to the class, not to any specific instance.
    • Can be called without creating an object of the class.
    • Declared using the static keyword.
    • Example:
      public class MyClass { public static void sayHello() { System.out.println("Hello, World!"); } } public class Main { public static void main(String[] args) { MyClass.sayHello(); // Output: Hello, World! } }
  3. Parameterized Methods:

    • Accept parameters (inputs) that are used within the method.
    • Example:
      public class Calculator { public int multiply(int x, int y) { return x * y; } } public class Main { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.multiply(4, 5)); // Output: 20 } }
  4. Void Methods:

    • These methods do not return any value. The return type is void.
    • Example:
      public class MyClass { public void greet() { System.out.println("Hello, Java!"); } } public class Main { public static void main(String[] args) { MyClass obj = new MyClass(); obj.greet(); // Output: Hello, Java! } }

Method Overloading in Java

Method overloading allows you to define multiple methods with the same name but different parameter lists. Java determines which method to call based on the number and type of parameters.

Example of Method Overloading

public class Calculator { // Overloaded method: same name, different parameters public int add(int a, int b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } } public class Main { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(10, 20)); // Output: 30 System.out.println(calc.add(10, 20, 30)); // Output: 60 } }

In this example, the add method is overloaded, allowing it to accept either two or three integers.

Return Statement

The return statement in a method is used to exit the method and optionally return a value. If a method has a return type other than void, it must return a value of that type.

  • Example with return statement:
    public int square(int x) { return x * x; // Returns the square of the number }

Method Calling

  • Calling an Instance Method: You need to create an object of the class to call an instance method.

    ClassName object = new ClassName(); object.methodName();
  • Calling a Static Method: You can call a static method directly using the class name.

    ClassName.methodName();

Variable Scope in Methods

Variables declared inside a method are local variables, and they are only accessible within that method. Once the method execution completes, the variables go out of scope and are destroyed.

  • Example of Local Variable Scope:
    public class Example { public void displayNumber() { int number = 5; // Local variable System.out.println("Number: " + number); } public static void main(String[] args) { Example obj = new Example(); obj.displayNumber(); // Output: Number: 5 } }

Summary

  • A method in Java is a reusable block of code that performs a specific task.
  • Methods can return a value or perform an action (void methods).
  • Instance methods belong to an object of a class, while static methods belong to the class itself.
  • Method overloading allows you to create multiple methods with the same name but different parameter lists.
  • The return statement exits the method and optionally returns a value.
  • Methods can accept parameters and operate on them.