Java Method Examples

A method in Java exhibits certain behavior/operation of a class. According to OOP principle, the fields of a class should be accessed by its methods only to ensure data hiding.

As already specified, a Java method can be of two types— instance method (i.e. non-static method) and class method (i.e. static method). Instance methods are the members of a class object; while, the class methods are the members of the class only.

We will present here some of the examples of Java methods.

 

Example 1

The following example demonstrates useful concepts such as pass-by-value and pass-by-reference with respect to Java Methods.

Testing.java

public class Testing {
int x = 15, y = 25;

public static void main(String[] args) {
int a = 10, b = 20;

// Pass By Value
System.out.println("Before pass by value: a = " + a + "; b = " + b);
passByValue(a, b);
System.out.println("After pass by value: a = " + a + "; b = " + b);

// Pass By Reference
Testing obj = new Testing();
System.out.println("\nBefore pass by reference: ob.x = " + obj.x
+ "; ob.y = " + obj.y);
passByReference(obj);
System.out.println("After pass by reference: ob.x = " + obj.x
+ "; ob.y = " + obj.y);
}

static void passByValue(int x, int y) { //class method
int t;
t = x;
x = y;
y = t;
}

static void passByReference(Testing ob) { //class method
int t;
t = ob.x;
ob.x = ob.y;
ob.y = t;
}
}

Output:

Before pass by value: a = 10; b = 20
After pass by value: a = 10; b = 20

Before pass by reference: ob.x = 15; ob.y = 25
After pass by reference: ob.x = 25; ob.y = 15

Explanation: It is evident from the above coding example that by using pass-by-value we are not being able to swap the values of the two variables a and b permanently. But, using pass-by-reference concept we will be able to do so, as it passes a object reference as the parameter of the method. Another point is that both these methods passByValue() and passByReference(), being static, can be called directly from the main() method without creating any object of the Testing class.

 

Example 2

The following example shows how a method in Java can return an object of a class.

Test.java

public class Test {
int a;

//constructor
public Test(int a) {
this.a = a;
}

//method returning object
Test retObj(Test ob) {
Test t = new Test(a+10);
return t;
}

public static void main(String[] args) {
Test t1 = new Test(10);
System.out.println("t1.a = " + t1.a);
Test t2 = t1.retObj(t1);
System.out.println("t2.a = " + t2.a);
Test t3 = t2.retObj(t2);
System.out.println("t3.a = " + t3.a);
}

}

Output:

t1.a = 10
t2.a = 20
t3.a = 30

Explanation: In the example shown above the instance method named retObj() returns an object of the class Test. Here, the constructor is used to initialize the value of the instance field for each of the objects of Test class.