Methods in Java: Essential OCA Java 8 Tips & Tricks

Table of Contents

Methods in JAVA are blocks of code designed to perform a specific task. In this article, we explore the strategies frequently employed by exam creators, focusing particularly on methods, access modifiers, specifiers, and tricks for passing data to methods.

Method Declaration

Methods are the building blocks of any Java program. They allow code reuse and modularization, making programs easier to read, maintain, and debug.

Syntax

access-modifier specifier returnType methodName(parameters) {
    // method body
    // return statement if returnType != void
}

  • access-modifier: Specifies the access level of the method (e.g., public, private). This is optional.
  • specifier: Defines additional characteristics of the method, such as static, final, or synchronized. This is also optional.
  • returnType: Indicates the data type of the value returned by the method. This is mandatory.
  • methodName: The name assigned to the method. This is mandatory.
  • parameters: A list of input parameters the method can accept. This is optional.

Example:

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

This is not all; we have a separate section for each part to ensure you have a complete understanding of this topic and you are ready for every question that may arise in this area!

Access Modifiers

Access modifiers control the visibility of a method to other classes and objects. Java provides four types of access modifiers:

  • public: The method is accessible from any other class.
  • protected: The method is accessible within the same package and subclasses.
  • default: The method is accessible only within the same package (no keyword is specified).
  • private: The method is accessible only within the class it is declared.

Exam creators use the protected access modifier a lot because it’s the trickiest one. Let’s ensure you have a complete understanding of it.

I’ve tried to collect every possible case you may find on the exam when dealing with the protected keyword. Here is what I’ve concluded:

  • protected behave as default access if we are in the same package.
  • Protected members are accessible in subclasses as inherited members.
  • Protected members are not accessible if we use an object of the superclass inside the subclass.
  • Protected members are accessible within the subclass using an object of the subclass, but only within the subclass methods. When inheriting a protected member, it behaves as if it has a private access modifier in the subclass. Using an object of the subclass in another class won’t grant access to the protected members.

let’s see some examples

Example 1: (ie, Protected members are accessible in subclasses as inherited members.)

// package 1

package com.javalaunchpad.package1;

public class SuperClass {
    
    protected void protectedMethod() {
        System.out.println("This is a protected method.");
    }
}


// package 2

package com.javalaunchpad.package2;

import com.javalaunchpad.package1.SuperClass;

public class SubClass extends SuperClass {

    public SubClass() {
        protectedMethod();
    }
    
}

// package 2
package com.javalaunchpad.package2;

public class Main {
    public static void main(String[] args) {
        SubClass subClass = new SubClass();
    }
}

Executing the main method of the Main class will print ‘This is a protected method.’ to the console.

Example 2: (ie, Protected members are not accessible if we use an object of the superclass inside the subclass.)

package com.javalaunchpad.package1;

public class SuperClass {
    
    protected void protectedMethod() {
        System.out.println("This is a protected method.");
    }
}


// package 2

package com.javalaunchpad.package2;

import com.javalaunchpad.package1.SuperClass;

public class SubClass extends SuperClass {

    public SubClass() {
        SuperClass superClass = new SuperClass();
        superClass.protectedMethod(); // compilation error
    }
    
}

// package 2
package com.javalaunchpad.package2;

public class Main {
    public static void main(String[] args) {
        SubClass subClass = new SubClass();
    }
}

Accessing the protectedMethod() method using a superclass object in package2 will cause a compilation error (we are outside of package1 even if we are inside a subclass of SuperClass).

Example 3: (ie, Protected members are accessible within the subclass using an object of the subclass, but only within the subclass methods )

package com.javalaunchpad.package1;

public class SuperClass {
    
    protected void protectedMethod() {
        System.out.println("This is a protected method.");
    }
}


// package 2

package com.javalaunchpad.package2;

import com.javalaunchpad.package1.SuperClass;

public class SubClass extends SuperClass {

    public SubClass() {

    }

    public void accessProtectedResourceUsingSubClassReference(){
        SubClass subClass = new SubClass();
        subClass.protectedMethod();
    }
}

// package 2
package com.javalaunchpad.package2;

public class Main {
    public static void main(String[] args) {
         SubClass subClass = new SubClass();
         subClass.protectedMethod();  // compilation error
         subClass.accessProtectedResourceUsingSubClassReference();
    } 
}

Accessing the protectedMethod() method using the subClass object will cause a compilation error.

Optional Specifiers

Optional specifiers modify the behavior of methods. The most common optional specifier is static, which indicates that the method belongs to the class rather than an instance of the class.

There are many more specifiers than static, such as final, abstract, and synchronized. We will not discuss them in detail here, as we have separate articles for them. Please be patient.

Example:

public class MathUtil {
    public static int multiply(int a, int b) {
        return a * b;
    }
}

// Calling a static method
int result = MathUtil.multiply(5, 3);

Static methods are mainly used for utility methods: These methods do not need an object state, so you can call them without creating an object.

one of the common tricks we can see in the exam is the following :

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee();
        System.out.println(emp.count);
         emp = null;
        System.out.println(emp.count);
    }
}

This is the trickiest question you may find in the exam. Believe it or not, this will print 0 in both cases. When accessing a static field, Java doesn’t care about the instance; internally, it just infers the type from the object and uses it to access the static field.

Passing Data

The key point to understand here is that Java uses only the pass-by-value technique to pass data into methods; it does not use pass-by-reference. This means that when you call a method, Java creates variables for the method parameters and copies the exact values of the arguments into these variables, whether they are primitives or objects. To clarify this concept further, I have written a separate article titled Does Java Support Pass-by-Reference?

Conclusion

Methods facilitate code reuse and modularity. By reading this article, you should be able to solve any questions that might arise in the OCA JAVA 8 exam related to methods and access modifiers concepts.

Leave a Reply

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

Join the Tribe