Java Methods

Java methods are one of the fundamental building blocks of programming in Java. They allow you to organize your code into smaller, more manageable pieces, which can be called upon as needed. In this blog, we will discuss Java methods, their types, and how to use them in your code. We will also provide example code snippets to illustrate each concept.

Types of Java Methods:

Java has two types of methods:

  1. Built-in Methods: These methods are built into the Java language, and they are available to all Java programs.

Example:

System.out.println("Hello, World!");

In the above example, we are using the built-in method println() to print the message “Hello, World!” to the console.

  1. User-Defined Methods: These methods are created by the user and can be called upon as needed in your code.

Example:

public void exampleMethod() {
   // method body
}

In the above example, we are creating a user-defined method called exampleMethod().

Declaring Methods:

To declare a method, you need to specify the method’s access level, return type, name, and parameters.

Example:

public int sum(int num1, int num2) {
   int result = num1 + num2;
   return result;
}

In the above example, we are declaring a method called sum() with the public access level, an int return type, two int parameters num1 and num2, and a method body that calculates the sum of num1 and num2 and returns the result.

Calling Methods:

To call a method, you need to refer to the method’s name and pass any necessary arguments.

Example:

int result = sum(10, 20);
System.out.println("The sum of 10 and 20 is: " + result);

In the above example, we are calling the method sum() with arguments 10 and 20 and storing the result in a variable called result. We then print the result to the console.

Overloading Methods:

Java allows you to define methods with the same name but different parameters. This is called method overloading.

Example:

public int sum(int num1, int num2) {
   int result = num1 + num2;
   return result;
}

public int sum(int num1, int num2, int num3) {
   int result = num1 + num2 + num3;
   return result;
}

In the above example, we have two methods with the same name sum() but different parameters. The first method takes two int parameters, while the second method takes three int parameters.

Final Thoughts:

Java methods are essential to creating well-organized and efficient Java code. With the examples provided, you can get started with Java methods and take your programming skills to the next level. By understanding the different types of methods, how to declare and call them, and how to use method overloading, you can create more robust Java programs.