Java Encapsulation Quiz: 25 Practice Questions

Welcome to the Java Encapsulation Quiz! In this quiz, we have compiled 25 top multiple-choice questions (MCQs) covering Java Encapsulation, data hiding, access modifiers, and modern Java Records.

Whether you are preparing for technical interviews, studying for Java certifications, or brushing up on OOP design principles, this assessment tests both conceptual understanding and real-world code analysis.

Put your skills to the test, analyze tricky edge cases, and discover where your Java OOP expertise stands!

Which of the following approaches best demonstrates the core principle of encapsulation in Java?
A. Declaring class fields as public so any external class can directly read and modify them.
B. Declaring class fields as private and providing public getter and setter methods to control access.
C. Making all methods static and removing instance variables entirely from the class.
D. Extending multiple classes simultaneously to combine their internal variables into a single subclass.
Declaring class fields as private and providing public getter and setter methods to control access.

Explanation:

  • A: Incorrect. Declaring fields as public breaks encapsulation because external classes can directly mutate the object’s internal state without validation or boundary checks.
  • B: Correct. Encapsulation binds data and code into a single unit. Restricting direct access using private variables while offering controlled access via public getters and setters preserves data integrity.
  • C: Incorrect. Marking methods static associates them with the class rather than individual instances, which is unrelated to encapsulating instance state.
  • D: Incorrect. Java does not support multiple class inheritance (extends A, B), and inheritance models an “is-a” relationship rather than state hiding.
Consider the following Java class:
public class Employee {
    private final int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
}

How does this implementation apply encapsulation to the id field?

A. The id field is write-only because it can be initialized inside the constructor.
B. The id field is read-only because it is declared private and provides a getter method without a setter method.
C. The id field violates encapsulation principles because it uses the final keyword.
D. The id field can be modified directly by any class located in the same package.
The id field is read-only because it is declared private and provides a getter method without a setter method.
Explanation:
Encapsulation allows selective access control. By declaring a field private and providing only a public getter (and no setter), the field becomes effectively read-only to external code.
Consider the following Java class definition:
public class BankAccount {
    private double balance;
    public BankAccount(double initialBalance) {
        if (initialBalance >= 0) {
            this.balance = initialBalance;
        } else {
            this.balance = 0.0;
        }
    }
    public double getBalance() {
        return this.balance;
    }

    // Line to complete
}

Which of the following method implementations properly provides a setter for balance while preserving encapsulation and preventing invalid account states?

A.

public void setBalance(double amount) {
    this.balance = amount;
}

B.

public void deposit(double amount) {
    if (amount > 0) {
        this.balance += amount;
    } else {
        throw new IllegalArgumentException("Deposit amount must be positive.");
    }
}

C.

private void setBalance(double balance) {
     this.balance = balance;
}

D.

private void setBalance(double balance) {
    this.balance = balance;
}
public void deposit(double amount) {
    if (amount > 0) {
        this.balance += amount;
    } else {
        throw new IllegalArgumentException("Deposit amount must be positive.");
    }
}
Explanation:
Encapsulation is not just about writing standard getters and setters; it is about protecting an object’s internal invariant state through controlled, validated mutator methods with clear domain logic (such as deposit).
What happens when you try to compile and run the following Java code?
class Student {
    private int age;
    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }
    public int getAge() {
        return this.age;
    }
}
public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.age = 20;
        System.out.println(s.getAge());
    }
}
A. The program compiles and prints 20.
B. The program compiles and prints 0.
C. A compilation error occurs at s.age = 20 because age has private access in Student.
D. A runtime exception (NullPointerException) is thrown when accessing s.age.
A compilation error occurs at s.age = 20 because age has private access in Student.
Explanation:
In Java, when a variable is marked as private, it is hidden from other classes. The Main class cannot see or change s.age directly. The Java compiler stops this and throws an error: age has private access in Student. To change the age correctly, you must use the setter method: s.setAge(20).
What will be the output of the following Java program?
class Rectangle {
    private int length;
    public void setLength(int length) {
        length = length;
    }
    public int getLength() {
        return length;
    }
}
public class Main {
    public static void main(String[] args) {
        Rectangle rect = new Rectangle();
        rect.setLength(15);
        System.out.println(rect.getLength());
    }
}
A. 15
B. 0
C. Compilation error at length = length;
D. Runtime error (IllegalArgumentException)
0

