Software Development Exam  >  Software Development Notes  >  Basics of Java  >  Methods in Java

Methods in Java | Basics of Java - Software Development PDF Download

Methods are an essential concept in Java programming. They allow us to encapsulate a sequence of code statements into a single block, making our code more organized, reusable, and easier to understand. In this article, we will explore methods in Java, learn how to define and use them, and discuss different types of methods.

What is a Method?

A method in Java is a collection of statements that perform a specific task. It is similar to a function in mathematics and other programming languages. Methods are used to break down complex problems into smaller, manageable tasks, making our code modular and easier to maintain.

Method Signature and Syntax

Before diving into method examples, let's understand the syntax and components of a method in Java. Here is the general structure of a method:

accessModifier returnType methodName(parameterList) {

    // method body

    // code statements

    // return statement (if returnType is not void)

}

Let's break down each component:

  • Access Modifier: It determines the visibility and accessibility of the method. Common access modifiers are public, private, and protected.
  • Return Type: It specifies the type of value that the method returns. If the method doesn't return any value, we use the keyword void.
  • Method Name: It is the name used to call the method. It should be meaningful and follow the naming conventions in Java.
  • Parameter List: It includes the data types and names of the parameters (inputs) the method accepts. If the method doesn't require any parameters, we use empty parentheses ().
  • Method Body: It contains the sequence of statements that make up the method's functionality.
  • Return Statement: It is used to return a value from the method. This statement is only required if the return type is not void.

Now that we understand the components of a method, let's move on to some examples to see them in action.

Example 1: Simple Method

Let's start with a simple method that greets the user by printing a welcome message. The method does not accept any parameters and does not return any value (void return type).

public class HelloWorld {

    public static void main(String[] args) {

        greet(); // Call the greet() method

    }

    

    public static void greet() {

        System.out.println("Welcome to Java Programming!");

    }

}

Output

Welcome to Java Programming!

Explanation

  • In the example above, we define a method named greet() with the public access modifier and void return type.
  • Inside the greet() method, we use the System.out.println() statement to display the welcome message.
  • In the main() method, we call the greet() method using its name followed by parentheses ().

Example 2: Method with Parameters

Methods can also accept input parameters. Let's create a method that calculates the sum of two numbers and returns the result.

public class Calculator {

    public static void main(String[] args) {

        int result = add(5, 7); // Call the add() method with arguments 5 and 7

        System.out.println("Sum: " + result);

    }

    

    public static int add(int num1, int num2) {

        int sum = num1 + num2;

        return sum; // Return the sum

    }

}

Output

Sum: 12

Explanation

  • In this example, we define a method named add() with the public access modifier and int return type.
  • The add() method accepts two integer parameters: num1 and num2.
  • Inside the method, we calculate the sum of the two numbers and store it in the sum variable.
  • Finally, we use the return keyword to send the result (sum) back to the caller.

Example 3: Method Overloading

Java allows us to define multiple methods with the same name but different parameters. This is called method overloading. Let's see an example:

public class Rectangle {

    public static void main(String[] args) {

        int area1 = calculateArea(5); // Call the calculateArea() method with one argument

        int area2 = calculateArea(4, 7); // Call the calculateArea() method with two arguments

        System.out.println("Area 1: " + area1);

        System.out.println("Area 2: " + area2);

    }

    

    public static int calculateArea(int sideLength) {

        return sideLength * sideLength;

    }

    

    public static int calculateArea(int length, int width) {

        return length * width;

    }

}

Output

Area 1: 25

Area 2: 28

Explanation:

  • In this example, we have two methods named calculateArea().
  • The first method calculateArea(int sideLength) calculates the area of a square given the side length.
  • The second method calculateArea(int length, int width) calculates the area of a rectangle given the length and width.
  • Java determines which method to call based on the number and type of arguments passed.

Sample Problems

1. Write a Java method to check if a number is even or odd.

public class NumberChecker {

    public static void main(String[] args) {

        int number = 7;

        if (isEven(number)) {

            System.out.println(number + " is even.");

        } else {

            System.out.println(number + " is odd.");

        }

    }

    

    public static boolean isEven(int number) {

        return number % 2 == 0;

    }

}

Output

7 is odd.

2. Write a Java method to find the maximum of three numbers.

public class MaximumFinder {

    public static void main(String[] args) {

        int a = 5, b = 9, c = 3;

        int max = findMax(a, b, c);

        System.out.println("Maximum: " + max);

    }

    

    public static int findMax(int num1, int num2, int num3) {

        int max = num1;

        if (num2 > max) {

            max = num2;

        }

        if (num3 > max) {

            max = num3;

        }

        return max;

    }

}

Output

Maximum: 9

The document Methods in Java | Basics of Java - Software Development is a part of the Software Development Course Basics of Java.
All you need of Software Development at this link: Software Development
60 videos|37 docs|12 tests

Top Courses for Software Development

60 videos|37 docs|12 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

pdf

,

Sample Paper

,

ppt

,

mock tests for examination

,

past year papers

,

Important questions

,

Methods in Java | Basics of Java - Software Development

,

Viva Questions

,

Semester Notes

,

Exam

,

Free

,

Objective type Questions

,

Previous Year Questions with Solutions

,

Extra Questions

,

shortcuts and tricks

,

video lectures

,

MCQs

,

Summary

,

Methods in Java | Basics of Java - Software Development

,

practice quizzes

,

Methods in Java | Basics of Java - Software Development

,

study material

;