An instance method is a method that belongs to an object created from a class. To use an instance method, you must have an object reference.
. to call the method.Syntax:
objectName.methodName(arguments);
| Instance Methods | Static Methods |
|---|---|
| Called on an object | Called on the class |
| Access instance variables | Cannot access instance variables directly |
Use obj.method() |
Use ClassName.method() |
Static method example:
Math.sqrt(16);
Instance method example:
str.length();
String str = "Hello"; int len = str.length();
Other common String instance methods:
str.toUpperCase(); // "HELLO"
str.substring(1, 4); // "ell"
str.indexOf("l"); // 2
Example class:
public class Dog {
private int age;
public void setAge(int a) {
age = a;
}
public int getAge() {
return age;
}
}
Using the class:
Dog d = new Dog(); d.setAge(5); int a = d.getAge();
Dot notation is used for all instance method calls:
objectReference.methodName(parameters);
Examples:
student.getName(); car.startEngine(); scanner.nextInt();
int len = str.length(); String upper = str.toUpperCase();
Dog d = new Dog(); d.setAge(3);
String result = str.toUpperCase().substring(1, 3);
This calls multiple instance methods in a row.
String s = null; s.length(); // ERROR: NullPointerException
Scanner sc; int x = sc.nextInt(); // ERROR: sc not initialized
Math.random(); // correct myRandom.random(); // incorrect unless myRandom is an object with that method