Explanation:

  • A: Incorrect. The value 15 was not saved into the object’s field because the method parameter shadowed (hid) the instance variable.
  • B: Correct. In the setLength method, the parameter name length is the same as the class variable length. Writing length = length; simply assigns the parameter value to itself and does not update the object’s variable. Since the object’s length was never changed, it keeps its default int value, which is 0. To fix this and store 15, you should write this.length = length;.
  • C: Incorrect. length = length; is valid Java syntax, so the code compiles without any compiler errors.
  • D: Incorrect. No exceptions are thrown during execution.
According to Java Beans and standard Java naming conventions, what is the recommended way to name a getter method for an encapsulated boolean field named active?
A. getActive()
B. isActive()
C. checkActive()
D. hasActive()
isActive()

Explanation:

  • A: Incorrect. While getActive() works and compiles in Java, standard conventions specifically recommend using the is prefix for boolean properties instead of get.
  • B: Correct. In standard Java naming rules (JavaBeans), getter methods for boolean variables should start with is (like isActive() or isEligible()). This makes the code sound like a natural yes/no question when reading it, making your code easier to understand and compatible with Java frameworks.
  • C: Incorrect. checkActive() is not a standard getter naming pattern in Java.
  • D: Incorrect. hasActive() does not follow the standard getter naming convention for a primitive boolean variable.
How does encapsulation help protect an object from receiving invalid data?
A. By making all variables public so the compiler can validate them automatically.
B. By keeping variables private and placing validation checks (like if-conditions) inside setter methods.
C. By converting all variables into constants using the final keyword.
D. By forcing all methods to return void.
By keeping variables private and placing validation checks (like if-conditions) inside setter methods.

Explanation:

  • A: Incorrect. Public variables can be changed by anyone without any check or restriction.
  • B: Correct. When fields are private, outside code must use setter methods to change them. Inside these setter methods, you can write simple if statements (e.g., checking if age > 0) to reject bad or invalid input before saving it.
  • C: Incorrect. The final keyword makes a variable unchangeable, but it does not provide custom validation logic for updates.
  • D: Incorrect. Return types do not control whether data is validated or protected.
Which of the following is also known as a synonym or closely related term for encapsulation in object-oriented programming?
A. Data Hiding
B. Code Duplication
C. Method Overloading
D. Dynamic Dispatch
Data Hiding

Explanation:

  • A: Correct. Encapsulation is often referred to as “data hiding” because it hides the internal details and variables of a class from outside interference and misuse.
  • B: Incorrect. Code duplication means writing the same code multiple times, which is a bad programming practice.
  • C: Incorrect. Method overloading means having multiple methods with the same name but different parameters (polymorphism).
  • D: Incorrect. Dynamic dispatch is related to runtime polymorphism and method overriding, not data hiding.
What will happen if you create a class with private variables and provide only getter methods, but no setter methods?
A. The class will not compile because every getter requires a setter.
B. The fields of the class become effectively read-only to outside classes.
C. Outside classes can still modify the private variables directly.
D. The Java Virtual Machine (JVM) will automatically generate default setters at runtime.
The fields of the class become effectively read-only to outside classes.

Explanation:

  • A: Incorrect. Java does not force you to write setters. Classes without setters compile completely fine.
  • B: Correct. When you hide a variable with private and provide only a getter method, outside code can only view (read) the value. Because there is no setter method, no one from the outside can modify (write) the value after the object is created.
  • C: Incorrect. Outside classes cannot access private fields directly.
  • D: Incorrect. Java never automatically adds setter methods for you.
What will happen if you create a class with private variables and provide only setter methods, but no getter methods?
A. The fields become write-only to outside classes.
B. The class becomes immutable.
C. A compilation error occurs because getters are mandatory.
D. The private variables can be read without using getters.
The fields become write-only to outside classes.

