;
Java Basics July 21 ,2025

1. What is a Method in Java?

In Java, a method is a block of code that performs a specific task or operation. Methods help break programs into smaller, manageable, and reusable pieces. Think of a method as a set of instructions grouped together to perform an action — for example, printing a message, calculating a sum, or processing user input.

When you want to execute the task, you call (invoke) the method. You can define your own methods or use the ones already provided by Java.

How to Think of a Method:

Imagine you’re baking a cake. Instead of repeating the entire recipe every time, you write it once in a cookbook. Similarly, in programming, you define the method once and call it whenever you need to reuse it.

Real-World Analogy:

  • Turning on a fan = a method (you press a button → action is performed).
  • startFan() would be a method in programming terms that turns the fan on.

Basic Method Structure:

Here’s a simple method example in Java:

public static void greet() {
    System.out.println("Hello, welcome to Java methods!");
}

This method:

  • Is named greet
  • Doesn't take any input
  • Prints a message when called

To call this method:

greet(); // Output: Hello, welcome to Java methods!

Key Points:

TermMeaning
Method DeclarationThe part where you define what the method does
Method CallUsing or invoking the method in your code
Return TypeThe type of value the method gives back (or void if none)
ParametersInputs the method accepts (if any)

Benefits of Using Methods:

  • Reusability: Write once, use many times.
  • Maintainability: Divide logic into sections, easier to debug and maintain.
  • Modularity: Break down large tasks into smaller chunks.
  • Readability: Code becomes cleaner and easier to understand.

2. Why Use Methods in Java?

Using methods in your Java programs is essential for writing clean, efficient, and maintainable code. Especially in large programs, methods help organize logic, reduce repetition, and simplify debugging.

A. Code Reusability

One of the biggest advantages of using methods is reusability. Instead of writing the same code multiple times, you define it once in a method and call it whenever required.

Example:

public static void printWelcome() {
    System.out.println("Welcome to the Java Course!");
}

Now you can call printWelcome() multiple times throughout your program, saving time and lines of code.

B. Better Organization (Modularity)

Methods divide your program into logical sections. Each section (method) performs a specific task, making the overall structure more modular and manageable.

Example:
You might have:

  • calculateTotal()
  • applyDiscount()
  • generateBill()

Each method performs a part of your billing system, making it easy to isolate and understand each operation.

C. Easy Debugging and Maintenance

When your code is split into small methods, it's easier to:

  • Find where an error occurs
  • Fix only the faulty method without touching the entire program
  • Test individual units separately

D. Improves Readability

Short, descriptive method names make your code more readable. Instead of going through 100 lines of logic, you see clean calls like:

sendEmail();
printReceipt();
updateProfile();

E. Reduces Code Duplication

Instead of copying the same logic again and again, put it in a method. This helps if you want to change something later — just update the method once, and all method calls reflect the change.

F. Encourages Abstraction

Methods allow you to hide the implementation details. The caller doesn’t need to know how the method works — just what it does.

Example:

public static int sum(int a, int b) {
    return a + b;
}

Whoever uses sum(5, 10) doesn’t need to know how the addition happens.

 

3. Types of Methods in Java

In Java, methods are broadly classified into two types:

  1. Predefined Methods (also called built-in methods)
  2. User-defined Methods (methods created by the programmer)

Let’s understand both in detail.

A. Predefined (Built-in) Methods

These are the methods provided by Java itself. You don’t have to write them from scratch — you simply use them by calling from Java's libraries or classes like String, Math, Scanner, etc.

Examples:

  1. length() – Finds the length of a string
String name = "Java";
System.out.println(name.length()); // Output: 4
  1. sqrt() – Returns the square root of a number
System.out.println(Math.sqrt(16)); // Output: 4.0
  1. nextInt() – Reads an integer from user input
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();

These methods are defined inside Java libraries and can be reused anywhere.

B. User-defined Methods

These are the methods created by you (the programmer) to perform custom operations or tasks.

You define a user-defined method using this structure:

returnType methodName(parameters) {
    // code block
    return value; // if required
}

Examples:

  1. Method with no parameters and no return value:
public static void greet() {
    System.out.println("Hello!");
}
  1. Method with parameters and return type:
public static int add(int a, int b) {
    return a + b;
}

To use the method:

int result = add(10, 20);
System.out.println(result); // 30

Summary Table:

Type of MethodDescriptionExample
PredefinedProvided by Java libraryMath.sqrt(), length()
User-definedCreated by programmer for specific functionalityadd(), greet()

4. Defining a Method in Java (Syntax & Structure)

