🎓 BookMCQ
← Back to 14. Protection

📝 Language based Protection in Java (21 MCQs)

Java's Runtime Model for Language Based Protection

Java supports language-based protection through strong type checking, access control, bytecode verification, and managed memory. Java source code is compiled into bytecode that runs within a Java Virtual Machine. The language and runtime restrict many unsafe operations, while class visibility and controlled object references help separate implementation details from permitted interfaces.

Why Java Uses Verification and Managed Execution

Java was designed to support portable execution and reduce risks associated with direct memory manipulation. Programs from different sources may execute within the same runtime environment, so malformed bytecode and unsafe type operations must be controlled. Verification and runtime checks help enforce structural and type-safety rules before or during execution.

Bytecode Verification and Access Modifiers

The JVM verifies class files before execution, checking properties such as valid instruction structure, operand types, and safe use of the operand stack. Java access modifiers such as private, protected, and public control member visibility according to language rules. Runtime checks also handle conditions such as array bounds and reference casts.

Example of Java Array and Field Protection

Suppose an array has five elements, so valid indexes are 0 through 4. Accessing index 5 triggers an ArrayIndexOutOfBoundsException at runtime. Separately, code outside a class cannot directly access a private field through ordinary Java syntax. These controls prevent certain invalid operations while leaving application logic responsible for broader authorisation.

Managed Memory, Portability and Security Boundaries

Java's managed runtime reduces risks from arbitrary pointer arithmetic and many memory corruption errors. Bytecode verification and access controls improve safety for applications and libraries. They do not guarantee that an application is secure: vulnerable libraries, unsafe native interfaces, incorrect business logic, and runtime flaws can still create serious problems. Modern Java security relies on several layers, not a single sandbox.

Misconceptions About Java Protection Features

'The Java compiler alone enforces every runtime rule' is incorrect because the JVM performs bytecode verification and runtime checks. 'Private means inaccessible under every circumstance' overlooks reflection and privileged runtime mechanisms subject to restrictions. 'The Security Manager always provides Java sandboxing' is outdated because the Security Manager was deprecated and later permanently disabled in modern Java releases.

Exam Focus: JVM Verification and Java Access Control

Know the roles of the compiler, bytecode verifier, JVM, and access modifiers. Questions may ask when array bounds errors occur or how private, protected, and public affect visibility. Distinguish language-level protection from operating system process isolation, and avoid treating historical Java sandbox mechanisms as universal features of current Java versions.

Key Terms of Java Language Protection

  • JVM - Runtime environment for Java bytecode.
  • Bytecode verifier - Checks class-file safety properties.
  • Encapsulation - Restricts access to internal state.
  • Array bounds - Valid index range of an array.
  • Access modifier - Defines class member visibility.
5
Easy
10
Medium
6
Hard

📝 All Language based Protection in Java MCQs

Q1. Which Java feature automatically checks that an index used to access an array is within valid bounds?

A.Bounds checking ✅
B.Type erasure
C.Garbage collection
D.Autoboxing
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: The Java runtime inserts a bounds‑checking operation for every array access. If the index is outside the range 0 ≤ i < array.length, the JVM throws an ArrayIndexOutOfBoundsException. This automatic check prevents accidental memory corruption. Options B, C, and D refer to unrelated language mechanisms: type erasure occurs during compilation, garbage collection reclaims memory, and autoboxing converts primitives to wrapper objects. The bounds‑checking feature directly protects array data from invalid indices.

Q2. Which keyword makes a class non‑extendable, helping to protect its implementation from subclass alteration?

A.static
B.final ✅
C.abstract
D.synchronized
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: The keyword final marks a class as closed for inheritance, so no other class can extend it. This restriction preserves the class’s behavior and prevents malicious or accidental overrides. The other options serve different purposes: static applies to members, abstract defines incomplete classes, and synchronized controls thread access. By using final, developers create a strong protection boundary around critical classes, ensuring their code cannot be altered through subclassing.

Q3. Why does Java’s SecurityManager examine the call stack before granting a permission request?

A.To identify the class that originated the request ✅
B.To improve performance
C.To enforce type safety
D.To manage memory allocation
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: When a permission is requested, the SecurityManager walks the call stack to find the class that initiated the request. This stack inspection determines whether that class (or any caller) has the necessary permission, allowing fine‑grained control based on code provenance. The other choices are unrelated: performance is not the primary goal, type safety is handled by the compiler, and memory allocation is managed by the JVM, not by the SecurityManager.

Q4. An applet wants to read the system property \user.home\. Which permission must be granted in the policy file?

A.java.io.FilePermission
B.java.util.PropertyPermission ✅
C.java.net.SocketPermission
D.java.lang.RuntimePermission
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: Reading a system property requires a PropertyPermission with the target name and the action \read\. The policy entry would look like java.util.PropertyPermission \user.home\ \read\. FilePermission controls file access, SocketPermission governs network sockets, and RuntimePermission covers actions such as exiting the VM. Providing the correct PropertyPermission ensures the applet can obtain the property without violating the security policy.