Explanation:

  • A: Correct. If you provide only setter methods, external classes can supply or update the data, but they have no way to retrieve or inspect the stored value directly. This creates a write-only property.
  • B: Incorrect. Immutable means an object cannot be changed after creation. Adding setters makes it mutable (modifiable).
  • C: Incorrect. Getters are not mandatory in Java syntax.
  • D: Incorrect. Private variables can never be directly read by external classes.
What is a major maintenance benefit of using encapsulation when building large software applications?
A. It guarantees that the code will execute twice as fast.
B. You can change internal class implementation details without breaking external code that uses the class.
C. It completely eliminates the need for unit testing.
D. It automatically manages database connections.
You can change internal class implementation details without breaking external code that uses the class.

Explanation:

  • A: Incorrect. Encapsulation is a design principle for clean architecture; it does not automatically double execution speed.
  • B: Correct. Since outside code interacts only through public methods (like getters and setters), you can freely change the internal variable names, data types, or algorithms inside the class without affecting or breaking any outside code.
  • C: Incorrect. Encapsulated code still requires thorough testing.
  • D: Incorrect. Encapsulation has nothing to do with automatic database management.

Consider this code:

public class User {
    private String password;

    public void setPassword(String password) {
        if (password != null && password.length() >= 8) {
            this.password = password;
        }
    }
}

Why is keeping the password field private better than making it public?

A. It makes the password field accessible only to subclasses.
B. It forces passwords to always be set through validation rules (at least 8 characters), preventing short or invalid passwords.
C. It automatically encrypts the password in memory.
D. It allows other classes to bypass the if-condition when needed.
It forces passwords to always be set through validation rules (at least 8 characters), preventing short or invalid passwords.

Explanation:

  • A: Incorrect. Private fields are not directly accessible by subclasses either.
  • B: Correct. Making password private means outside code cannot directly assign a weak password like user.password = "123". It is forced to go through setPassword(), which enforces the minimum length rule.
  • C: Incorrect. Making a variable private does not automatically encrypt it.
  • D: Incorrect. The private modifier prevents outside classes from bypassing the method and its checks.
What access modifier gives the highest level of data hiding and restriction in Java?
A. public
B. protected
C. default (package-private)
D. private
private

Explanation:

  • A: Incorrect. public is the most open modifier, accessible from any class in any package.
  • B: Incorrect. protected allows access to classes in the same package and subclasses in other packages.
  • C: Incorrect. Default access allows any class in the same package to access the member.
  • D: Correct. The private modifier is the strictest access level in Java. A private member can only be accessed within the exact same class where it is declared, giving you total control over the data.
What is a fully encapsulated class in Java?
A. A class that has only static methods and no constructor.
B. A class where all data members (variables) are private and accessed via public getter and setter methods.
C. A class that implements every interface in the java.lang package.
D. A class where all variables and methods are declared public.
A class where all data members (variables) are private and accessed via public getter and setter methods.

Explanation:

  • A: Incorrect. A class with only static methods is typically a utility class (like Math), not an example of full encapsulation.
  • B: Correct. In Java, a class is considered “tightly” or “fully” encapsulated when every single instance variable is marked private, and interaction with those fields is handled exclusively through standard public getter and setter methods.
  • C: Incorrect. Implementing interfaces is unrelated to field-level encapsulation.
  • D: Incorrect. Declaring variables public directly violates encapsulation.

Consider the following class:

public class ScoreTracker {
    private int score;

    public void addPoints(int points) {
        if (points > 0) {
            this.score += points;
        }
    }

    public int getScore() {
        return this.score;
    }
}

Why is providing an addPoints method better for encapsulation than a standard setScore(int score) method?

A. Because addPoints prevents external code from arbitrarily resetting or overwriting the entire score to any random value.
B. Because Java syntax forbids setters from taking integer arguments.
C. Because addPoints runs faster than setScore at the CPU level.
D. Because addPoints converts the score variable into a static field.
Because addPoints prevents external code from arbitrarily resetting or overwriting the entire score to any random value.