To create your own method in Java, you must define it first — this means writing the method signature (header) and the method body (the code that performs the task). This section explains how to define a method properly.

General Syntax:

returnType methodName(parameter1, parameter2, ...) {
    // Method body: code to be executed
    return value; // optional - only if returnType is not void
}

Let’s break down the parts:

PartDescription
returnTypeThe data type of the value the method returns (int, void, String, etc.)
methodNameThe name of the method (should follow camelCase)
parametersValues you pass into the method (optional)
returnKeyword used to return a value from the method (if needed)

Example 1: A Simple Method with No Parameters and No Return Value

public static void sayHello() {
    System.out.println("Hello, student!");
}
  • public static: Method is accessible and doesn’t need an object (for now, this is how we declare main methods).
  • void: Means it doesn’t return any value.
  • sayHello(): Method name with no parameters.

To call this method:

sayHello();

Example 2: Method with Parameters and a Return Type

public static int square(int num) {
    return num * num;
}
  • int is the return type
  • num is a parameter (input to method)
  • return keyword sends the output back to the caller

To use this method:

int result = square(5); // result = 25

Example 3: Method with Multiple Parameters

public static int add(int a, int b) {
    return a + b;
}

Calling:

System.out.println(add(10, 15)); // Output: 25

Important Rules for Defining Methods:

  1. Method name must follow naming conventions
    • Start with a lowercase letter
    • Use camelCase (e.g., calculateArea)
  2. Method must be inside a class
    Java does not allow functions outside classes.
  3. Return type must match the value being returned
    If your method returns an int, make sure the return statement returns an integer.
  4. If method returns nothing, use void
    Do not use return unless you want to exit early.

Summary Table:

FeatureExamplePurpose
void return typevoid greet()Method returns nothing
return valueint square(int x)Returns result to caller
multiple parametersint sum(int a, int b)Accepts more than one input
no parametersvoid showDate()Just performs action

5. Calling a Method in Java

Once a method is defined, it doesn’t run automatically. You need to call or invoke the method from another place in your code — usually from the main() method or another method.

Basic Format:

methodName(arguments); // for non-returning methods
returnType variable = methodName(arguments); // for methods that return a value

Example 1: Calling a Method with No Parameters and No Return Type

public static void greet() {
    System.out.println("Welcome to Java!");
}

public static void main(String[] args) {
    greet(); // calling the method
}

Output:

Welcome to Java!

Example 2: Calling a Method with Parameters and Return Type

public static int add(int a, int b) {
    return a + b;
}

public static void main(String[] args) {
    int result = add(5, 10); // calling and storing return value
    System.out.println("Sum is: " + result);
}

Output:

Sum is: 15

Example 3: Calling a Method Inside Another Method

public static void displaySquare(int n) {
    int square = calculateSquare(n);
    System.out.println("Square is: " + square);
}

public static int calculateSquare(int x) {
    return x * x;
}

public static void main(String[] args) {
    displaySquare(6); // internally calls calculateSquare(6)
}

Output:

Square is: 36

Important Notes:

  1. The method must be in the same class or you must access it using a class/object reference.
  2. Static methods can be called without creating an object, directly using the method name (within the same class).
  3. Non-static methods require an object to be created first.

Static vs Non-static Call Example:

public class Example {

    // static method
    public static void show() {
        System.out.println("Hello from static method");
    }

    // non-static method
    public void display() {
        System.out.println("Hello from non-static method");
    }

    public static void main(String[] args) {
        show(); // static method can be called directly

        Example obj = new Example(); // create object
        obj.display(); // calling non-static method using object
    }
}

Output:

Hello from static method
Hello from non-static method

 

6. Parameters and Arguments in Java Methods

In Java, parameters and arguments allow methods to accept data and work with it. This makes methods more flexible and reusable for different inputs.

A. What are Parameters and Arguments?

  • Parameters are variables listed in a method's definition.
  • Arguments are the actual values passed to the method when calling it.

     

📝 Think of parameters as input names and arguments as actual values.

Example:

// Method definition with parameters
public static void greetUser(String name) {
    System.out.println("Hello, " + name + "!");
}

// Method call with an argument
greetUser("Saumya");

Output:

Hello, Saumya!

B. Types of Parameters

1. No Parameter Method

public static void greet() {
    System.out.println("Hello!");
}

Called as:

greet();

2. Single Parameter Method

public static void square(int num) {
    System.out.println(num * num);
}

Called as:

square(4); // Output: 16

3. Multiple Parameters

public static void printSum(int a, int b) {
    System.out.println("Sum: " + (a + b));
}

Called as:

printSum(10, 15); // Output: Sum: 25

C. Matching Arguments with Parameters

You must pass:

  • The same number of arguments as the number of parameters
  • Compatible data types

Incorrect example:

printSum(10); // Error! Only one argument, but method needs two

D. Return Type vs Parameters

Remember:

  • Parameters = input for the method
  • Return type = output from the method

Example:

public static int multiply(int x, int y) {
    return x * y;
}

E. Using Expressions as Arguments

You can also pass calculated values:

printSum(10 + 5, 4 * 2); // Sum: 23

7. Return Statement in Java Methods

In Java, the return statement is used to:

  • Exit a method.
  • Send a result back to the caller (only if the method is not declared as void).

Understanding how and when to return values from a method is essential for writing modular and reusable code.

A. Syntax of return Statement

return value;

The value returned must match the return type specified in the method definition.

B. Method with a Return Value

Let’s look at a simple example:

public static int getDouble(int number) {
    return number * 2;
}

Here, getDouble returns an integer.

To use the return value:

int result = getDouble(10);
System.out.println(result); // Output: 20

C. Method with No Return Value (void)

If a method doesn’t return anything, it is declared with a void return type:

public static void greet() {
    System.out.println("Hello there!");
}

You call it directly:

greet();

No return value is used here, but you can still use return; to exit early if needed:

public static void checkAge(int age) {
    if (age < 18) {
        System.out.println("Not eligible");
        return; // exits the method early
    }
    System.out.println("Eligible");
}

D. Returning Different Data Types

You can return any data type — int, float, boolean, String, object, array, etc.

Examples:

  1. String Return:
public static String getName() {
    return "Java";
}
  1. Boolean Return:
public static boolean isEven(int num) {
    return num % 2 == 0;
}
  1. Array Return:
public static int[] getArray() {
    return new int[] {1, 2, 3};
}

E. Multiple Return Statements

You can use multiple return statements conditionally:

public static String grade(int marks) {
    if (marks >= 90) return "A";
    else if (marks >= 75) return "B";
    else return "C";
}

F. Common Mistakes to Avoid

  • Declaring a return type but forgetting to write a return statement.
  • Returning the wrong type of value.
  • Using return in a void method incorrectly with a value.

8. Method Overloading in Java

Method Overloading allows a class to have more than one method with the same name, but different parameters (type, number, or order). It helps make your code more readable and logically grouped, especially when performing similar operations on different data types or with different inputs.

Why Use Method Overloading?

  • To perform a similar operation in different ways.
  • To improve code reusability and readability.
  • To avoid creating separate method names for logically similar tasks.

A. Rules for Method Overloading

You can overload a method if:

  1. The number of parameters is different, or
  2. The data types of parameters are different, or
  3. The order of parameters is different (when data types vary)

✅ Method name must be the same
❌ Return type alone cannot distinguish overloaded methods

B. Examples of Method Overloading

Example 1: Changing Number of Parameters

public static void greet() {
    System.out.println("Hello!");
}

public static void greet(String name) {
    System.out.println("Hello, " + name);
}

Calling:

greet(); // Hello!
greet("Saumya"); // Hello, Saumya

Example 2: Changing Data Types of Parameters

public static int add(int a, int b) {
    return a + b;
}

public static double add(double a, double b) {
    return a + b;
}

Calling:

System.out.println(add(5, 10));       // 15
System.out.println(add(5.5, 4.5));    // 10.0

Example 3: Changing Order of Parameters

public static void display(String name, int age) {
    System.out.println(name + " is " + age + " years old.");
}

public static void display(int age, String name) {
    System.out.println(name + " is " + age + " years old.");
}

Calling:

display("John", 25);  // John is 25 years old.
display(30, "Amit");  // Amit is 30 years old.

C. What Does NOT Qualify as Overloading?

Changing only the return type does not qualify:

// Invalid: Compiler Error
public static int print() { return 1; }

public static void print() { System.out.println("Hello"); }

This will cause a compiler error because the method signature (name + parameters) is the same.

D. Method Overloading with Static Methods

Static methods can also be overloaded just like regular methods:

public static void show() {
    System.out.println("No value");
}

public static void show(int x) {
    System.out.println("Value: " + x);
}

E. Advantages of Method Overloading

  • Makes the program more readable and clean.
  • Allows performing similar operations with different types or number of inputs.
  • Reduces the need to remember multiple method names.

Summary Table:

Method SignatureDescription
add(int a, int b)Adds two integers
add(double a, double b)Adds two doubles
add(int a, int b, int c)Adds three integers
display(String name, int age)Name first
display(int age, String name)Age first

