Java From Beginner To Advanced

0% completed

Previous
Next
Defining methods in Java

Methods in Java are blocks of code designed to perform specific tasks. They help in organizing code into reusable and manageable sections, making programs more modular and easier to maintain. By defining methods, you can execute the same code multiple times without rewriting it, enhancing code efficiency and readability.

Syntax of Defining a Method

accessModifier returnType methodName(parameters) { // Method body }
Image
  • accessModifier: Determines the visibility of the method (e.g., public, private, protected). We will learn more about access modifiers in advanced Java course.
  • returnType: Specifies the type of value the method returns (e.g., int, String, void if no value is returned).
  • methodName: The name of the method, following Java naming conventions.
  • parameters: (Optional) Input values the method can accept, defined as a comma-separated list of type and variable name.
  • Method Body: Contains the code that defines what the method does.

How to Call Methods

Calling a method in Java involves invoking the method by its name followed by parentheses. If the method requires parameters, you pass the necessary arguments inside the parentheses. Depending on the method's return type, you can also capture and use the returned value.

Syntax

methodName(arguments);
  • methodName: The name of the method you want to call.
  • arguments: The values you pass to the method's parameters (if any).

If the method returns a value, you can store it in a variable:

returnType variableName = methodName(arguments);
  • returnType: The type of value the method returns.

  • variableName: The variable that will store the returned value.

Example 1: Simple Method with Return Type and Parameters

Below is an example of a method that adds two integers and returns the result.

Java
Java

. . . .

Explanation:

  • Method Declaration: public static int addNumbers(int a, int b)
    • public: Method is accessible from other classes.
    • static: Method belongs to the class, not instances of the class.
    • int: Method returns an integer value.
    • addNumbers: Name of the method.
    • int a, int b: Parameters the method accepts.
  • Method Body:
    • int result = a + b; Calculates the sum of a and b.
    • return result; Returns the sum to where the method was called.
  • Method Call: addNumbers(5, 10)
    • Passes 5 and 10 as arguments to the method.
    • Receives 15 as the returned value and assigns it to sum.
  • Output:
    • Prints "Sum: 15" to the console.

Example 2: Method Without Parameters and No Return Value

Below is an example of a method that prints a greeting message without accepting any parameters or returning any value.

Java
Java

. . . .

Explanation:

  • Method Declaration: public static void greet()
    • void: Indicates that the method does not return any value.
    • greet: Name of the method.
    • No Parameters: The method does not accept any input.
  • Method Body:
    • System.out.println("Hello, welcome to Java programming!"); Prints the greeting message.
  • Method Call: greet();
    • Executes the greet method, resulting in the message being printed.
  • Output:
    • Prints "Hello, welcome to Java programming!" to the console.

Example 3: Method with Multiple Parameters and Return Type

Below is an example of a method that calculates the area of a rectangle given its length and width.

Java
Java

. . . .

Explanation:

  • Method Declaration: public static double calculateArea(double length, double width)
    • double: Method returns a double value representing the area.
    • calculateArea: Name of the method.
    • double length, double width: Parameters representing the dimensions of the rectangle.
  • Method Body:
    • double area = length * width; Calculates the area by multiplying length and width.
    • return area; Returns the calculated area.
  • Method Call: calculateArea(5.5, 3.2)
    • Passes 5.5 and 3.2 as arguments.
    • Receives 17.6 as the returned value and assigns it to area.
  • Output:
    • Prints "Area of the rectangle: 17.6" to the console.

Why Use Methods?

  • Reusability: Methods allow you to reuse code blocks multiple times without rewriting them, reducing redundancy.
  • Modularity: Breaking down complex problems into smaller, manageable methods makes your code organized and easier to understand.
  • Maintainability: Changes made in a method automatically reflect wherever the method is called, simplifying updates and maintenance.
  • Readability: Well-named methods can make your code more readable by abstracting complex logic behind simple method calls.
  • Debugging: Isolating functionality within methods makes it easier to locate and fix bugs.

Defining methods is a fundamental concept in Java that promotes code organization, reusability, and clarity. By mastering method creation and usage, you can build more efficient and maintainable Java applications.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next