Explanation:

  • A: Correct. Good encapsulation exposes meaningful actions rather than raw variables. An addPoints() method ensures that points can only increase naturally according to game rules, rather than allowing any outside code to overwrite the score directly.
  • B: Incorrect. Setters can take integer parameters with no issue.
  • C: Incorrect. There is no significant performance difference between the two methods.
  • D: Incorrect. The method does not alter the variable’s static or instance nature.
What is the default access level in Java if you do not specify an access modifier (such as public, private, or protected) for a variable?
A. private
B. protected
C. package-private (default)
D. public
package-private (default)

Explanation:

  • A: Incorrect. You must explicitly write the private keyword to make a member private.
  • B: Incorrect. You must explicitly write protected.
  • C: Correct. When you write no modifier (e.g., int score;), Java assigns default access (package-private). This allows any other class in the exact same package/folder to see and modify the field, which can unintentionally bypass encapsulation if not planned.
  • D: Incorrect. public must be explicitly declared for class fields.
How does encapsulation improve software reusability and testing?
A. It lets you test and debug a class as a self-contained, independent unit without worrying about external side-effects.
B. It merges all project files into a single binary file.
C. It turns all classes into global singleton objects.
D. It removes the need to declare constructors.
It lets you test and debug a class as a self-contained, independent unit without worrying about external side-effects.

Explanation:

  • A: Correct. Because an encapsulated class manages its own state and validates all inputs internally, you can easily write unit tests for it and reuse it in other applications with confidence that its internal state will stay valid.
  • B: Incorrect. Encapsulation is a source-code design concept, not a compilation or packaging tool.
  • C: Incorrect. Encapsulation does not convert objects into singletons.
  • D: Incorrect. Constructors are still used to initialize encapsulated objects properly.
Which keyword in Java is used inside an instance method or constructor to avoid name collisions between a parameter and an encapsulated instance variable?
A. super
B. this
C. static
D. final
this

Explanation:

  • A: Incorrect. super refers to members of the parent (super) class.
  • B: Correct. The this keyword refers to the current object instance. When a method parameter has the exact same name as an instance variable (e.g., int age), writing this.age = age; clearly tells Java to assign the parameter value to the object’s instance variable.
  • C: Incorrect. static denotes class-level variables or methods.
  • D: Incorrect. final marks a variable or method as unchangeable/un-overridable.

Look at the following code snippet:

public class Temperature {
    private double celsius;

    public void setCelsius(double celsius) {
        if (celsius >= -273.15) {
            this.celsius = celsius;
        } else {
            System.out.println("Invalid temperature: Below Absolute Zero!");
        }
    }

    public double getFahrenheit() {
        return (this.celsius * 9 / 5) + 32;
    }
}

What concept does the getFahrenheit() method demonstrate?

A. Storing redundant variables in memory.
B. Providing a computed property without exposing or creating extra internal state fields.
C. Violating encapsulation by returning an unformatted double.
D. Polymorphic method overriding.
Providing a computed property without exposing or creating extra internal state fields.

Explanation:

  • A: Incorrect. Notice there is no separate fahrenheit variable stored, so no extra memory is wasted.
  • B: Correct. Encapsulation allows you to provide useful getters that compute values on the fly. The caller gets Fahrenheit seamlessly, while the class keeps only a single source of truth (celsius) internally.
  • C: Incorrect. Returning a computed value does not violate encapsulation.
  • D: Incorrect. There is no inheritance or method overriding happening here.
What is a potential risk to encapsulation when a getter method returns a direct reference to a mutable object (such as an array or a List)?
A. It causes an immediate compilation failure.
B. External code can modify the internal contents of the array/List without going through the class methods.
C. The garbage collector will immediately delete the object.
D. It automatically marks the array as private static.
External code can modify the internal contents of the array/List without going through the class methods.

