Instance Method in Java

An instance method in Java is a non-static method that belongs to an object (or an instance) of a class. It does not tie up with class itself. You can use this type of method to define behavior that operates on the instance variables (data) of the class. Inside the instance method, you can access instance variables and invoke other instance methods of the same class.

The statements inside an instance method are executed when you call it using an object of the class. Although all objects share the same method code, each method operates on the instance-specific data of the object it is called on. You cannot call an instance method from a static context without creating an object.

Learn instance method in Java: Ultimate guide with examples.

Syntax to Declare Instance Method in Java

The general syntax for declaring an instance method in Java programming is as follows:

<access_modifier> <return_type> <method_name>(<parameter_list>) {
    // method body
}

Components of an Instance Method

There are five components of an instance method in Java which are as follows:

1. access_modifier specifies the accessibility of the method within the program. You can use one of four access modifiers:

  • public — accessible from anywhere
  • private — accessible only within the same class
  • protected — accessible within the same package and subclasses
  • default (no modifier) — accessible within the same package

2. return_type defines the data type of the value returned by the method to the caller. If the method does not return any value, use void.

3. method_name is the name of the method. For example: display, calculateTotal, etc. It should follow Java naming conventions.

4. parameter_list is an optional list of input variables passed to the method. For example: (int a, String name). If there are no parameters, you can simply use empty parentheses: ().

5. Curly braces { } define the method body, which contains the code that will be executed when the method is called.

Basic Examples of Instance Method in Java

Let’s take some simple example programs based on instance method in Java.

Example 1:

class MyClass {
   int number = 10;

// Declare an instance method.
   void display() {
     System.out.println("Number: " + number);
   }
}
public class Main {
public static void main(String[] args) {
// Create an object of class and call instance method using reference variables.
   MyClass obj = new MyClass();
     obj.display();// Calling the instance method.
   }
}
Output:
      Number: 10

In this example, we have created a class named MyClass in which we have defined an instance variable and assigned a value 10. Then, we have declared an instance method to display the value of variable on the console. After that, we have created another class named Main in which we have declared the main method.

Inside the main method, we have created an object of the class MyClass and called the instance method using object reference variable. A method in Java only executes when it is explicitly called by another method, typically from main() or another method in the class or program.

Example 2:

public class Student {
    String name;
    int age;

 // Instance method
    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}
public class Main {
public static void main(String[] args) {
   Student s1 = new Student();
   s1.name = "Alice";
   s1.age = 20;
   s1.displayInfo();
 }
}
Output:
      Name: Alice
      Age: 20

Calling One Instance Method from Another

Instance methods can call other instance methods directly or using this.

Example 3:

public class Calculator {
    int add(int a, int b) {
        return a + b;
    }
    void displaySum() {
        int result = add(5, 3); // calling add() method.
        System.out.println("Sum: " + result);
    }
}
public class Main {
public static void main(String[] args) {
// Creating an instance of class.
   Calculator c = new Calculator();
   c.displaySum();
  } 
}
Output:
      Sum: 8

Parameterized Instance Method in Java

A parameterized instance method in Java is a non-static method that takes input values (parameters) when it is called. These parameters allow the method to operate using external data passed at runtime.

Example 4:

class Greeter {
 // Declare parameterized instance method.
    void sayHello(String name) {
        System.out.println("Hello, " + name + "!");
    }
}

public class Main {
  public static void main(String[] args) {
     Greeter g = new Greeter();
  // Calling instance methods with passing argument values.
     g.sayHello("Alice"); 
     g.sayHello("Bob");
  }
}
Output:
      Hello, Alice!
      Hello, Bob!

Learning Java instance methods becomes easier when you supplement your study with interactive resources. For regular updates and structured learning, you can join our WhatsApp Java learning channel.

Example 5: Java program to calculate the sum of two numbers.

class Calculator {
 // Instance method with two parameters.
    int add(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        int result = calc.add(10, 20);  // Passing two integers
        System.out.println("Sum: " + result);
    }
}
Output:
      Sum: 30

Example 6: Java program to calculate the area of a rectangle.

class Rectangle {
 // Method to calculate and print area.
    void calculateArea(double length, double width) {
        double area = length * width;
        System.out.println("Area: " + area);
    }
}

public class Main {
    public static void main(String[] args) {
        Rectangle rect = new Rectangle();
        rect.calculateArea(5.0, 3.2);
    }
}
Output:
      Area: 16.0

In the above example program, we have passed argument values to the instance methods. You can pass primitive types, such as int, double or objects, such as String, ArrayList, custom classes. The order and types of arguments passed must match the method signature.

Returning Values from Instance Method

In Java, an instance method can return a value to the caller using the return statement. The type of value it returns must match the declared return type of the method.

Example 7: Java program to return the sum of two numbers.

class Calculator {
 // Instance method with return value
    int add(int a, int b) {
        return a + b;  // returning an int value
    }
}

public class Main {
public static void main(String[] args) {
    Calculator calc = new Calculator();
    int result = calc.add(5, 10);  // storing returned value.
    System.out.println("Sum: " + result);
  }
}
Output:
      Sum: 15

Example 8: Returning an Object

class Person {
   String name;
   Person(String name) {
      this.name = name;
   }
   Person getPerson() {
      return this;
   }
}
public class Main {
public static void main(String[] args) {
     Person p = new Person("John");
     Person returnedPerson = p.getPerson();
     System.out.println("Returned name: " + returnedPerson.name);
  }
}
Output:
      Returned name: John

Common Errors and Misconceptions

1. Calling Instance Method Without Object ❌

public class Test {
    void greet() {
        System.out.println("Hello");
    }

    public static void main(String[] args) {
        greet(); // ❌ Error: Cannot make a static reference to a non-static method
    }
}

✅ Fix:

Test obj = new Test();
obj.greet();

2. Accessing Instance Variables in Static Methods ❌

class Demo {
    int x = 10;
     public static void show() {
        System.out.println(x); // ❌ Error
   }
}

✅ Fix:

Demo d = new Demo();
System.out.println(d.x);

3. Misunderstanding this Keyword ❌

In Java, this keyword refers to the current object. Misusing it can lead to confusion:

class Sample {
   int x;
   void setX(int x) {
        x = x; // ❌ Doesn't assign to instance variable
   }
}

✅ Fix:

void setX(int x) {
    this.x = x;
}

Instance Method vs Static Method

FeatureInstance MethodStatic Method
Belongs toObjectClass
Requires object?YesNo
Can access static members?YesYes
Can access instance members?YesNo (unless object created)
Invocationobj.method()Class.method()

Quiz Questions on Instance Method in Java

Q1. What will this print?

class Demo {
    int x = 5;

    void increase() {
        x += 5;
    }

    void print() {
        System.out.println(x);
    }

    public static void main(String[] args) {
        Demo d1 = new Demo();
        Demo d2 = new Demo();

        d1.increase();
        d2.print();
    }
}

Answer: 5

Q2. Which of the following is true about instance methods?

a) They can be called without creating an object.
b) They are declared using the static keyword.
c) They belong to the class rather than any instance.
d) They require an object to be called.

Answer: d) They require an object to be called.

Please Share Your Love.

Leave a Reply

Your email address will not be published. Required fields are marked *