Q5. How does the principle of least privilege influence the design of Java security policies?

A.Grant all permissions by default
B.Grant only permissions needed for each code source ✅
C.Ignore permissions
D.Allow users to override policies at runtime
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: Least privilege means each piece of code receives only the rights it truly needs, reducing the impact of bugs or attacks. In Java, this translates to writing policy files that specify minimal permissions for each code source (e.g., a signed JAR). Granting all permissions defeats the purpose, ignoring permissions makes no sense, and runtime overrides would undermine the static policy model, weakening security.

Q6. You have a custom class loader that loads untrusted classes. To prevent these classes from opening network sockets, which permission should be omitted from the policy granted to the loader?

A.java.net.SocketPermission \*\ ✅
B.java.io.FilePermission \*\
C.java.lang.RuntimePermission \exitVM\
D.java.security.AllPermission
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: SocketPermission controls network operations. By omitting or denying this permission, untrusted classes cannot create sockets, protecting the host from unauthorized network communication. FilePermission governs file system access, RuntimePermission \exitVM\ controls JVM termination, and AllPermission would grant every possible right, which is the opposite of what is needed for a secure sandbox.

Q7. What is the main advantage of compiler‑based enforcement of access control compared with runtime checks?

A.Eliminates all security risks
B.Catches violations before code runs ✅
C.Guarantees zero overhead
D.Allows dynamic permission changes
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Compiler‑time checks can detect illegal accesses (e.g., illegal field or method visibility) before the program ever executes, providing early feedback to developers. While they do not remove all security concerns—runtime checks are still needed for dynamic features—they reduce the chance of deploying code with obvious access violations. The other options are inaccurate: compilers cannot eliminate all risks, cannot guarantee zero overhead, and cannot replace the need for dynamic permission adjustments.

Q8. An application runs with a SecurityManager that denies write access to \/etc/config\. The code attempts to open a FileOutputStream to that path. What exception is thrown?

A.NullPointerException
B.IOException
C.SecurityException ✅
D.FileNotFoundException
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: When a SecurityManager blocks a prohibited operation, it throws a SecurityException to signal that the requested permission was denied. The FileOutputStream constructor triggers a permission check for write access; because the policy denies it, the JVM raises SecurityException. IOException and FileNotFoundException relate to I/O problems, not permission violations, and NullPointerException occurs when dereferencing a null reference.

Q9. How do abstract data types (ADTs) assist in building protection mechanisms in object‑oriented languages like Java?

A.By exposing internal representation
B.By hiding implementation behind interfaces ✅
C.By preventing inheritance
D.By enforcing static typing only
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: ADTs encapsulate data behind a well‑defined interface, hiding the underlying representation. This encapsulation limits how other code can interact with the data, forming a natural protection boundary. Exposing internal details would weaken protection, inheritance is not prevented by ADTs, and static typing concerns compile‑time type safety rather than runtime protection.

Q10. A Java web application uses AccessController.doPrivileged to perform a privileged action. Which statement is true about the effect of doPrivileged?

A.It grants all permissions to the current thread
B.It bypasses the SecurityManager completely
C.It limits the permission check to the code inside the privileged block ✅
D.It disables class loader checks
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: doPrivileged executes the enclosed code with a reduced stack inspection: only the permissions of the code inside the block are considered, not those of the callers. This isolates the privileged operation while still respecting the overall security policy. It does not grant universal permissions, nor does it bypass the SecurityManager or affect class loader verification.

Q11. Why might a developer choose to place security checks in both the compiler and the runtime environment?

A.To double the execution time
B.To catch errors early and enforce policies at runtime ✅
C.To avoid using access modifiers
D.To eliminate the need for a SecurityManager
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Compiler checks catch static violations such as illegal visibility, providing fast feedback during development. Runtime checks handle dynamic behaviors like reflection, dynamic class loading, and permission changes that the compiler cannot foresee. Combining both layers offers defense in depth. The other options are false: adding checks does not intentionally double execution time, does not replace access modifiers, and does not remove the need for a SecurityManager.

Q12. In Java protection, what role does the concept of 'code source' play when evaluating permissions?

A.It determines the CPU usage
B.It identifies the origin (URL, signer) of the code ✅
C.It sets the garbage‑collection frequency
D.It controls thread priority
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: A code source describes where the class bytes came from—typically a URL and optional signer certificates. The security policy can grant permissions based on this origin, allowing trusted locations or signed code to receive more rights. CPU usage, garbage collection, and thread priority are unrelated to permission evaluation.

Q13. A developer writes a method that calls System.exit(0). The application runs under a SecurityManager that denies exitVM permission. What will happen when the method is invoked?

A.The JVM will terminate normally
B.The call will be ignored
C.A SecurityException will be thrown ✅
D.The method will return a status code
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: When exitVM permission is missing, the SecurityManager throws a SecurityException before the JVM terminates. This prevents the program from exiting unexpectedly. The call is not silently ignored, nor does it return a status code; the exception signals the security violation. The JVM only terminates if the required permission is granted.

Q14. How does Java’s use of 'AccessController' differ from traditional operating‑system access control lists?

A.It operates at the bytecode level ✅
B.It uses hardware interrupts
C.It replaces file permissions
D.It manages network routing
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: AccessController evaluates permissions based on the protection domains associated with loaded classes, which are determined from bytecode signatures and origins. This fine‑grained, language‑specific approach contrasts with OS ACLs that control access to resources like files or sockets at the system level. The other options describe mechanisms unrelated to Java’s permission checking.

Q15. An application needs to perform a computation that requires reading a system property and opening a socket, but only the socket operation should be checked against the current permissions. Which Java construct should be used?

A.synchronized block
B.AccessController.doPrivileged ✅
C.volatile variable
D.Thread.sleep
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: doPrivileged executes the enclosed code with a reduced stack inspection, allowing the property read (which may be permitted) while the socket creation is still subject to the prevailing permission checks. The other constructs manage concurrency or timing and do not affect permission evaluation.

Q16. A Java program loads a plugin JAR signed by a different certificate than the main application. The plugin tries to invoke a private method of a class in the main application. Assuming both are loaded by separate class loaders, which statement is correct?

A.The call succeeds because signatures match
B.The call fails due to access control checks on the declaring class ✅
C.The call succeeds because private methods are always accessible via reflection
D.The call fails only if the SecurityManager is disabled
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Private methods are only accessible within the defining class. Even with reflection, the caller must have appropriate access rights, and separate class loaders create distinct protection domains. Because the plugin’s code does not belong to the same domain, the access check fails, resulting in an IllegalAccessException. The other choices misinterpret Java’s access rules or the effect of the SecurityManager.

Q17. Why does language‑based protection in Java rely on both compile‑time type checking and runtime security checks rather than solely on one of them?

A.Compile‑time checks can enforce all possible security policies
B.Runtime checks are unnecessary if the compiler is strict
C.Certain dynamic behaviors (reflection, dynamic class loading) cannot be fully verified at compile time ✅
D.Java does not support compile‑time checks
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: Java’s static type system can verify many safety properties, but features such as reflection, dynamic class loading, and permission changes occur only at runtime. These dynamic actions can bypass compile‑time guarantees, so runtime security checks are essential to enforce policies on code that cannot be fully analyzed ahead of time. The other statements are incorrect regarding the capabilities of compile‑time or runtime checks.

Q18. A server application runs with a SecurityManager that grants the permission: java.io.FilePermission \/var/log/app.log\ \write\. The code attempts to rename \/var/log/app.log\ to \/var/log/app_old.log\. Which permission is required for the rename operation to succeed?

A.read
B.write,delete ✅
C.execute
D.AllPermission
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Renaming a file is treated as a combination of delete (removing the original name) and write (creating the new name). Therefore the permission string must include both \write\ and \delete\ for the target directory. A simple \read\ or \execute\ does not cover the operation, and AllPermission would be excessive.

Q19. How does the concept of 'object capability' relate to Java’s protection model?

A.Capabilities are stored in static variables
B.An object’s reference serves as a capability that grants the holder the authority to invoke its methods ✅
C.Capabilities replace the need for garbage collection
D.Java does not implement capabilities
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: In capability‑based security, possessing a reference to an object is itself a grant of authority to use that object’s methods. Java naturally follows this model: if code holds a reference, it can call the object's public methods, subject to any additional security checks. This differs from static variables or other mechanisms, and Java does not replace garbage collection with capabilities.

Q20. A Java program uses a custom SecurityManager that overrides checkPermission to log each permission request but then calls super.checkPermission(p). If code calls AccessController.checkPermission with a permission that is not granted, what will happen?

A.The permission will be silently ignored
B.The program will log the request and then throw a SecurityException ✅
C.The program will continue without any exception
D.The custom manager will grant the permission automatically
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: The overridden checkPermission logs the request and then delegates to the parent implementation. If the permission is not granted, the parent throws a SecurityException, which propagates back to the caller. The logging side effect does not alter the decision; the denial still results in an exception. The other options incorrectly suggest that logging changes the outcome or that the permission is ignored.

Q21. What is the main reason that Java’s protection mechanisms must be able to evolve at runtime, such as by installing a new SecurityManager or changing policy files?

A.To adapt to changing security requirements and new code modules ✅
B.To increase CPU speed
C.To reduce memory usage
D.To enable static linking of native libraries
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: Security requirements evolve as applications load new components, as vulnerabilities are discovered, or as organizational policies change. Java allows dynamic installation of a new SecurityManager or reloading of policy files so that the system can respond to these changes without restarting. The other options describe performance or linking concerns unrelated to security adaptability.

🔗 Related Topics (MCQs)