Explanation:

  • A: Incorrect. Returning an array or list reference compiles without any warnings or errors.
  • B: Correct. If you return a direct reference to a mutable object (like a list or array), external code can add or remove items from it directly. To protect encapsulation, you should return a defensive copy or an unmodifiable view (e.g., Collections.unmodifiableList(...)).
  • C: Incorrect. The garbage collector does not delete referenced objects.
  • D: Incorrect. Java will not change modifiers automatically.
Which of the following classes is properly immutable and fully encapsulated?
A. A class with public variables and no methods.
B. A class with private final fields, values set only in the constructor, and only getter methods.
C. A class where all methods and variables are declared static.
D. A class with private variables and public setters for every variable.
A class with private final fields, values set only in the constructor, and only getter methods.

Explanation:

  • A: Incorrect. Public variables provide zero encapsulation and can be changed anytime.
  • B: Correct. An immutable class cannot be modified after creation. By setting private final fields in the constructor and providing only getter methods, the object’s state is completely protected and cannot be altered by anyone.
  • C: Incorrect. Static members belong to the class, not to encapsulated instances.
  • D: Incorrect. Having setters makes the object mutable (changeable).
Why is standard encapsulation preferred over making variables public and adding comments asking other developers “Please do not modify directly”?
A. Comments are ignored by the compiler, meaning anyone can still accidentally modify or corrupt the public data.
B. Comments make the compiled .class file too large.
C. Public variables consume double the RAM of private variables.
D. Java does not allow comments next to public fields.
Comments are ignored by the compiler, meaning anyone can still accidentally modify or corrupt the public data.

Explanation:

  • A: Correct. Comments are just human text and cannot enforce rules. Encapsulation uses language-level rules (the private keyword) so the compiler itself stops anyone from modifying data incorrectly.
  • B: Incorrect. Comments are stripped out during compilation and do not increase bytecode size.
  • C: Incorrect. Access modifiers have no effect on memory size.
  • D: Incorrect. Comments can be written anywhere in Java source code.
What is the standard return type of a typical setter method in Java?
A. int
B. String
C. void
D. boolean
void

Explanation:

  • A: Incorrect. Setters typically set a value and do not return an integer.
  • B: Incorrect. Setters do not return String by convention.
  • C: Correct. By standard Java convention, a setter method’s job is simply to update the value of an internal variable. Therefore, it takes a parameter and returns void (nothing).
  • D: Incorrect. While some custom methods return a boolean indicating success, standard JavaBeans setters return void.
What is a Java Record (introduced in modern Java) in relation to encapsulation?
A. A special type of class that automatically creates a transparent, immutable data carrier with private final fields and accessor methods.
B. A tool used exclusively for recording audio and video in Java applications.
C. A keyword that makes all fields in a class public and mutable.
D. A replacement for the JVM garbage collector.
A special type of class that automatically creates a transparent, immutable data carrier with private final fields and accessor methods.

Explanation:

  • A: Correct. In modern Java, a record is a concise way to create an immutable class. Java automatically marks fields as private and final and provides clean accessor methods for you, reducing boilerplate code while maintaining strong encapsulation.
  • B: Incorrect. Records have nothing to do with multimedia recording.
  • C: Incorrect. Record fields are implicitly final and private.
  • D: Incorrect. Records are language constructs, not garbage collectors.
Which of the following best summarizes the main goal of encapsulation in Java?
A. To bundle data (fields) and the methods that operate on that data into a single unit while restricting direct outside access to internal state.
B. To allow classes to inherit methods from multiple parent classes.
C. To convert source code directly into machine code without bytecode.
D. To make all program variables accessible globally from anywhere.
To bundle data (fields) and the methods that operate on that data into a single unit while restricting direct outside access to internal state.

Explanation:

  • A: Correct. This is the definition of encapsulation: grouping related data and methods together inside a class (“capsule”) and using access modifiers to protect the data from unauthorized direct modification.
  • B: Incorrect. This describes multiple inheritance, which Java does not support for classes.
  • C: Incorrect. Bytecode generation is the job of the Java compiler (javac).
  • D: Incorrect. Global public access is the opposite of encapsulation.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.