9. Static vs Non-static Methods in Java

In Java, methods can be categorized into static and non-static (instance) methods. Understanding their differences is essential to know when to call methods using a class name and when you need an object.

A. What is a Static Method?

A static method belongs to the class rather than an instance of the class. It can be called without creating an object.

Syntax:

public static void methodName() {
    // method body
}

B. What is a Non-static Method?

A non-static method belongs to an object (instance) of the class. You need to create an object to call it.

Syntax:

public void methodName() {
    // method body
}

C. Example: Static vs Non-static

public class MyClass {

    // Static method
    public static void greet() {
        System.out.println("Hello from static method!");
    }

    // Non-static method
    public void welcome() {
        System.out.println("Hello from non-static method!");
    }

    public static void main(String[] args) {
        // Calling static method
        MyClass.greet(); // Direct call using class name

        // Calling non-static method
        MyClass obj = new MyClass();
        obj.welcome(); // Requires object
    }
}

Output:

Hello from static method!
Hello from non-static method!

D. Key Differences

FeatureStatic MethodNon-static Method
Belongs toClassObject
Called usingClass nameObject reference
Can accessOnly static variables/methodsBoth static and instance members
Object needed?❌ No✅ Yes
Memory allocationAt class loadingWhen object is created

E. When to Use What?

  • Use static methods when:
    • The logic is independent of any object.
    • The method doesn’t need access to instance variables.
    • Utility/helper functions (e.g., Math.sqrt(), Arrays.sort()).
  • Use non-static methods when:
    • Method behavior depends on object state (instance variables).
    • You need object-specific behavior.

F. Practical Tip

A good rule of thumb:
If your method does not use any instance variables, make it static.

10. Best Practices for Using Methods in Java

Writing effective methods is not just about syntax—it’s about clarity, reusability, maintainability, and performance. Follow these best practices to become a better Java programmer.

A. Keep Methods Short and Focused

A method should perform a single, well-defined task.

Bad:

public void processOrderAndPrintInvoiceAndSendEmail() {
    // does too much at once
}

Good:

public void processOrder() { }
public void printInvoice() { }
public void sendEmail() { }

B. Use Descriptive Method Names

Use meaningful names that explain what the method does.

Examples:

  • calculateTotal(), not calc()
  • isValidEmail(), not check1()

Use verbs for methods: get, set, compute, validate, etc.

C. Avoid Using Too Many Parameters

Keep parameter lists short (ideally under 4). If needed, create a helper class to pass multiple values.

// Instead of
public void register(String name, int age, String email, String address) { }

// Use a model class
public void register(User user) { }

D. Reuse Code with Methods

If the same block of code appears multiple times, convert it into a method.

Before:

System.out.println(a + b);
System.out.println(x + y);

After:

public static void printSum(int a, int b) {
    System.out.println(a + b);
}

E. Use Return Statements Effectively

  • Return values when results are needed elsewhere.
  • Don't return unnecessary data.
  • Use early return; to exit method cleanly when appropriate.

F. Choose Static or Non-static Wisely

  • Use static when method doesn't depend on object state.
  • Use non-static when method works with instance variables.

G. Add Comments and JavaDoc

Document complex methods using // comments or /** JavaDoc */.

/**
 * Calculates the area of a circle.
 * @param radius Radius of the circle
 * @return Area value
 */
public double calculateArea(double radius) {
    return Math.PI * radius * radius;
}

H. Handle Edge Cases in Methods

Check for invalid inputs, like null values, negative numbers, or empty arrays.

public int findMax(int[] nums) {
    if (nums == null || nums.length == 0) return -1;
    // continue logic
}

I. Group Related Methods in Classes

Follow object-oriented principles. Group related methods into logical classes.

class MathUtils {
    public static int square(int x) { return x * x; }
    public static int cube(int x) { return x * x * x; }
}

J. Test Your Methods

Always test methods independently to verify:

  • They return correct results
  • They handle invalid inputs
  • They don't cause side effects

 Summary: Method Best Practices

PracticeWhy It Matters
Keep methods smallEasier to understand and debug
Use clear namesImproves readability
Limit parametersEasier method calls
Write reusable logicAvoid duplication
Use comments/docMakes code maintainable
Check for nulls / edge casesPrevents bugs
Static vs Non-staticImproves memory and design

 

Next Blog- Object-Oriented Programming (OOP) Basics

Sanjiv
0

You must logged in to post comments.

Get In Touch

123 Street, New York, USA

+012 345 67890

techiefreak87@gmail.com

© Design & Developed by HW Infotech