Bird
Raised Fist0
Javaprogramming~20 mins

Data hiding in Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
πŸŽ–οΈ
Data Hiding Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Java code demonstrating data hiding?

Consider the following Java class that uses private fields to hide data. What will be printed when the main method runs?

Java
public class Person {
    private String name = "Alice";
    private int age = 30;

    public String getName() {
        return name;
    }

    public void setName(String newName) {
        name = newName;
    }

    public static void main(String[] args) {
        Person p = new Person();
        System.out.println(p.name);
    }
}
ARuntime error
BAlice
Cnull
DCompilation error: name has private access in Person
Attempts:
2 left
πŸ’‘ Hint

Private fields can be accessed directly from main inside the same class using an instance reference.

❓ Predict Output
intermediate
2:00remaining
What is the output when accessing a private field via a public method?

Given the class below, what will be printed when the main method runs?

Java
public class BankAccount {
    private double balance = 1000.0;

    public double getBalance() {
        return balance;
    }

    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        System.out.println(account.getBalance());
    }
}
A1000.0
BCompilation error: getBalance() not found
C0.0
DRuntime error
Attempts:
2 left
πŸ’‘ Hint

Private fields can be accessed inside the class. Public methods can expose them safely.

πŸ”§ Debug
advanced
2:30remaining
Why does this code fail to update the private field?

Look at this Java class. The setAge method tries to update the private field age. Why does the age not change after calling setAge(40)?

Java
public class Employee {
    private int age = 25;

    public void setAge(int age) {
        age = age;
    }

    public int getAge() {
        return age;
    }

    public static void main(String[] args) {
        Employee e = new Employee();
        e.setAge(40);
        System.out.println(e.getAge());
    }
}
AThe parameter 'age' shadows the field 'age', so the assignment does nothing
BThe field 'age' is final and cannot be reassigned
CThe method setAge is never called
DPrivate fields cannot be changed once set
Attempts:
2 left
πŸ’‘ Hint

Check the difference between the parameter and the field names inside the method.

πŸ“ Syntax
advanced
2:00remaining
Which option correctly declares a private field with a public getter in Java?

Choose the correct code snippet that declares a private integer field count and a public method getCount that returns it.

A
private int count;
public int getCount() { return Count; }
B
int private count;
public int getCount() { return count; }
C
private int count;
public int getCount() { return count; }
D
private int count;
public int getCount() { return this.count; }
Attempts:
2 left
πŸ’‘ Hint

Remember Java syntax for access modifiers and case sensitivity.

πŸš€ Application
expert
3:00remaining
How many objects can access the private field directly in this scenario?

Given the following two classes in the same package, how many objects can directly access the private field secret of SecretBox?

public class SecretBox {
    private String secret = "hidden";
}

public class Spy {
    public void tryAccess() {
        SecretBox box = new SecretBox();
        System.out.println(box.secret);
    }
}
AZero objects can access the private field directly
BOnly objects of class Spy can access it
COnly objects of class SecretBox can access it
DAll objects in the same package can access it
Attempts:
2 left
πŸ’‘ Hint

Recall what private means in Java regarding access from other classes.

Practice

(1/5)
1. What is the main purpose of data hiding in Java?
easy
A. To keep class variables private and protect them from outside access
B. To make all variables public for easy access
C. To hide methods from the user interface
D. To encrypt data before storing it

Solution

  1. Step 1: Understand data hiding concept

    Data hiding means keeping variables private inside a class to prevent direct access from outside.
  2. Step 2: Identify the purpose

    This protects data from unwanted changes and bugs by controlling access through methods.
  3. Final Answer:

    To keep class variables private and protect them from outside access -> Option A
  4. Quick Check:

    Data hiding = keeping variables private [OK]
Hint: Data hiding means making variables private [OK]
Common Mistakes:
  • Thinking data hiding means encrypting data
  • Confusing data hiding with making variables public
  • Believing data hiding hides methods from UI
2. Which of the following is the correct way to declare a private variable in a Java class?
easy
A. int age;
B. public int age;
C. protected int age;
D. private int age;

Solution

  1. Step 1: Recall Java access modifiers

    Private variables are declared with the keyword private to restrict access.
  2. Step 2: Identify correct syntax

    Only private int age; correctly declares a private variable.
  3. Final Answer:

    private int age; -> Option D
  4. Quick Check:

    Private variable = private keyword [OK]
Hint: Use 'private' keyword to hide variables [OK]
Common Mistakes:
  • Using public or protected instead of private
  • Omitting access modifier defaults to package-private
  • Confusing private with protected
3. What will be the output of the following Java code?
class Person {
  private String name = "Alice";
  public String getName() {
    return name;
  }
}

public class Test {
  public static void main(String[] args) {
    Person p = new Person();
    System.out.println(p.getName());
  }
}
medium
A. null
B. Compilation error
C. Alice
D. Runtime error

Solution

  1. Step 1: Understand private variable access

    The variable name is private but accessed via the public getter getName().
  2. Step 2: Trace the output

    The getter returns "Alice", so System.out.println prints "Alice".
  3. Final Answer:

    Alice -> Option C
  4. Quick Check:

    Getter returns private value = Alice [OK]
Hint: Private data accessed via public getter returns value [OK]
Common Mistakes:
  • Expecting direct access to private variable
  • Thinking code causes compilation error
  • Confusing output with null or error
4. Identify the error in this code related to data hiding:
class BankAccount {
  private double balance;
  public void setBalance(double balance) {
    balance = balance;
  }
  public double getBalance() {
    return balance;
  }
}
medium
A. The setter method does not update the private variable
B. The getter method should be private
C. The balance variable should be public
D. The class should not have a setter method

Solution

  1. Step 1: Analyze setter method

    The setter uses balance = balance; which assigns the parameter to itself, not the class variable.
  2. Step 2: Identify correct assignment

    It should use this.balance = balance; to update the private variable.
  3. Final Answer:

    The setter method does not update the private variable -> Option A
  4. Quick Check:

    Setter must update class variable using 'this' [OK]
Hint: Use 'this' to assign parameter to class variable [OK]
Common Mistakes:
  • Forgetting 'this' keyword in setter
  • Making getter private by mistake
  • Changing variable access to public unnecessarily
5. You want to protect a class's sensitive data but allow controlled updates only if the new value is positive. How would you implement this using data hiding in Java?
hard
A. Make the variable public and check the value before assigning it outside the class
B. Make the variable private and write a setter that updates only if the value is positive
C. Make the variable protected and allow direct access in subclasses
D. Use a public variable and no setter method

Solution

  1. Step 1: Use private variable for data hiding

    Keep the sensitive variable private to prevent direct external access.
  2. Step 2: Implement setter with condition

    Write a setter method that updates the variable only if the new value is positive, ensuring controlled updates.
  3. Final Answer:

    Make the variable private and write a setter that updates only if the value is positive -> Option B
  4. Quick Check:

    Private variable + conditional setter = safe updates [OK]
Hint: Use private variable with conditional setter method [OK]
Common Mistakes:
  • Making variable public and trusting external checks
  • Using protected instead of private for sensitive data
  • Not validating data in setter method