Bird
0
0

Identify the error in the following code:

medium📝 Debug Q6 of 15
Java - Packages and Access Control
Identify the error in the following code:
public class Alpha {
    public int number;
}

class Beta {
    public static void main(String[] args) {
        Alpha a = new Alpha();
        System.out.println(a.number);
    }
}
AError because number is not initialized.
BError because class Alpha is public but in the same file as Beta.
CNo error, code compiles and runs fine.
DError because Beta cannot access Alpha's public member.
Step-by-Step Solution
Solution:
  1. Step 1: Check file and class rules

    One public class (Alpha) and one package-private class (Beta) in the same file is allowed.
  2. Step 2: Analyze code execution

    number is public and defaults to 0 for int; code compiles and prints 0.
  3. Final Answer:

    No error, code compiles and runs fine. -> Option C
  4. Quick Check:

    One public + package-private classes OK [OK]
Quick Trick: Multiple top-level classes OK if at most one public [OK]
Common Mistakes:
  • Thinking no other classes allowed with public class
  • Believing uninitialized int causes compilation error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes