series
Java is an object-oriented programming language that follows a structured approach to coding. One key component of Java programming is methods (functions in some contexts). Methods help ensure code reusability, modularity, and maintainability. In this blog, we will explore methods in Java, their types, and the best practices for writing efficient methods.
A method in Java is a block of code that performs a specific task. It is defined using a specific structure that includes a name, return type, parameters (optional), and method body.
Syntax of a Method
access_modifier return_type method_name(parameter_list) {
// Method body (logic to be executed)
return value; // (Only required if return_type is not void)
}
Use our
Output
Sum: 15
Use our
Example:
public int add(int a, int b) {
return a + b;
}
Use our
Example of Access Modifiers:
class MasterBackend {
public void publicMethod() {
System.out.println("Public Method");
}
private void privateMethod() {
System.out.println("Private Method");
}
protected void protectedMethod() {
System.out.println("Protected Method");
}
void defaultMethod() { // No modifier means 'default'
System.out.println("Default Method");
}
}
Use our
Method with a return type (int)
public int multiply(int a, int b) {
return a * b;
}
Use our
4. Method Name and Parameters
Method Name: It should be meaningful, following the camelCase naming convention.
Parameters: Values passed to the method inside parentheses
()(optional).
Example:
public double calculateDiscount(double price, double discountRate) {
return price - (price * discountRate / 100);
}
Use our
Output:
Hello from MasterBackend!
Use our
Output:
Static Method Called!
Non-Static Method Called!
Use our
Output:
Hello, Welcome to Java Programming!
Use our
Output:
Hello, Ayush! Welcome to Java.
Use our
Output:
The number is: 100
Use our
Output:
The sum is: 30
Use our
Output:
Number: 10
Number: 20, Text: Java
Use our
Output:
Message from Child class
Use our Annotation
The @Override annotation ensures that a method correctly overrides a method from its parent class.
Benefits of @Override:
Helps catch errors if the method signature does not match.
Improves code readability.
Example Without
Here, showMessage(int num) is not actually overriding the parent method because its signature is different.
With @Override, Java will catch such errors:
class Child extends Parent {
@Override
void showMessage(int num) { // Compilation Error: Method does not override parent method
System.out.println("Message from Child: " + num);
}
}
Use our
Conclusion
Java methods play a crucial role in structuring programs by enabling code reusability, modularity, and better organization. They help in breaking down large codebases into smaller, manageable blocks, making the program easier to read, maintain, and debug.
Have a great one!!!
SOCIAL SHARE CARD GENERATOR