Java Methods are a key part of writing clean and efficient Java programs. They help you break down complex tasks into smaller, manageable steps, making your code easier to read, reuse, and maintain. Whether you’re performing a calculation, handling user input, or running a specific task, methods make everything more organized and straightforward.
Java Methods
What is a Method in Java?
In Java, a method is a block of code designed to perform a specific task. Methods are written inside a class but outside the main method. They are executed only when called, making them a critical part of creating structured and reusable programs.
Syntax of a Method:
To execute a method, it must be called from the main method or another method. Let’s look at how to call a method.
Syntax for Method Call:
methodName();
Example:
class Passion2Code {
public static void greet() {
System.out.println("Hello, welcome to Passion2Code!");
}
public static void main(String[] args) {
greet();
}
}
In the above example, the greet method is called inside the main method, which executes it and prints a message.
Why are Java Methods Used?
Reusability: Code can be reused multiple times by calling the same method.
Readability: Methods make the code easier to read and understand.
Modularity: Breaking code into smaller methods allows better organization.
How to Create a Method in Java:
To create a method, follow these steps:
- Define the method inside the class.
- Specify the access modifier, return type, and method name.
- Write the task the method should perform inside curly braces.
Example:
class Passion2Code {
public void displayMessage() {
System.out.println("Java methods make programming easier!");
}
}
You can call the above method using an object of the Passion2Code class.
Types of Java Methods
There are two main types of methods in Java:
- Static Methods
- Non-Static Methods
1. Static Methods:
These are the methods defined using the static keyword in its method signature. Static methods can be called directly by using a class name.
Syntax:
ClassName.methodName();
Example:
class Passion2Code {
public static void staticMethod() {
System.out.println("This is a static method.");
}
public static void main(String[] args) {
Passion2Code.staticMethod();
}
}
2. Non-Static Methods:
These are the methods that do not contain static keywords in their method signature. Non-static methods cannot be called directly instead we need to create a reference variable.
Syntax:
ClassName referenceVariable = new ClassName();
referenceVariable.methodName();
Example:
class Passion2Code {
public void nonStaticMethod() {
System.out.println("This is a non-static method.");
}
public static void main(String[] args) {
Passion2Code obj = new Passion2Code();
obj.nonStaticMethod();
}
}
Method Calling in Java
In Java, methods can be called other methods. This concept is known as method calling methods. It can be done in four ways:
- Static Method Calling Another Static Method (Directly)
- Non-Static Method Calling a Static Method (Directly)
- Non-Static Method Calling Another Non-Static Method (Directly)
- Static Method Calling a Non-Static Method (Using Reference)
1. Static Method Calling Another Static Method directly in its implementation
class Passion2Code {
public static void methodA() {
System.out.println("Method A");
}
public static void methodB() {
methodA();
}
public static void main(String[] args) {
methodB();
}
}
Output: Method A
Explanation:
- Both methodA and methodB are static methods, meaning they can be called directly without creating an object of the class.
- The methodB calls methodA directly since static methods can call other static methods within the same class.
- In the main method, methodB is called directly.
- When methodB is executed, it internally calls methodA, which prints “Method A“ to the console.
2. Non-Static Method Calling a Static Method directly in its implementation
class Passion2Code {
public static void staticMethod() {
System.out.println("Static method called");
}
public void nonStaticMethod() {
staticMethod();
}
public static void main(String[] args) {
Passion2Code obj = new Passion2Code();
obj.nonStaticMethod();
}
}
Output: Static method called
Explanation:
- The staticMethod is a static method, so it can be called directly without creating an object of the class. It prints the message “Static method called“ to the console.
- The nonStaticMethod is an instance method, so it requires an object of the class to be called. Inside this method, the staticMethod is invoked directly since static methods can be accessed from anywhere in the class.
- In the main method, an object of the Passion2Code class is created. The nonStaticMethod is called using this object.
- The nonStaticMethod internally calls the staticMethod, and the message “Static method called“ is printed to the console.
3. Non-Static Method Calling Another Non-Static Method directly in its implementation
class Passion2Code {
public void methodA() {
System.out.println("Method A");
}
public void methodB() {
methodA();
}
public static void main(String[] args) {
Passion2Code obj = new Passion2Code();
obj.methodB();
}
}
Output: Method A
Explanation:
- The methodA prints the message “Method A“ to the console.
- The methodB calls methodA directly, as both methods belong to the same class.
- In the main method, an object of the Passion2Code class is created.
- The methodB is called using the object, which internally calls methodA.
- As a result, “Method A“ is printed to the console.
4. Static Method Calling a Non-Static Method indirectly, using reference variable in its implementation
class Passion2Code {
public void nonStaticMethod() {
System.out.println("Non-static method called");
}
public static void staticMethod() {
Passion2Code obj = new Passion2Code();
obj.nonStaticMethod();
}
public static void main(String[] args) {
staticMethod();
}
}
Output: Non-static method called
Explanation:
- The nonStaticMethod is an instance method, so it requires an object of the class to be called.
- The staticMethod is a static method, meaning it can be called directly without creating an object of the class.
- Inside the staticMethod, an object of the Passion2Code class is created, and the nonStaticMethod is called using this object.
- The main method calls the staticMethod, which in turn calls the nonStaticMethod, and the message “Non-static method called” is printed to the console.
Methods with Arguments
Methods with Arguments are methods that accept inputs, called arguments or parameters, to process data dynamically. These inputs allow a method to perform its task based on the provided values, making it more flexible and reusable. Arguments are specified within the parentheses of the method declaration and can vary in type and number, depending on the method’s purpose.
Syntax:
Example:
class Passion2Code {
public void greet(String name) {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
Passion2Code obj = new Passion2Code();
obj.greet("JESSY");
}
}
Output: Hello, JESSY
Explanation:
- The method greet() has a return type of void, meaning it does not return any value.
- It takes a single argument name, of type String, and prints a personalized greeting using System.out.println().
- In the main method, an object of the Passion2Code class is created.
- The greet method is called on the object with the argument “JESSY”.
- The method prints “Hello, JESSY” to the console.
Methods with Return Types
Return Type
The return type specifies the type of value that a method will produce or return after it completes its task. It defines what kind of data the method will send back to the calling code. For example, a method can return types like void, int, double, char, boolean, or String.
Return Types:
- void: The method doesn’t return anything.
- int: Returns an integer value.
- double: Returns a decimal value.
- char: Returns a single character.
- boolean: Returns a true or false value.
- String: Returns a text or string value.
What is the return Keyword
The return keyword is used to send JVM outside of the method block and optionally send a value back to the calling method. A method can either carry a value with return or simply exit without returning anything (in the case of void methods).
Important Note: The return type of a method and the value it returns must always match. For example, if the return type is int, the method must return an integer.
Example:
class Passion2Code {
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Passion2Code obj = new Passion2Code();
int result = obj.add(5, 10);
System.out.println("Result: " + result);
}
}
Output: Result: 15
Explanation:
- The method add has a return type of int, meaning it will return an integer value.
- It takes two integer arguments, a and b, adds them, and returns the result.
- In the main method, an object of the Passion2Code class is created to call the add method.
- The method is called with the arguments 5 and 10, and the result (15) is stored in the variable result.
- The value of the result is then printed to the console.
When we use the return type as a void then we can use the return keyword in the method without carrying the value. Return keyword should be the last statement for the method, if any statement is created below the return then we will get an unreachable statement error. If the return type is void and the return value is given then we will get an unexpected return value error.
Create a method with the return type int:
public class Passion2Code {
// Method to calculate the sum of two numbers
public static int addNumbers(int a, int b) {
// Adding the two numbers
int sum = a + b;
// Returning the result
return sum;
}
public static void main(String[] args) {
// Calling the method and storing the returned value
int result = addNumbers(10, 20);
// Printing the result
System.out.println("The sum is: " + result);
}
}
Output: The sum is: 30
Explanation:
- The method addNumbers has a return type of int, meaning it will return an integer value.
- It takes two integer arguments, a and b, adds them, and returns the result.
- The main method calls addNumbers and stores the returned value in the variable result, which is then printed.
When we create a method with a return type int that method must contain a return keyword with a return (int) value. The returned value can be used or cannot be used. Always return value will be given to the method call.
Why Return Types are Required for Java Methods?
Return types are essential because they allow a method to send a value back to the caller, which can be used in another method or part of the program. They make it possible to pass data between methods and reuse the result of a computation.
Here’s an example to show why return types are required:
Example:
class Passion2Code {
// Method with a return type that calculates the square of a number
public int square(int number) {
return number * number; // Returning the square of the number
}
// Method that uses the returned value from another method
public void displaySquare(int number) {
int result = square(number); // Using the value returned by the square method
System.out.println("The square of " + number + " is: " + result);
}
public static void main(String[] args) {
Passion2Code obj = new Passion2Code();
obj.displaySquare(5); // Calling the method to display the square
}
}
Output: The square of 5 is: 25
Explanation:
- The square method has a return type of int and calculates the square of the given number. It returns the result to the caller.
- The displaySquare method uses the value returned by the square method to display the result.
- In the main method, the displaySquare method is called, which internally calls the square method to calculate and display the square of the number.
This demonstrates how return types allow methods to share and reuse values efficiently.
Tasks for Practice
Task 1:
- Create a class.
- Define three methods inside the class.
- Create a main method and call these methods inside it.
- Make multiple calls to the methods and observe the output.
Task 2:
- Create a class.
- Define five non-static methods.
- Create a main method and call all the non-static methods inside it.
Task 3:
- Create a method with arguments and a return type (e.g., a method to calculate the area of a rectangle).
- Call the method from the main method, store the returned value in a variable, and print it.
Summary
Mastering Java methods is fundamental to becoming a proficient Java programmer. By organizing your code into methods, you can write cleaner, more efficient programs. With the examples and tasks provided, you now have a strong foundation to practice and build your skills.
Must Read
Operators in Java
– Get to know the various operators in Java and how to use them in expressions.
Decision-Making Statements in Java
– Learn how to control the flow of your program using if, if-else, switch, and other decision-making constructs.
Looping Statements in Java
– Master the art of iteration with for, while, and do-while loops in Java.
Jumping Statements in Java
– Understand how to alter the flow of loops using break, continue, and return statements in Java.
FAQ’S
What is a method in Java?
A method in Java is a block of code designed to perform a specific task. It is written inside a class and is executed only when called.
What are the types of methods in Java?
Java methods are categorized into two types:
- Static Methods: Called directly using the class name.
- Non-Static Methods: Called using an object of the class.
How do you call a static method in Java?
Static methods can be called directly using the class name and method name.
Example:
ClassName.methodName();
What is the purpose of return types in methods?
Return types specify the kind of value a method will return after execution. They allow methods to send results back to the caller, enabling reuse and data sharing between methods.
Can a method have parameters in Java?
Yes, methods can have parameters to accept input values, allowing them to perform tasks based on those inputs.
What is the difference between void and non-void methods?
- Void Methods: Do not return any value.
- Non-Void Methods: Return a value, such as an integer, string, or object, depending on the return type specified.
Why are methods used in Java?
Methods improve code reusability, readability, and modularity, making programs easier to manage and maintain.
How do you call a non-static method from a static context?
To call a non-static method, you need to create an object of the class and use the object reference.
Example:
ClassName obj = new ClassName();
obj.methodName();