Methods in Java are an essential part of programming that help in organizing code efficiently. This article will explain what methods are, their different types, and how they are used in Java. We will also explore their benefits and practical applications to give you a thorough understanding of methods in Java.
Contents:
- What is a Method in Java?
- Types of Methods in Java
- Defining a Method
- Calling a Method
- Method Parameters and Return Types
- Static vs Instance Methods in Java
- Method Overloading in Java
- Method Overriding in Java
- Recursion Method in Java
- FAQs on Methods in Java
What is a Method in Java?
A method in Java is a collection of statements that execute a specific operation. It allows code reuse and reduces redundancy by avoiding repetitive code. Java programs always contain a main() method, which acts as the entry point for program execution.
Syntax of a Java Method:
A method in Java is defined using the following syntax:
returnType methodName(parameterList) { // Method body return value; // Required if returnType is not void }
- returnType: Defines what type of value the method gives back (e.g., int, String). If the method doesn’t return anything, use void.
- methodName: The name of the method (e.g., calculateSum). It should be meaningful and follow Java naming rules.
- parameterList: Inputs the method can accept (optional). These are placed inside parentheses.
- return statement: Needed if the method returns a value. If the return type is void, this is not required.
Types of Methods in Java
In Java, methods are categorized based on their functionality and declaration. The two main types of methods are:
- Predefined Methods (Built-in Methods)
- User-defined Methods
1. Predefined Methods (Built-in Methods)
These are methods that come with Java’s standard libraries. You can use them without defining them.
Examples of Predefined Methods
- Math.sqrt(36) → Returns the square root of 36 (Output: 6.0).
- System.out.println(“Java”) → Prints text to the console.
- Arrays.sort(array) → Sorts an array in ascending order.
2. User-defined Methods
User-defined methods in Java are custom methods created by the programmer to perform specific tasks.
Example:
public class Sanfoundry { public static void greet() { System.out.println("Hello, welcome to Java Course!"); } public static void main(String[] args) { greet(); } }
Output:
Hello, welcome to Java Course!Defining a Method
In Java, a method is a block of code that performs a specific task. It must be defined inside a class.
public class SanfoundryExample { // Defining a method public void displayMessage() { System.out.println("Welcome to Sanfoundry MCQs!"); } }
In this example:
- The method displayMessage() is defined using public void.
- It prints a message when called.
Calling a Method
To call a method, you must create an object of the class and use the dot (.) operator.
public class SanfoundryTest { public static void main(String[] args) { // Creating an object SanfoundryExample obj = new SanfoundryExample(); // Calling the method obj.displayMessage(); } }
Output:
Welcome to Sanfoundry MCQs!Explanation:
- An object obj is created from SanfoundryExample.
- The method displayMessage() is called using obj.displayMessage();.
- It executes and prints the output.
Method Parameters and Return Types
Method with Parameters
A method can accept input values (parameters) to perform operations.
public class Sanfoundry { public void add(int a, int b) { System.out.println("Sum: " + (a + b)); } public static void main(String[] args) { SanfoundryCalculator calc = new SanfoundryCalculator(); calc.add(5, 10); } }
Output:
Sum: 15
Method with Return Type
A method can return a value using the return keyword.
public class SanfoundryTest { public static void main(String[] args) { SanfoundryMultiplication obj = new SanfoundryMultiplication(); // Storing the returned value int result = obj.multiply(5, 4); // Printing the result System.out.println("Product: " + result); } }
Output:
Product: 20
Static vs Instance Methods in Java
In Java, methods can be categorized as static or instance methods based on how they are accessed and associated with a class or an instance of a class.
| Feature | Static Method | Instance Method |
|---|---|---|
| Definition | Belongs to the class and is declared using the static keyword. |
Belongs to an instance (object) of the class. |
| Accessed via | Class name (ClassName.methodName()) or an object (not recommended). |
Requires an object (objectName.methodName()). |
| Memory Allocation | Allocated in Method Area once per class. | Created separately for each object in Heap Memory. |
| Can Access | Only static variables and static methods of the class. | Both static and instance variables/methods. |
| Use Case | Utility methods (e.g., Math.pow(), Collections.sort()). |
Behavior dependent on object state (e.g., getName() for an employee). |
| Overriding | Cannot be overridden but can be hidden in subclasses. | Can be overridden in subclasses (runtime polymorphism). |
| Example | public static void showMessage() {} |
public void displayInfo() {} |
Method Overloading in Java
Method overloading is a feature in Java that allows multiple methods to have the same name but with different parameters (different types, number of parameters, or both). It helps in improving code readability and reusability.
public class SanfoundryQuiz { // Overloaded method with one parameter public void showTopic(String topic) { System.out.println("Sanfoundry MCQs on: " + topic); } // Overloaded method with two parameters public void showTopic(String topic, int questions) { System.out.println("Sanfoundry MCQs on: " + topic + " | Total Questions: " + questions); } public static void main(String[] args) { SanfoundryQuiz quiz = new SanfoundryQuiz(); quiz.showTopic("Java"); quiz.showTopic("C Programming", 50); } }
Output:
Sanfoundry MCQs on: Java Sanfoundry MCQs on: C Programming | Total Questions: 50
Explanation:
- The class SanfoundryQuiz contains two methods named showTopic, but with different parameter lists.
- The first method accepts a single String parameter (topic name).
- The second method accepts a String (topic name) and an integer (number of questions).
- Based on the arguments passed, Java automatically determines which method to call.
- This demonstrates method overloading, where the method name remains the same, but the parameter list changes.
Method Overriding in Java
Method Overriding is a feature in Java where a subclass provides a specific implementation of a method already defined in its superclass. The overridden method in the child class must have the same method signature (method name, return type, and parameters) as in the parent class.
// Parent class class SanfoundryTopic { public void showInfo() { System.out.println("Sanfoundry MCQs on various topics."); } } // Child class overriding the method class JavaQuiz extends SanfoundryTopic { @Override public void showInfo() { System.out.println("Sanfoundry MCQs on Java Programming."); } } public class MethodOverridingExample { public static void main(String[] args) { SanfoundryTopic topic1 = new SanfoundryTopic(); topic1.showInfo(); // Calls parent class method SanfoundryTopic topic2 = new JavaQuiz(); topic2.showInfo(); // Calls overridden method in child class } }
Output:
Sanfoundry MCQs on various topics.
Sanfoundry MCQs on Java Programming.Explanation:
- The code demonstrates method overriding in Java. The parent class SanfoundryTopic defines a method showInfo() that prints the message “Sanfoundry MCQs on various topics.”.
- The child class JavaQuiz overrides the showInfo() method to provide a new implementation that prints “Sanfoundry MCQs on Java Programming.”.
- In the main() method, when the showInfo() method is called on an object of the parent class (topic1), it executes the method from the parent class.
- However, when the showInfo() method is called on an object of the child class (topic2), it invokes the overridden method in the child class due to runtime polymorphism, resulting in different outputs depending on the actual object type.
- The output demonstrates this by printing both the parent class and child class messages.
Recursion Method in Java
Recursion in Java refers to a method calling itself in order to solve a problem. This approach can be useful when a problem can be divided into smaller sub-problems that are similar to the original problem.
public class SanfoundryRecursionExample { // Recursive method to calculate factorial public static int SanfoundryFactorial(int n) { // Base case: if n is 0 or 1, return 1 if (n == 0 || n == 1) { return 1; } // Recursive case: n * factorial of n-1 else { return n * SanfoundryFactorial(n - 1); } } public static void main(String[] args) { int number = 5; // Example number to calculate factorial int result = SanfoundryFactorial(number); // Call the recursive method System.out.println("Factorial of " + number + " is: " + result); } }
Output:
Factorial of 5 is: 120
Explanation:
- The SanfoundryFactorial method is a recursive method that computes the factorial of a given number.
- The base case checks if n is 0 or 1, in which case it returns 1.
- The recursive case returns n * SanfoundryFactorial(n – 1), which means it calls the same method with n-1 until it hits the base case.
FAQs on Methods in Java
1. What is a method in Java?
A method in Java is a block of code that performs a specific task and can be called whenever needed. It helps in code reusability and better organization.
2. What are the types of methods in Java?
Java methods are categorized into two types:
- Predefined Methods: Methods already provided by Java, such as System.out.println(), Math.sqrt(), etc.
- User-defined Methods: Methods created by the user to perform specific operations.
3. Can we declare a method inside another method?
No, Java does not support nested methods, but we can define methods inside local/anonymous inner classes.
4. What is method overloading?
Method overloading allows multiple methods with the same name but different parameter lists in the same class. It enhances readability and flexibility.
5. What is method overriding?
Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass. It enables runtime polymorphism.
6. Can we override a static method?
No, static methods cannot be overridden. If a subclass defines a static method with the same name as in the superclass, it is known as method hiding rather than overriding.
Key Points to Remember
Here is the list of key points we need to remember about the “Java Methods”.
- A method is a block of code that performs a specific task, promoting code reuse and reducing redundancy.
- Java has predefined methods (built-in, like Math.sqrt()) and user-defined methods (custom methods created by programmers).
- Method overloading allows multiple methods with the same name but different parameters, while method overriding lets a subclass modify a parent class method.
- Static methods belong to the class (called via class name), while instance methods require an object to be accessed.
- Methods can accept parameters (input values) and return a value using the return keyword, or use void if nothing is returned.
- A method calling itself to solve a problem (e.g., calculating factorial) is called recursion, useful for breaking problems into smaller sub-problems.
Continue learning Java from basics to advanced topics in our complete Java Tutorial.
Practice what you’ve learned with topic-wise questions on our Java MCQs.