CCNA Java Io Security Questions

74 of 81 questions · Page 1/2 · Java Io Security topic · Answers revealed

1
MCQeasy

A developer needs to write text to a file with UTF-8 encoding. Which class should be used?

A.BufferedWriter
B.new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)
C.FileWriter
D.PrintWriter with default constructor
AnswerB

This allows explicit UTF-8 encoding for writing text.

Why this answer

Option B is correct because it explicitly constructs an OutputStreamWriter with a FileOutputStream and StandardCharsets.UTF_8, ensuring the text is written with UTF-8 encoding. This is the standard approach when you need precise control over the character encoding, as the OutputStreamWriter acts as a bridge from byte streams to character streams using the specified charset.

Exam trap

The trap here is that candidates often assume FileWriter or BufferedWriter automatically use UTF-8, but they actually rely on the platform's default charset, which may vary across operating systems, leading to encoding bugs in production.

How to eliminate wrong answers

Option A is wrong because BufferedWriter is a character stream that wraps another Writer but does not itself specify encoding; it relies on the underlying Writer's encoding, which by default is the platform's default encoding, not necessarily UTF-8. Option C is wrong because FileWriter uses the platform's default charset (e.g., UTF-8 on some systems, but not guaranteed) and does not allow specifying a charset, making it unreliable for cross-platform UTF-8 requirements. Option D is wrong because PrintWriter with the default constructor writes to System.out and does not write to a file; even if used with a file, it would use the platform's default encoding unless explicitly wrapped with an OutputStreamWriter specifying UTF-8.

2
Multi-Selectmedium

Which TWO statements are true regarding reading files with the NIO.2 API?

Select 2 answers
A.Files.readAllLines() is memory efficient for large files.
B.Files.newBufferedReader() provides buffered character input.
C.Files.lines() with try-with-resources allows streaming of lines.
D.Files.newInputStream() wraps a FileChannel for high performance.
E.Files.readAllBytes() is the best choice for large binary files.
AnswersB, C

newBufferedReader returns a BufferedReader for efficient reading.

Why this answer

Option B is correct because `Files.newBufferedReader()` returns a `BufferedReader` that wraps a `FileReader` (or underlying `FileChannel`), providing efficient buffered character input. This method is designed for reading text files line-by-line with reduced I/O operations, making it suitable for large or stream-oriented text processing.

Exam trap

Oracle often tests the distinction between memory-hungry convenience methods (`readAllLines`, `readAllBytes`) and streaming approaches (`lines`, `newBufferedReader`), trapping candidates who assume 'readAll' methods are efficient for large files.

3
MCQhard

A financial services company runs a Java 17 application on a server with 8 GB RAM. The application reads daily transaction files in CSV format (each file is about 500 MB). It processes each line, validates it against a SQL database, and writes results to an output file. Recently, after processing about 60% of a file, the application crashes with an OutOfMemoryError: Java heap space. The heap size is set to 2 GB. The code uses Files.readAllLines() to load the entire file into a List<String>, then iterates. The team is evaluating solutions to avoid memory issues. Which approach is the best course of action?

A.Increase the JVM heap size to 4 GB.
B.Enable class data sharing to reduce memory footprint.
C.Split the file into 100 MB chunks and process each chunk sequentially.
D.Replace Files.readAllLines() with Files.lines() and process the stream line by line.
AnswerD

Streams lines lazily, fits in memory regardless of file size.

Why this answer

Option D is correct because Files.readAllLines() loads the entire 500 MB CSV file into memory as a List<String>, which causes the OutOfMemoryError when combined with other heap usage. Replacing it with Files.lines() returns a Stream<String> that reads lines lazily, processing each line one at a time without holding the entire file in memory. This directly solves the heap space issue without requiring additional hardware or manual file splitting.

Exam trap

The trap here is that candidates often choose to increase heap size (Option A) as a quick fix, missing the fundamental design flaw of loading the entire file into memory, which is a classic Java anti-pattern tested in the 1Z0-829 exam.

How to eliminate wrong answers

Option A is wrong because increasing the heap to 4 GB only postpones the problem and may not be feasible on an 8 GB server; the application could still crash with larger files or concurrent operations. Option B is wrong because class data sharing (CDS) reduces memory footprint of loaded classes, not heap usage for data buffers, so it does not address the root cause of loading a large file into memory. Option C is wrong because splitting the file into chunks still requires loading each chunk entirely into memory via readAllLines(), and the manual splitting adds complexity without fixing the fundamental issue of eager loading.

4
Multi-Selectmedium

Which THREE statements are true about Java NIO.2 and its interaction with blocking I/O? (Choose three.)

Select 3 answers
A.A Selector can be used to manage multiple non-blocking channels.
B.Files.walk() returns a Stream<Path> that lazily populates.
C.FileChannel operations are always non-blocking.
D.BufferedInputStream extends FilterInputStream.
E.Paths.get() is a factory method for obtaining a Path object.
AnswersA, B, E

A Selector can monitor multiple non-blocking channels.

Why this answer

Option A is correct because a Selector in Java NIO.2 is specifically designed to manage multiple non-blocking channels, enabling a single thread to monitor I/O readiness across many channels. This is a core feature of the NIO.2 multiplexed I/O model, where channels must be configured in non-blocking mode to be registered with a Selector.

Exam trap

The trap here is that candidates often confuse the blocking nature of FileChannel with NIO.2's non-blocking channels, or they mistakenly think BufferedInputStream is a correct answer because it is a valid I/O class, but it is not related to NIO.2 and does not fit the question's focus on NIO.2 and blocking I/O interaction.

5
MCQhard

An application must read a configuration file that is updated frequently by another process. The developer wants to avoid stale data and minimize I/O operations. Which approach is best?

A.Use java.nio.file.WatchService to monitor the file for modifications and reload when notified
B.Read the file from disk every time it is accessed using Files.newInputStream()
C.Periodically check the file's lastModified timestamp using File.lastModified() and reload if changed
D.Read the file once at startup and cache the content in memory
AnswerA

WatchService provides asynchronous notifications, reducing unnecessary reads and ensuring freshness.

Why this answer

Option A is correct because java.nio.file.WatchService provides an event-driven mechanism to monitor file system changes, such as modifications to a configuration file. This approach avoids stale data by reloading the file only when a change is detected, and it minimizes I/O operations by eliminating the need for polling or repeated reads. The WatchService uses the underlying OS file system events (e.g., inotify on Linux, ReadDirectoryChanges on Windows) for efficient notification.

Exam trap

The trap here is that candidates often choose option C (polling with lastModified) because it seems simple and avoids continuous reads, but they overlook that polling still wastes resources and may miss updates, whereas WatchService is the true event-driven solution that minimizes I/O and avoids stale data.

How to eliminate wrong answers

Option B is wrong because reading the file from disk every time it is accessed using Files.newInputStream() results in excessive I/O operations, which is inefficient and contradicts the requirement to minimize I/O. Option C is wrong because periodically checking the file's lastModified timestamp using File.lastModified() and reloading if changed still involves polling, which wastes CPU cycles and I/O if the file hasn't changed, and it may miss rapid updates if the polling interval is too long. Option D is wrong because reading the file once at startup and caching the content in memory leads to stale data, as it does not account for updates made by another process.

6
Multi-Selecteasy

Which TWO are true about the try-with-resources statement?

Select 2 answers
A.Resources declared outside the try block can be used if they are effectively final.
B.All resources must be of the same type.
C.Resources declared in try-with-resources are implicitly final.
D.Multiple resources must be separated by commas.
E.The resource must implement the Closeable interface.
AnswersA, C

Effectively final variables can be used as resources.

Why this answer

Option A is correct because the try-with-resources statement allows resources declared outside the try block to be used, provided they are effectively final (i.e., their reference does not change after initialization). This was introduced in Java 9, which enhanced try-with-resources to support effectively final variables in addition to those declared directly within the try parentheses.

Exam trap

Oracle often tests the distinction between Closeable and AutoCloseable, and the requirement that resources must be declared inside the try parentheses (pre-Java 9) or be effectively final (Java 9+), leading candidates to incorrectly think resources must always be declared inside the try block or that Closeable is the only valid interface.

7
Multi-Selectmedium

Which TWO practices improve the security of Java serialization?

Select 2 answers
A.Disable serialization by throwing NotSerializableException from writeObject().
B.Mark sensitive fields as transient to exclude them from serialization.
C.Set a random serialVersionUID to prevent malicious serialization.
D.Implement readObject() to validate and sanitize fields.
E.Use Externalizable for full control over serialization format.
AnswersB, D

transient prevents sensitive data from being serialized.

Why this answer

Option B is correct because marking sensitive fields as transient prevents them from being serialized, ensuring that confidential data (e.g., passwords, cryptographic keys) is not exposed through the serialized stream. Option D is correct because implementing readObject() allows you to validate and sanitize deserialized fields, protecting against deserialization attacks where crafted data could corrupt the object state or trigger malicious behavior.

Exam trap

The trap here is that candidates often confuse serialVersionUID as a security mechanism when it is actually a versioning control for class compatibility, not a defense against malicious serialization.

8
MCQeasy

A Java application running on a server reads configuration from a file 'config.properties' located in the same directory as the JAR. The application uses java.util.Properties.load(InputStream) to read the file. Recently, the file was modified by an unauthorized user, and the application started throwing runtime exceptions due to corrupted property values. The security team requires that the file be protected from unauthorized modifications while still being readable by the application. Which action should be taken to ensure the integrity of the configuration file?

A.Encrypt the file using AES and decrypt it in the application.
B.Set the file permissions to read-only for the application user.
C.Store the file in a ZIP archive with a checksum.
D.Digitally sign the file and verify the signature before loading properties.
AnswerD

Digital signatures provide integrity and authenticity; any modification invalidates the signature.

Why this answer

Option D is correct because digital signing provides both integrity and authenticity. By signing the file with a private key and verifying the signature with a public key before calling Properties.load(InputStream), the application can detect any unauthorized modification. This directly addresses the security requirement without relying on encryption (which protects confidentiality, not integrity) or file permissions (which can be bypassed by a privileged attacker).

Exam trap

The trap here is that candidates confuse encryption (confidentiality) with integrity, or assume file permissions are sufficient, but the exam tests understanding that only digital signing provides non-repudiation and tamper detection against unauthorized modifications.

How to eliminate wrong answers

Option A is wrong because encryption (e.g., AES) protects confidentiality, not integrity; a corrupted or tampered file would still decrypt (possibly to garbage) and cause runtime exceptions. Option B is wrong because file permissions can be overridden by a root user or an attacker with sufficient privileges, and they do not prevent the file from being modified by a different user or process. Option C is wrong because a ZIP archive with a checksum does not provide cryptographic integrity; a checksum can be recomputed after tampering, and ZIP does not inherently include a digital signature mechanism.

9
Multi-Selecthard

Which THREE statements about the SecurityManager and security policies in Java 17 are true? (Choose three.)

Select 3 answers
A.System.setProperty("java.security.policy", "policy.url") loads a new policy.
B.The SecurityManager class is deprecated in Java 17.
C.By default, Java 17 applications run with a SecurityManager installed.
D.A security policy file can contain grant entries for code sources.
E.AccessController.doPrivileged() allows code to temporarily escalate privileges.
AnswersB, D, E

Deprecated since Java 18? Actually Java 17 already marks it deprecated.

Why this answer

The SecurityManager class is deprecated for removal in Java 17 (JEP 411). This deprecation means that while the class still exists for compatibility, it is no longer recommended for use and may be removed in a future release. The core reasoning is that the SecurityManager architecture is considered legacy and difficult to maintain, so Oracle has deprecated it to encourage developers to adopt alternative security mechanisms.

Exam trap

The trap here is that candidates often confuse setting a system property with actually loading a policy, and they assume the SecurityManager is active by default in modern Java versions, when in fact it is deprecated and disabled by default since Java 17.

10
MCQeasy

Which is the best practice for securing a Java application that reads sensitive configuration files?

A.Restrict access to the file using operating system permissions.
B.Define a Java security policy file with FilePermission for the configuration file.
C.Make the file read-only at the OS level.
D.Store credentials in the source code and use encryption.
AnswerB

Enforces permissions within the JVM.

Why this answer

Option B is correct because Java's built-in security manager, when enabled, enforces a sandbox that restricts file access based on a policy file. Granting FilePermission to the specific configuration file is the standard, fine-grained approach to control read access at the JVM level, independent of the underlying OS. This ensures that even if the OS permissions are misconfigured or the application runs with elevated privileges, the Java code itself cannot read the file without explicit permission.

Exam trap

The trap here is that candidates often assume OS-level permissions (Option A) are sufficient, overlooking that the Java security manager provides an additional, JVM-enforced layer of access control that is independent of the operating system.

How to eliminate wrong answers

Option A is wrong because OS permissions are external to the JVM and can be bypassed if the application runs with the same user account that owns the file, or if the OS is compromised; they do not provide Java-level access control. Option C is wrong because making a file read-only at the OS level prevents writing but does not prevent reading, which is the primary concern for sensitive configuration files; it also does not restrict access from unauthorized Java code. Option D is wrong because storing credentials in source code is a severe security anti-pattern—it exposes secrets in version control and to anyone with code access—and encryption alone does not control who can decrypt or access the data at runtime.

11
MCQmedium

A developer needs to read a very large text file (over 1 GB) efficiently with minimal memory overhead. Which approach is most suitable?

A.Use Scanner to read tokens.
B.Use BufferedReader to read lines.
C.Use FileInputStream and read byte by byte.
D.Use FileChannel with a ByteBuffer to read in chunks.
AnswerD

FileChannel with ByteBuffer allows efficient chunked reading, minimizing memory usage.

Why this answer

FileChannel with a ByteBuffer allows reading a large file in configurable chunks, leveraging the operating system's native I/O for high throughput and minimal memory overhead. This approach avoids loading the entire file into memory and reduces context switching compared to stream-based readers.

Exam trap

The trap here is that candidates often choose BufferedReader for its simplicity, not realizing that reading lines from a multi-GB file still requires holding entire lines in memory, which can cause OutOfMemoryError or severe performance degradation.

How to eliminate wrong answers

Option A is wrong because Scanner is designed for parsing tokens with delimiters and has high memory overhead due to internal buffering and regex processing, making it inefficient for large files. Option B is wrong because BufferedReader reads lines into memory, which for a 1 GB file would require storing entire lines (potentially huge) and causes significant memory pressure. Option C is wrong because reading byte by byte with FileInputStream incurs excessive system calls and overhead, resulting in abysmal performance for large files.

12
MCQeasy

Refer to the exhibit. What is the purpose of this code?

A.Compress data.txt and write to data.enc
B.Encrypt data.txt and write to data.enc
C.Encrypt data.enc and write to data.txt
D.Decrypt data.txt and write to data.enc
AnswerB

The cipher is in encrypt mode, and data from data.txt is written to data.enc via CipherOutputStream.

Why this answer

The code uses a CipherOutputStream with a cipher initialized in ENCRYPT_MODE, reading from data.txt and writing to data.enc, thus encrypting the plaintext file and producing an encrypted output file. This is the standard pattern for file encryption in Java using the JCA (Java Cryptography Architecture).

Exam trap

Oracle often tests the distinction between encryption and compression, and the direction of the cipher mode (ENCRYPT vs DECRYPT) relative to the input/output file names, leading candidates to confuse the source and destination or the operation type.

How to eliminate wrong answers

Option A is wrong because compression is not performed; the code uses a Cipher, not a compression algorithm like GZIPOutputStream. Option C is wrong because the input is data.txt and output is data.enc, not the reverse; the cipher is in ENCRYPT_MODE, not DECRYPT_MODE. Option D is wrong because the cipher is in ENCRYPT_MODE, not DECRYPT_MODE, so it cannot decrypt; also the input/output mapping is reversed for decryption.

13
MCQmedium

A class that stores sensitive user data implements Serializable. To minimize security exposure from deserialization attacks, which modification is the best practice?

A.Declare the sensitive fields as transient.
B.Override writeObject to manually exclude the sensitive fields.
C.Implement Externalizable and override readExternal and writeExternal.
D.Remove the implements Serializable clause from the class declaration.
AnswerA

Transient fields are not serialized, preventing them from being exposed in serialized data and reducing deserialization risks.

Why this answer

Marking sensitive fields as transient prevents them from being serialized, so they are not exposed in the serialized stream. Option B (implement writeObject) can be used but does not inherently prevent serialization of fields. Option C (remove implements Serializable) may break other functionality if serialization is needed.

Option D (use Externalizable) allows custom control but still requires careful handling.

14
MCQeasy

Which class is best suited for reading integer tokens from a string containing space-separated integers?

A.InputStreamReader
B.BufferedReader
C.DataInputStream
D.Scanner
AnswerD

Scanner has nextInt() and can parse integers from a string directly.

Why this answer

Scanner is best suited because it provides built-in methods like nextInt() that can parse space-separated integer tokens directly from a string, handling whitespace delimiters automatically. It is designed for parsing formatted input, making it the ideal choice for this task.

Exam trap

The trap here is that candidates often choose BufferedReader because it is familiar for reading text, but they overlook that Scanner provides direct tokenization and parsing methods, making it the more appropriate and efficient choice for this specific task.

How to eliminate wrong answers

Option A is wrong because InputStreamReader reads raw bytes and decodes them into characters, but it does not provide tokenization or integer parsing capabilities. Option B is wrong because BufferedReader reads text efficiently line by line, but it requires manual splitting and parsing of tokens to extract integers. Option C is wrong because DataInputStream reads primitive data types from a binary stream, not from a string of space-separated integers, and would throw an exception if used on text data.

15
MCQmedium

Refer to the exhibit. A developer runs a keytool command and sees the output above. Which command produced this output?

A.keytool -list -v -alias mykey -keystore keystore.jks
B.keytool -exportcert -alias mykey -keystore keystore.jks -file cert.cer
C.keytool -importcert -alias mykey -keystore keystore.jks -file cert.cer
D.keytool -printcert -file cert.cer
AnswerA

Shows verbose details of the specified alias.

Why this answer

Option A is correct because the `keytool -list -v -alias mykey -keystore keystore.jks` command displays detailed certificate information (including owner, issuer, serial number, validity, and fingerprint) for the specified alias in the JKS keystore. The `-v` flag produces verbose output, which matches the exhibit's detailed certificate listing.

Exam trap

The trap here is that candidates may confuse `-list -v` (which shows keystore entry details) with `-printcert` (which shows certificate file details), or mistakenly think `-exportcert` or `-importcert` produce verbose console output.

How to eliminate wrong answers

Option B is wrong because `keytool -exportcert` exports the certificate to a file (e.g., cert.cer), not to the console in a human-readable verbose format; it would not produce the listed output. Option C is wrong because `keytool -importcert` imports a certificate into the keystore, not list or display existing entries. Option D is wrong because `keytool -printcert` reads and prints details from a certificate file (e.g., cert.cer), not from a keystore entry; it does not use the `-alias` or `-keystore` options and would not show keystore-specific metadata.

16
MCQhard

Refer to the exhibit. What is the most likely cause of this exception?

A.The serialized object was tampered with after serialization.
B.The serial version UIDs of the class and stream do not match.
C.The stream's magic number is wrong due to a network error.
D.The file contains non-object data (e.g., text) instead of a serialized Java object.
AnswerD

The bytes 'ser' are likely part of a text file; the stream is not a serialized object.

Why this answer

Option D is correct because a `java.io.StreamCorruptedException` with the message 'invalid stream header: 546F6D' indicates that the input stream does not begin with the expected magic number `0xACED` (the standard Java serialization stream header). The hex value `546F6D` corresponds to the ASCII string 'Tom', which is plain text, not serialized object data. This occurs when a file containing non-object data (e.g., text) is read by `ObjectInputStream`.

Exam trap

The trap here is that candidates may confuse `StreamCorruptedException` with `InvalidClassException` (UID mismatch) or assume network corruption, but the specific hex value `546F6D` (ASCII 'Tom') is a clear giveaway that the file contains text, not random binary corruption.

How to eliminate wrong answers

Option A is wrong because tampering with a serialized object after serialization typically causes a `java.io.InvalidClassException` or a checksum/CRC mismatch, not a `StreamCorruptedException` with an invalid stream header. Option B is wrong because a mismatch in serial version UIDs results in an `InvalidClassException` during deserialization, not a `StreamCorruptedException`; the stream header is still valid. Option C is wrong because a network error corrupting the magic number would produce a different `StreamCorruptedException` message (e.g., 'invalid stream header: random bytes'), but the specific hex value `546F6D` (ASCII 'Tom') points to text data, not random corruption.

17
MCQmedium

A web server application writes access logs to a file. To ensure that log entries are written to disk immediately even if the JVM crashes, which approach is most appropriate?

A.Use FileOutputStream and call flush() after each write.
B.Use BufferedWriter and call write() then flush() periodically.
C.Use PrintWriter with autoFlush enabled.
D.Use FileWriter without any buffering.
AnswerA

Flushing after each write forces the data to be written to the underlying file system.

Why this answer

Option A is correct because FileOutputStream provides direct, unbuffered byte-level access to the underlying file. Calling flush() after each write forces the operating system to immediately write the data to disk, ensuring that log entries are persisted even if the JVM crashes before the next write cycle. This approach bypasses any intermediate buffering that could lose data.

Exam trap

The trap here is that candidates often confuse 'flush()' with 'sync()' and assume that flushing a buffered stream (like BufferedWriter or PrintWriter) guarantees disk persistence, when in fact it only pushes data to the next layer (e.g., OS buffer) and does not ensure an immediate disk write.

How to eliminate wrong answers

Option B is wrong because BufferedWriter uses an internal buffer (default 8192 characters) that delays writing to disk; even with periodic flush(), entries in the buffer at the time of a crash are lost. Option C is wrong because PrintWriter with autoFlush enabled only flushes after println() or printf() calls, not after every write() or print() call, and it still may buffer data internally, leading to potential data loss. Option D is wrong because FileWriter uses an internal buffer (default 8192 characters) for efficiency, so without explicit flushing, data remains in the buffer and is not written to disk immediately, risking loss on JVM crash.

18
MCQeasy

Refer to the exhibit. Which algorithm was used to generate the certificate fingerprint shown?

A.SHA-1
B.MD5
C.SHA-384
D.SHA-256
AnswerB

The fingerprint shown is MD5 as indicated in the exhibit.

Why this answer

The certificate fingerprint shown is a 32-character hexadecimal string, which corresponds to a 128-bit hash. MD5 produces a 128-bit (16-byte) hash, displayed as 32 hex digits. This matches the fingerprint format exactly, confirming that MD5 was used.

Exam trap

The trap here is that candidates often confuse the output length of hash algorithms: MD5 (32 hex chars) is frequently mistaken for SHA-1 (40 hex chars) or SHA-256 (64 hex chars), leading them to pick a wrong answer based on familiarity rather than counting the hex digits.

How to eliminate wrong answers

Option A is wrong because SHA-1 produces a 160-bit (20-byte) hash, displayed as 40 hex digits, not 32. Option C is wrong because SHA-384 produces a 384-bit (48-byte) hash, displayed as 96 hex digits. Option D is wrong because SHA-256 produces a 256-bit (32-byte) hash, displayed as 64 hex digits, not 32.

19
Multi-Selectmedium

Which TWO approaches are valid for writing text data to a file in Java? (Choose two.)

Select 2 answers
A.new FileOutputStream("out.txt").write(text.getBytes())
B.new RandomAccessFile("out.txt", "rw").writeUTF(text)
C.new FileWriter("out.txt", true).write(text)
D.new PrintWriter("out.txt").print(text)
E.Files.write(Paths.get("out.txt"), lines, StandardOpenOption.CREATE)
AnswersC, E

Writes characters with append mode; proper for text.

Why this answer

Option C is correct because `FileWriter` with the `true` argument opens the file in append mode, and its `write(String)` method directly writes the text to the file. This is a straightforward, valid approach for writing character data to a file using the Writer API.

Exam trap

The trap here is that candidates often confuse `PrintWriter` with `FileWriter` and assume `PrintWriter` automatically flushes or appends, but it does not unless explicitly configured (e.g., with `autoFlush=true` or using `FileWriter` as the underlying stream).

20
MCQeasy

A Java application writes sensitive user data to a file. To ensure that data is not left in the file system after the application crashes, which practice should be followed?

A.Call flush() after every write operation
B.Delete the file manually in a finally block
C.Use a FileLock to prevent concurrent access
D.Write to a temporary file, then use Files.move() with ATOMIC_MOVE to replace the target file
AnswerD

Atomic move ensures the target file is either fully written or not replaced, preventing partial writes.

Why this answer

Option D is correct because writing to a temporary file and then atomically moving it with `Files.move()` using the `ATOMIC_MOVE` option ensures that the target file is replaced only after the write succeeds. If the application crashes during the write, only the temporary file is corrupted, and the original target file remains intact. This prevents sensitive data from being left in an incomplete or partially written state in the file system.

Exam trap

The trap here is that candidates often confuse data flushing or locking with crash-safe file updates, but neither `flush()` nor `FileLock` provides atomicity guarantees, which is the key requirement for preventing data corruption after a crash.

How to eliminate wrong answers

Option A is wrong because calling `flush()` only forces buffered data to the underlying stream but does not guarantee that the data is fully written to disk or that the file is not left in an inconsistent state after a crash. Option B is wrong because manually deleting the file in a `finally` block cannot execute if the JVM crashes or the application is killed abruptly, leaving the sensitive data on disk. Option C is wrong because a `FileLock` prevents concurrent access from other JVM processes but does not protect against data loss or incomplete writes during a crash.

21
MCQeasy

A web application allows users to specify filenames for uploaded documents. The application saves files to a directory using the provided name. Which secure programming practice should be applied to prevent path traversal attacks?

A.Validate that the filename contains only alphanumeric characters.
B.Generate a random UUID for each file, ignoring the user-provided filename.
C.Replace all occurrences of ".." and "/" with an empty string.
D.Use File.getCanonicalPath() to resolve the path and check it starts with the intended directory.
AnswerD

By resolving the canonical path, the application can verify that the file lies within the allowed directory.

Why this answer

Option D is correct because `File.getCanonicalPath()` resolves all symbolic links, `.` and `..` sequences, and platform-specific path conventions to produce an absolute, unique path. By then verifying that this canonical path starts with the intended base directory (e.g., `/var/uploads/`), the application can definitively reject any path that escapes outside the allowed directory, even if the user-supplied filename contains encoded or obfuscated traversal sequences.

Exam trap

The trap here is that candidates often choose Option C (string replacement) because it seems straightforward, but they overlook that simple blacklisting of `..` and `/` is trivially bypassed by double-encoding, nested patterns, or Unicode normalization, whereas canonical path resolution is the only robust defense against path traversal.

How to eliminate wrong answers

Option A is wrong because restricting to alphanumeric characters is overly restrictive and still fails to prevent path traversal if the filename contains encoded traversal sequences (e.g., `%2e%2e%2f`) that are decoded after validation. Option B is wrong because while generating a random UUID eliminates the user-supplied filename entirely and prevents traversal, it is not a validation or sanitization technique; it is a complete replacement strategy that discards user intent, which may not be acceptable for all use cases (e.g., when the original filename must be preserved for business logic). Option C is wrong because simply replacing `..` and `/` with an empty string is easily bypassed by using nested patterns like `....//` which, after removal of `..` and `/`, leave `../` intact, or by using URL-encoded or Unicode variants that the replacement logic does not catch.

22
Multi-Selecthard

Which TWO statements about Java serialization are true?

Select 2 answers
A.The serialVersionUID must be explicitly declared in every serializable class.
B.During deserialization, the constructor of the serialized class is not invoked.
C.A class that implements Externalizable does not need to implement Serializable.
D.Static fields are not serialized during serialization.
E.Fields marked as transient are serialized by default.
AnswersB, D

Deserialization uses special mechanism without constructor.

Why this answer

Option B is correct because during deserialization, Java does not invoke the constructor of the class being deserialized. Instead, the object is reconstructed from the serialized stream data using the no-arg constructor of the first non-serializable superclass (if any), and the serialized class's fields are populated via reflection or readObject() methods. This avoids re-executing initialization logic that may have side effects or depend on runtime state.

Exam trap

The trap here is that candidates often assume constructors are always called during object creation, but Java serialization bypasses constructors for the serialized class, which can lead to unexpected behavior if initialization logic is missing.

23
MCQmedium

Refer to the exhibit. A Java application is deployed in /opt/app/lib/ and attempts to perform the following operations: 1) Read the file /data/config/settings.xml 2) Write to the file /logs/app.log 3) Read the file /data/config/subdir/extra.conf Which statement is true?

A.All three operations are allowed because the code base matches.
B.Operations 1 and 2 are allowed; operation 3 is denied.
C.Only operation 1 is allowed; operations 2 and 3 are denied.
D.Operations 1 and 3 are allowed; operation 2 is denied.
AnswerB

Operation 1 is allowed by "/data/config/*" (file in /data/config/). Operation 2 is explicitly granted. Operation 3 is in a subdirectory, not matched by *.

Why this answer

The grant applies to code from /opt/app/lib/* (all jars in that directory). The first FilePermission "/data/config/*" grants read access to /data/config/settings.xml but not to /data/config/subdir/extra.conf because * only matches files in the directory, not subdirectories. The second permission grants write to /logs/app.log exactly.

So only operations 1 and 2 are allowed.

24
MCQmedium

A developer wants to traverse a directory tree to find all files that are symbolic links. Which NIO.2 method should be used to follow symbolic links during traversal?

A.Files.newDirectoryStream(Path)
B.Files.list(Path)
C.Files.walk(Path) without options
D.Files.walk(Path, FileVisitOption.FOLLOW_LINKS)
AnswerD

This method with FOLLOW_LINKS will follow symbolic links during directory traversal.

Why this answer

The correct answer is D because `Files.walk(Path, FileVisitOption.FOLLOW_LINKS)` is the only method among the options that both traverses a directory tree recursively and explicitly follows symbolic links. The `FileVisitOption.FOLLOW_LINKS` enum constant instructs the walk to follow symbolic links, allowing the traversal to detect files that are themselves symbolic links. Without this option, `Files.walk` treats symbolic links as regular files and does not follow them, which would miss the target of the link.

Exam trap

The trap here is that candidates often assume `Files.walk(Path)` without options follows symbolic links by default, but the default behavior is to NOT follow links, and the `FOLLOW_LINKS` option must be explicitly provided to enable that behavior.

How to eliminate wrong answers

Option A is wrong because `Files.newDirectoryStream(Path)` returns a `DirectoryStream` that only lists the immediate entries of a single directory, not a recursive traversal, and it does not have any option to follow symbolic links. Option B is wrong because `Files.list(Path)` also only returns a stream of entries in a single directory (non-recursive) and cannot follow symbolic links. Option C is wrong because `Files.walk(Path)` without options performs a recursive traversal but does not follow symbolic links by default; it treats symbolic links as files and does not descend into directories that are symbolic links, so it would not find all files that are symbolic links in the sense of following them.

25
MCQmedium

A class implements Serializable. Which modification ensures that a specific field (password) is not included in the serialized stream?

A.Declare the field as volatile
B.Declare the field as transient
C.Declare the field as static
D.Declare the field as final
AnswerB

Transient fields are skipped during serialization.

Why this answer

Option C is correct because the transient keyword prevents serialization of that field. Option A is wrong because final does not affect serialization. Option B is wrong because static fields are not serialized anyway, but that changes the field's nature.

Option D is wrong because volatile affects concurrency, not serialization.

26
Multi-Selecthard

Which THREE are valid ways to read the contents of a text file into a String in Java?

Select 3 answers
A.String content = Files.readString(Path.of("file.txt"));
B.String content = new FileReader("file.txt").readString();
C.String content = Files.readAllLines(Path.of("file.txt"));
D.String content = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();
E.String content = Files.lines(Path.of("file.txt")).collect(Collectors.joining("\n"));
AnswersA, D, E

Files.readString() reads entire file into a String.

Why this answer

Option A is correct because `Files.readString()` (introduced in Java 11) reads the entire content of a text file into a `String` in one call, handling charset encoding (default UTF-8) and closing the file automatically. It is the simplest and most direct method for this task.

Exam trap

The trap here is that candidates may confuse `Files.readAllLines()` (which returns a `List`) with `Files.readString()` (which returns a `String`), or assume `FileReader` has a `readString()` method when it does not.

27
MCQhard

A serialized object has an explicitly declared serialVersionUID of 123L. After a code change, a new field is added to the class but the serialVersionUID is left unchanged. What happens when deserializing an old stream?

A.Deserialization succeeds and the new field is set to its default value.
B.Deserialization succeeds only if the new field is marked transient.
C.Deserialization throws StreamCorruptedException due to missing field.
D.Deserialization throws InvalidClassException because the class definition has changed.
AnswerA

With matching serialVersionUID, deserialization maps fields; new fields get default values.

Why this answer

Option A is correct because when a serialized object has an unchanged serialVersionUID, the Java deserialization mechanism treats the class as compatible. The new field is not present in the old stream, so it is simply initialized to its default value (e.g., null for objects, 0 for primitives) without throwing an exception. This behavior is defined by the Java Object Serialization Specification, which allows forward compatibility as long as the serialVersionUID matches.

Exam trap

The trap here is that candidates often assume any class change (like adding a field) will break deserialization, but the exam tests that a matching serialVersionUID allows the new field to be silently defaulted, not that it causes an exception.

How to eliminate wrong answers

Option B is wrong because marking the new field transient is not required for deserialization to succeed; the field will be set to its default value regardless of the transient modifier. Option C is wrong because StreamCorruptedException is thrown only when the stream data is corrupted or the stream header is invalid, not when a field is missing due to a class evolution. Option D is wrong because InvalidClassException is thrown only when the serialVersionUIDs differ between the local class and the stream, not when fields are added or removed while the UID remains the same.

28
MCQeasy

Which resource declaration order in try-with-resources is valid when both a FileInputStream and a BufferedInputStream wrapping it need to be closed automatically?

A.try (FileInputStream fis = new FileInputStream("a")) { BufferedInputStream bis = new BufferedInputStream(fis); ... }
B.try (FileInputStream fis = new FileInputStream("a"); BufferedInputStream bis = new BufferedInputStream(fis)) { ... }
C.try (BufferedInputStream bis = new BufferedInputStream(fis); FileInputStream fis = new FileInputStream("a")) { ... }
D.try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a"))) { ... }
AnswerB

Both resources are declared in order; fis is closed after bis as resources are closed in reverse order.

Why this answer

Option A is correct: Both resources are declared in the try header, with fis declared before bis. Option B has a forward reference error. Option C does not include bis in the try header, so it won't be automatically closed.

Option D only declares one resource, not both.

29
Multi-Selecthard

Which two statements are true about FileInputStream? (Select two.)

Select 2 answers
A.It supports mark() and reset().
B.It extends java.io.InputStream.
C.It implements java.io.Closeable.
D.It reads data in big-endian order.
E.It can be used to read characters.
AnswersB, C

FileInputStream is a subclass of InputStream.

Why this answer

Option B is correct because FileInputStream directly extends java.io.InputStream, inheriting its abstract methods for reading bytes from a file. Option C is correct because FileInputStream implements java.io.Closeable, which extends AutoCloseable, allowing it to be used in try-with-resources statements for automatic resource management.

Exam trap

The trap here is that candidates often confuse FileInputStream with BufferedInputStream or DataInputStream, assuming it supports mark/reset or reads data in a specific byte order, when in fact it is a simple unbuffered byte stream with no such capabilities.

30
MCQmedium

A developer is tasked with reading a large binary file (1 GB) from a network share using the least amount of memory possible. Which approach should be used?

A.Use a FileInputStream wrapped in a BufferedInputStream with a 8 KB buffer
B.Read the entire file into a byte array using Files.readAllBytes()
C.Use a FileReader wrapped in a BufferedReader to read lines
D.Use a RandomAccessFile to read the file in segments
AnswerA

This reads the file in chunks with a small buffer, minimizing memory footprint.

Why this answer

Option A is correct because using a FileInputStream wrapped in a BufferedInputStream with a small buffer (e.g., 8 KB) allows reading the file in chunks without loading the entire 1 GB into memory. This approach minimizes heap usage by processing data incrementally, which is essential for large binary files over a network share where memory constraints are critical.

Exam trap

The trap here is that candidates often confuse 'least memory' with 'fastest performance' and choose Files.readAllBytes() for simplicity, or they incorrectly assume RandomAccessFile is more memory-efficient, when in fact buffered streaming is the standard low-memory approach for large binary files.

How to eliminate wrong answers

Option B is wrong because Files.readAllBytes() reads the entire file into a single byte array, which would require at least 1 GB of heap memory, defeating the goal of minimal memory usage. Option C is wrong because FileReader and BufferedReader are designed for character-based text files, not binary data; reading a binary file as characters would corrupt the data and still buffer large amounts unnecessarily. Option D is wrong because RandomAccessFile is primarily for random access and seeking within a file, not for sequential streaming; it still requires managing file pointers and does not inherently reduce memory usage compared to a buffered stream.

31
MCQhard

A Java application uses FileChannel to copy a file to a remote network drive. The developer wants to ensure atomic file replacement on the destination. Which approach is correct?

A.Delete the destination file, then rename the temporary file.
B.Use Files.move() with StandardCopyOption.ATOMIC_MOVE.
C.Use FileChannel.transferTo() to write directly.
D.Use Files.copy() with REPLACE_EXISTING option.
AnswerB

Requests atomic move; throws exception if not supported.

Why this answer

Option B is correct because `Files.move()` with `StandardCopyOption.ATOMIC_MOVE` guarantees that the file replacement on the destination file system is atomic — either the entire move succeeds or the original state remains intact. This is essential for remote network drives where partial writes or concurrent access could leave the destination in an inconsistent state. The `ATOMIC_MOVE` option leverages file system–level atomic rename operations (e.g., NFS or SMB support) to ensure no intermediate state is visible.

Exam trap

The trap here is that candidates often assume `Files.copy()` with `REPLACE_EXISTING` or `FileChannel.transferTo()` provides atomicity because they replace the destination, but neither guarantees that the replacement is atomic — only `ATOMIC_MOVE` ensures the entire operation is indivisible at the file system level.

How to eliminate wrong answers

Option A is wrong because deleting the destination file and then renaming a temporary file is not atomic — a crash or concurrent access between the delete and rename can leave the destination missing or in an inconsistent state. Option C is wrong because `FileChannel.transferTo()` performs a direct, non-atomic copy that does not guarantee atomic replacement; it writes data in chunks and can leave a partial file on the destination if interrupted. Option D is wrong because `Files.copy()` with `REPLACE_EXISTING` replaces the destination file but does so as a non-atomic copy operation, meaning the destination may be overwritten partially or left in an inconsistent state if the copy fails.

32
MCQeasy

Which of the following correctly uses try-with-resources to ensure a FileInputStream is closed after use?

A.FileInputStream fis = new FileInputStream("file.txt"); try { ... } finally { fis.close(); }
B.try (FileInputStream fis = new FileInputStream("file.txt")) { ... }
C.try { FileInputStream fis = new FileInputStream("file.txt"); ... } finally { fis.close(); }
D.try (fis = new FileInputStream("file.txt")) { ... }
AnswerB

Correct syntax; resource is closed automatically.

Why this answer

Option B is correct because it uses the try-with-resources syntax (try (resource declaration) { ... }), which automatically closes the FileInputStream when the block exits, regardless of exceptions. This ensures the resource is closed without requiring an explicit finally block, as mandated by the AutoCloseable interface.

Exam trap

The trap here is that candidates often forget that try-with-resources requires the resource variable to be declared with its type inside the parentheses, and they mistakenly think a pre-declared variable or a variable without a type declaration is valid.

How to eliminate wrong answers

Option A is wrong because it uses a traditional try-finally block without try-with-resources, requiring manual close() call and risking resource leaks if an exception occurs before the finally block. Option C is wrong because it declares the FileInputStream inside the try block, making it inaccessible in the finally block for closing, leading to a compilation error. Option D is wrong because it omits the resource type declaration (FileInputStream) in the try-with-resources header, causing a compilation error as the variable must be declared with its type.

33
MCQhard

Refer to the exhibit. A security policy file is configured as shown. The application in app.jar tries to read a file named "${user.home}/data/db.properties". What is the result?

A.Access is denied because the FilePermission for data files is missing.
B.Access is denied because app.jar's AllPermission is not sufficient.
C.Access is allowed because the first grant includes read permission for logs/-, which covers data.
D.Access is allowed because app.jar has AllPermission.
AnswerD

AllPermission overrides any restrictions.

Why this answer

Option D is correct because the security policy grants AllPermission to app.jar, which supersedes any specific file permissions. AllPermission implies every possible permission, including read access to any file, regardless of path restrictions. Therefore, the application can read '${user.home}/data/db.properties' without denial.

Exam trap

The trap here is that candidates focus on the specific FilePermission grants and miss that AllPermission in the second grant renders all other permission checks irrelevant, leading them to incorrectly choose options based on path mismatches.

How to eliminate wrong answers

Option A is wrong because the FilePermission for data files is irrelevant when AllPermission is granted; AllPermission overrides all specific permission checks. Option B is wrong because AllPermission is the most powerful permission in the Java security model, granting all access rights, so it is sufficient for any operation. Option C is wrong because the first grant's read permission for logs/- does not cover the data directory; 'logs/-' only applies to files under the logs directory, not 'data/db.properties', but this is moot due to AllPermission.

34
MCQmedium

A financial application deserializes objects received over the network using ObjectInputStream. To prevent deserialization attacks, which secure coding practice should be implemented?

A.Use an ObjectInputFilter to whitelist allowed classes.
B.Override readObject() in each serializable class to validate data.
C.Declare all fields as transient to prevent unwanted data exposure.
D.Encrypt the serialized data with AES before transmission.
AnswerA

ObjectInputFilter provides a declarative way to restrict class loading during deserialization.

Why this answer

Option A is correct because ObjectInputFilter (introduced in Java 9) allows you to define a filter that whitelists only trusted classes during deserialization. By rejecting untrusted classes before they are deserialized, you prevent deserialization attacks such as remote code execution via gadget chains. This is the recommended secure coding practice per Oracle's secure coding guidelines for the Java I/O API.

Exam trap

The trap here is that candidates often confuse data validation (Option B) or encryption (Option D) with deserialization attack prevention, but the core issue is controlling which classes are allowed to be deserialized, which only an ObjectInputFilter can enforce at the stream level.

How to eliminate wrong answers

Option B is wrong because overriding readObject() to validate data only checks the integrity of the deserialized object's fields, but does not prevent the deserialization of malicious classes themselves; an attacker can still trigger dangerous class instantiation before validation occurs. Option C is wrong because declaring fields as transient prevents their serialization but does not protect against deserialization attacks—attackers can still deserialize non-transient fields or exploit the deserialization process itself. Option D is wrong because encrypting serialized data with AES protects confidentiality during transmission but does not prevent deserialization attacks; the attacker can still decrypt the data and then deserialize malicious classes on the receiving end.

35
MCQhard

In a JAAS login module, after the login() method returns true, which method must be called to commit the authentication and add principals to the Subject?

A.login()
B.initialize()
C.commit()
D.abort()
AnswerC

commit() commits the authentication and associates principals with the Subject.

Why this answer

Option C is correct. In a LoginModule, after successful login(), the commit() method is called to finalize the authentication. Option A (initialize) is called first to set up.

Option B (login) performs authentication. Option D (abort) is called if login fails or commit fails.

36
MCQhard

A financial trading application processes real-time stock data from multiple exchanges. The application reads large binary files (each up to 500 MB) containing trade records, processes them, and writes summary reports to a shared network drive. The development team observes that the application occasionally throws a java.io.IOException: 'The process cannot access the file because it is being used by another process' when writing reports. The application is multi-threaded, and each thread writes to a separate file in the same directory. The team also notices that the application slows down significantly when the network drive is under heavy load. The application runs on Windows servers with Java 17. The code uses FileOutputStream for writing and does not explicitly close streams in some paths. Which course of action should the team take to resolve the issues and improve performance?

A.Increase the thread pool size to handle more concurrent writes.
B.Use FileChannel with FileLock to synchronize access.
C.Switch to using try-with-resources for all FileOutputStream instances and wrap them in BufferedOutputStream with a larger buffer.
D.Write to local temporary files and then copy to the network drive.
AnswerC

This ensures proper closure and reduces I/O calls, mitigating both issues.

Why this answer

Option C is correct because the primary issue is resource leaks from not closing FileOutputStream instances, which can cause file locking conflicts on Windows when multiple threads write to separate files in the same directory. Using try-with-resources ensures streams are closed reliably, eliminating the 'file in use' IOException. Wrapping with BufferedOutputStream and a larger buffer reduces the number of write operations to the network drive, mitigating slowdowns under heavy load by batching data and minimizing latency.

Exam trap

The trap here is that candidates may think file locking (Option B) is needed for multi-threaded file access, but the question specifies each thread writes to a separate file, making locking irrelevant, while the real issue is resource leaks from unclosed streams and performance from unbuffered writes.

How to eliminate wrong answers

Option A is wrong because increasing the thread pool size would exacerbate contention on the network drive and increase the likelihood of file access conflicts, not resolve the underlying resource leak or performance issue. Option B is wrong because FileChannel with FileLock is designed for inter-process synchronization on the same file, but here each thread writes to a separate file, so locking is unnecessary and would add overhead without addressing the stream closure problem or network latency. Option D is wrong because writing to local temporary files and then copying to the network drive introduces additional I/O steps and does not fix the root cause of unclosed streams causing file locks; it also adds complexity and potential consistency issues if the copy fails.

37
Multi-Selectmedium

Which TWO statements about java.io and java.nio.file packages are true?

Select 2 answers
A.java.io.Console can be used to read from and write to the standard streams of the JVM.
B.java.nio.file.Files class provides methods for operating on symbolic links.
C.java.io.RandomAccessFile can be used for both reading and writing to a file.
D.java.io.FileInputStream supports the mark and reset methods.
E.java.nio.file.Path is a class that represents a file path.
AnswersB, C

Files has methods like isSymbolicLink, createSymbolicLink, etc.

Why this answer

Option B is correct because the `java.nio.file.Files` class provides methods such as `createSymbolicLink()`, `readSymbolicLink()`, and `isSymbolicLink()` that directly operate on symbolic links in the file system. This is a key feature of the NIO.2 API, which offers comprehensive support for file system metadata and link management, unlike the older `java.io` package.

Exam trap

The trap here is that candidates often confuse `java.io.Console` with standard streams or assume `Path` is a concrete class, and they may overlook that `FileInputStream` lacks mark/reset support, leading them to select incorrect options based on superficial familiarity.

38
Multi-Selecteasy

Which two of the following are valid methods to create a new directory using the NIO.2 Files class? (Select two.)

Select 2 answers
A.Files.mkdir(Path)
B.Files.createNewDirectory(Path)
C.Files.createDirectory(Path)
D.Files.createDirectories(Path)
E.Files.makeDirectory(Path)
AnswersC, D

Creates a single directory if parent exists.

Why this answer

The Files class in the java.nio.file package provides two static methods for creating directories: createDirectory(Path) creates a single directory, failing if the parent does not exist or if the directory already exists; createDirectories(Path) creates the directory and any nonexistent parent directories, succeeding silently if the target already exists. Both are valid and commonly used for NIO.2 directory creation.

Exam trap

The trap here is that candidates confuse legacy java.io.File methods (mkdir, mkdirs) with NIO.2 Files methods, or misremember method names like createNewDirectory or makeDirectory, which do not exist in the Files class.

39
MCQeasy

Which class provides a convenient means to read text from a file line by line?

A.FileReader
B.Scanner
C.FileInputStream
D.BufferedReader
AnswerD

Reads text efficiently line by line.

Why this answer

BufferedReader (option D) is the correct answer because it provides the `readLine()` method, which reads text from a character-input stream line by line, efficiently buffering characters to avoid frequent disk reads. When wrapped around a FileReader, it enables convenient and performant line-by-line reading of text files.

Exam trap

The trap here is that candidates often choose Scanner (option B) because they know it has `nextLine()`, but they overlook that Scanner is not optimized for simple line-by-line file reading and is typically used for parsing structured input, whereas BufferedReader is the dedicated, efficient choice for this task.

How to eliminate wrong answers

Option A is wrong because FileReader reads characters from a file but does not provide a `readLine()` method; it only offers `read()` for single characters or arrays, requiring manual line parsing. Option B is wrong because Scanner can read text line by line using `nextLine()`, but it is primarily designed for parsing tokens and is less efficient for simple line-by-line reading due to its internal regex-based tokenization and lack of buffering. Option C is wrong because FileInputStream reads raw bytes, not text, and does not support line-by-line reading; it would require wrapping in InputStreamReader and BufferedReader to achieve that functionality.

40
MCQhard

A large-scale data processing platform uses Java to read and write files across multiple nodes. Recently, operations have slowed down significantly. The system uses FileInputStream and FileOutputStream wrapped in BufferedInputStream and BufferedOutputStream with default buffer sizes (8 KB). The operations team suspects that the default buffer size is causing excessive system calls. The files are typically 100 MB to 1 GB in size. Which change would most improve I/O performance while minimizing memory overhead?

A.Increase the buffer size to 64 KB.
B.Switch to using FileChannel with direct ByteBuffers for all file operations.
C.Use memory-mapped files (MappedByteBuffer) for the entire file.
D.Replace FileInputStream with FileReader and FileOutputStream with FileWriter.
AnswerA

A larger buffer reduces system calls, improving throughput without significant memory increase.

Why this answer

Increasing the buffer size to 64 KB reduces the number of system calls (read/write) by allowing more data to be transferred per call. With default 8 KB buffers and 100 MB–1 GB files, the overhead of frequent kernel transitions is significant. A 64 KB buffer strikes a good balance between performance gain and memory overhead, as it is large enough to reduce syscalls substantially without consuming excessive heap space.

Exam trap

The trap here is that candidates often assume memory-mapped files or direct buffers are always faster, overlooking that the primary bottleneck in this scenario is excessive system calls due to small buffer size, and that a simple buffer size increase is the most direct and memory-efficient fix.

How to eliminate wrong answers

Option B is wrong because switching to FileChannel with direct ByteBuffers introduces additional complexity and memory management overhead (native memory allocation) that may not be justified; while it can improve performance, it does not directly address the root cause of excessive system calls due to small buffer size, and the memory overhead of direct buffers can be higher. Option C is wrong because memory-mapping the entire file (MappedByteBuffer) for files up to 1 GB would consume a large portion of the virtual address space and can cause performance degradation due to page faults and garbage collection pressure, especially when multiple files are accessed concurrently; it is not a minimal-memory-overhead solution. Option D is wrong because FileReader and FileWriter are character-stream wrappers that add encoding/decoding overhead and do not change the underlying buffering behavior; they still use the same default buffer size and do not reduce system call frequency.

41
MCQmedium

A Java application running in a secure environment needs to read a file located outside the application's directory. Which approach correctly handles security?

A.Use FileInputStream without any additional configuration
B.Grant java.io.FilePermission in the security policy file for the specific file path
C.Use java.net.URL to access the file via file:// protocol
D.Set the file readable flag using File.setReadable(true)
AnswerB

This grants the application permission to read the file under the security manager.

Why this answer

Option B is correct because in a secure Java environment, the SecurityManager enforces access controls based on the security policy file. To read a file outside the application's directory, you must explicitly grant `java.io.FilePermission` with the specific file path and the `read` action in the policy file. Without this permission, any attempt to read the file will throw a `java.security.AccessControlException`.

Exam trap

The trap here is that candidates often confuse OS-level file permissions (like `setReadable`) with Java's SecurityManager permissions, or assume that using a URL protocol bypasses security checks, when in fact the SecurityManager enforces the same policy regardless of the I/O API used.

How to eliminate wrong answers

Option A is wrong because using `FileInputStream` without additional configuration will trigger the SecurityManager, which by default denies access to files outside the application's directory, resulting in a security exception. Option C is wrong because using `java.net.URL` with the `file://` protocol still goes through the same file I/O security checks; the SecurityManager will block access unless the appropriate `FilePermission` is granted, and the URL approach does not bypass security policies. Option D is wrong because `File.setReadable(true)` only modifies the file's operating system permissions and does not affect the Java SecurityManager's access control; the SecurityManager will still enforce its own policy and deny access if no `FilePermission` is granted.

42
MCQeasy

A developer needs to create a temporary file that will be automatically deleted when the JVM terminates. Which approach correctly achieves this?

A.File.createTempFile("pre", ".txt").deleteOnExit()
B.new File("tmp.txt").deleteOnExit()
C.Files.createTempDirectory("tmp").toFile().deleteOnExit()
D.Files.createTempFile("pre", ".txt")
AnswerA

Creates a temp file and registers it for automatic deletion on JVM exit.

Why this answer

Option A is correct because `File.createTempFile("pre", ".txt")` creates a temporary file in the default temporary-file directory, and chaining `.deleteOnExit()` registers that file for deletion when the JVM terminates. This combination ensures both the creation of a temporary file and its automatic cleanup upon JVM shutdown, fulfilling the requirement precisely.

Exam trap

The trap here is that candidates often confuse creating a temporary file with simply scheduling deletion of any file, or they forget that `Files.createTempFile()` alone does not register for automatic deletion, leading them to pick option D without the necessary `.deleteOnExit()` call.

How to eliminate wrong answers

Option B is wrong because `new File("tmp.txt")` creates a File object representing a file in the current working directory, not a temporary file in the system's temp directory, and `.deleteOnExit()` only schedules deletion of that arbitrary file; it does not create a temporary file. Option C is wrong because `Files.createTempDirectory("tmp")` creates a temporary directory, not a file, and while `.toFile().deleteOnExit()` schedules the directory for deletion, the requirement specifies a temporary file, not a directory. Option D is wrong because `Files.createTempFile("pre", ".txt")` creates a temporary file but does not call `.deleteOnExit()`, so the file will not be automatically deleted when the JVM terminates; it only creates the file without any cleanup registration.

43
MCQmedium

A developer is writing a utility to copy a large binary file (e.g., 500 MB) from one location to another while minimizing memory overhead and ensuring data integrity. Which approach is most appropriate?

A.Use BufferedReader and BufferedWriter for binary data.
B.Use a custom loop reading into a byte array of 8KB and writing to the output stream.
C.Use Files.copy() with StandardCopyOption.REPLACE_EXISTING.
D.Use FileInputStream.readAllBytes() and FileOutputStream.write().
AnswerB

Processes data in small chunks, keeping memory usage low.

Why this answer

Option B is correct because reading and writing in fixed-size chunks (e.g., 8KB) minimizes memory overhead by avoiding loading the entire 500 MB file into memory, while still providing efficient I/O through buffered operations. This approach ensures data integrity by processing the file sequentially without relying on character-based streams, which are unsuitable for binary data.

Exam trap

The trap here is that candidates often choose Files.copy() (Option C) because it is convenient and commonly used, but the question explicitly requires minimizing memory overhead, and Files.copy() does not expose buffer size control, making the custom loop (Option B) the more precise answer for this specific constraint.

How to eliminate wrong answers

Option A is wrong because BufferedReader and BufferedWriter are character-based streams that decode bytes into characters using a charset, which can corrupt binary data and add unnecessary overhead. Option C is wrong because Files.copy() internally uses a buffer and is a valid approach, but it does not allow the developer to control buffer size or handle partial writes explicitly, making it less appropriate when minimizing memory overhead is a primary concern. Option D is wrong because FileInputStream.readAllBytes() loads the entire 500 MB file into memory as a byte array, defeating the goal of minimizing memory overhead.

44
MCQeasy

Which interface should be implemented to create a custom filter for deserialization in Java?

A.ObjectInputFilter
B.Serializable
C.ObjectOutput
D.FilterOutputStream
AnswerA

Defines the filter to accept or reject classes during deserialization.

Why this answer

The `ObjectInputFilter` interface (introduced in Java 9) allows you to define a custom filter that validates classes and data being deserialized from an `ObjectInputStream`. By implementing this interface, you can reject potentially malicious or unexpected classes during deserialization, which is a key security measure against deserialization attacks.

Exam trap

The trap here is that candidates confuse `ObjectInputFilter` with `Serializable` or stream-level filters like `FilterOutputStream`, missing that the question specifically asks for a filter on the deserialization process itself.

How to eliminate wrong answers

Option B is wrong because `Serializable` is a marker interface that enables an object to be serialized/deserialized, not to filter deserialization. Option C is wrong because `ObjectOutput` is an interface for writing objects to a stream (serialization), not for filtering deserialization. Option D is wrong because `FilterOutputStream` is a class that wraps an output stream to filter byte-level output, not for filtering object deserialization.

45
Multi-Selecthard

Which three actions help secure a Java application that uses serialization? (Select three.)

Select 3 answers
A.Overriding resolveClass() in ObjectInputStream to validate class names.
B.Implementing ObjectInputFilter to set a deserialization filter.
C.Using transient keyword for sensitive fields.
D.Using SecureRandom to generate serialVersionUID.
E.Declaring serialVersionUID explicitly as a long constant.
AnswersA, B, C

Allows filtering of classes during deserialization.

Why this answer

Option A is correct because overriding `resolveClass()` in `ObjectInputStream` allows you to validate the class name before it is deserialized. This prevents deserialization attacks where an attacker sends a malicious class that could execute arbitrary code. By checking the class name against a whitelist, you can block untrusted classes from being loaded.

Exam trap

The trap here is that candidates often confuse versioning best practices (like declaring `serialVersionUID`) with security controls, or think that using `SecureRandom` for `serialVersionUID` adds security, when in fact it only breaks compatibility and does nothing to prevent deserialization attacks.

46
MCQmedium

A company uses serialization to transfer objects between microservices. To prevent deserialization attacks, they want to restrict which classes can be deserialized. Which approach should be used in Java 17?

A.Override resolveClass in ObjectInputStream
B.Use SecurityManager with a policy file
C.Use ObjectInputFilter with a custom filter
D.Implement Externalizable and control fields
AnswerC

ObjectInputFilter is the recommended approach to restrict deserialized classes in modern Java.

Why this answer

Option C is correct because Java 17 provides the `ObjectInputFilter` API (introduced in Java 9) as the standard mechanism to restrict which classes can be deserialized. By setting a custom filter via `ObjectInputStream.setObjectInputFilter()` or a system-wide `jdk.serialFilter` property, you can whitelist or blacklist classes based on patterns, effectively preventing deserialization attacks without modifying the serialization stream itself.

Exam trap

The trap here is that candidates often confuse `resolveClass` (which loads a class) with `ObjectInputFilter` (which filters class resolution), or they assume `SecurityManager` is still the correct tool for this task despite its deprecation in Java 17.

How to eliminate wrong answers

Option A is wrong because overriding `resolveClass` in `ObjectInputStream` only controls which class is loaded for a given stream descriptor, but it does not provide a flexible, pattern-based filtering mechanism and can be bypassed if not carefully implemented; it is also not the recommended approach in modern Java. Option B is wrong because `SecurityManager` with a policy file is deprecated for removal in Java 17 and was never designed specifically to filter deserialization classes—it controls permissions, not the content of serialized streams. Option D is wrong because implementing `Externalizable` controls the serialization format and fields, but it does not restrict which classes can be deserialized; an attacker could still send a malicious serialized object of a different class.

47
MCQmedium

A developer is building a file synchronization tool that runs on multiple threads. Multiple threads may read and write to the same file concurrently. The developer wants to ensure that a thread does not read a file while another thread is writing to it, and that concurrent reads are allowed. Which locking mechanism should be used?

A.Use a ReentrantReadWriteLock in Java with the file as a resource.
B.Use synchronized blocks on the File object.
C.Use a Semaphore with permits equal to the number of threads.
D.Use java.nio.channels.FileLock with shared lock for reading and exclusive lock for writing.
AnswerD

FileLock with shared/exclusive modes allows concurrent reads and exclusive writes, and works across processes.

Why this answer

Option D is correct because java.nio.channels.FileLock provides a platform-independent mechanism for locking files, supporting shared locks for concurrent reads and exclusive locks for writes. This ensures that a thread cannot read a file while another thread is writing to it, while allowing multiple threads to read simultaneously, which matches the requirement exactly.

Exam trap

The trap here is that candidates often confuse in-memory concurrency mechanisms (like ReentrantReadWriteLock or synchronized) with file-level locking, forgetting that file access across threads or processes requires OS-level coordination provided by FileLock.

How to eliminate wrong answers

Option A is wrong because ReentrantReadWriteLock is a Java concurrency utility that works on in-memory objects, not on file system resources; it cannot coordinate access across threads that may be in different JVMs or processes. Option B is wrong because synchronized blocks on the File object only provide mutual exclusion within the same JVM, and they do not differentiate between read and write access, thus blocking concurrent reads unnecessarily. Option C is wrong because a Semaphore with permits equal to the number of threads can limit concurrency but does not distinguish between read and write operations, so it cannot allow concurrent reads while blocking writes.

48
MCQeasy

You are developing a Java application that processes sensitive user data. The application runs on a server with strict security policies. You need to read configuration properties from a file located at /etc/app/config.properties. The application uses a SecurityManager. During testing, you get a security exception: java.security.AccessControlException: access denied (java.io.FilePermission /etc/app/config.properties read). You have already added a file permission grant in the policy file for the application codebase. However, the exception persists. What is the most likely cause?

A.The application codebase URL in the policy file is incorrect.
B.A library or caller on the execution stack does not have the required FilePermission.
C.The file path is relative and needs to be resolved against user.dir.
D.The policy file is not being loaded because the JVM was not started with -Djava.security.policy.
AnswerB

SecurityManager requires all callers in the chain to have permission.

Why this answer

Option B is correct because even if the application's own codebase has the required FilePermission, any library or caller on the execution stack that does not have the permission will cause an AccessControlException. The SecurityManager performs stack inspection: every class on the call stack must have the required permission. If a library or framework method invoked by your code lacks the grant, the check fails.

Exam trap

The trap here is that candidates assume granting permission to the application codebase alone is sufficient, forgetting that the SecurityManager checks all callers on the execution stack, not just the top-level application code.

How to eliminate wrong answers

Option A is wrong because an incorrect codebase URL would prevent the policy grant from being applied to your code, but the question states you already added the grant and the exception persists, so the URL is likely correct. Option C is wrong because the file path is absolute (/etc/app/config.properties), not relative, so there is no resolution against user.dir. Option D is wrong because if the policy file were not loaded at all, the exception would still occur, but the question says you added a grant and the exception persists, implying the policy file is loaded but the grant is insufficient due to stack inspection.

49
MCQhard

A Java application needs to refer to a file using the path "data/input.txt". To ensure platform independence (correct file separator), which approach is recommended?

A.FileSystems.getDefault().getPath("data", "input.txt")
B.new File("data/input.txt").toPath().normalize()
C.new File("data/input.txt").toPath()
D.Paths.get("data", "input.txt")
AnswerD

Paths.get separates components and uses correct file separator.

Why this answer

Option B (Paths.get) accepts a varargs of strings and joins them using the platform file separator. Option A uses File's path which uses the default separator but File is older API. Option C is equivalent but more verbose.

Option D is unnecessary. Paths.get is the most idiomatic modern NIO.2 approach.

50
MCQmedium

A Java application uses SecurityManager with a policy file. Which permission is required to allow the application to read all files in the /var/log directory, including subdirectories?

A.permission java.io.FilePermission "/var/log", "read";
B.permission java.io.FilePermission "/var/log/-", "read";
C.permission java.io.FilePermission "/var/log/*", "read,write";
D.permission java.io.FilePermission "/var/log/*", "read";
AnswerB

"-" grants access to all files and subdirectories recursively.

Why this answer

Option B is correct because the trailing '-' in the path pattern '/var/log/-' is a recursive wildcard that matches all files and subdirectories under /var/log, which is required to read all files in that directory tree. The permission grants 'read' access, which is the only action needed for reading files.

Exam trap

The trap here is that candidates often confuse the single-level wildcard '*' with the recursive wildcard '-', leading them to choose option D which only grants access to files directly in /var/log, not subdirectories.

How to eliminate wrong answers

Option A is wrong because '/var/log' without a wildcard matches only the directory entry itself, not its contents or subdirectories. Option C is wrong because it includes 'write' permission, which is unnecessary for reading files, and uses '*' which matches only direct children, not recursive subdirectories. Option D is wrong because '*' matches only files and directories directly inside /var/log, not those in subdirectories.

51
MCQeasy

A web application allows users to upload profile pictures. The application saves the files to a directory using the original filename provided by the user. After a security review, the team discovered a critical path traversal vulnerability. Which remediation is most effective in preventing exploitation while maintaining usability?

A.Store the files in a database BLOB instead of the filesystem.
B.Sanitize the filename by removing all occurrences of "../" and "/".
C.Check that the file extension is allowed (e.g., .jpg, .png) and no special characters.
D.Generate a random UUID as the filename and store the original filename in a database.
AnswerD

By not using the user-provided filename in the path, traversal is impossible.

Why this answer

Option D is correct because generating a random UUID as the filename eliminates the user's control over the file path, making path traversal attacks impossible. The original filename can be stored in a database for display purposes, preserving usability while ensuring the file is saved with a safe, unpredictable name.

Exam trap

The trap here is that candidates often think sanitizing input (Option B) or checking extensions (Option C) is sufficient, but they fail to realize that path traversal can be achieved through encoding tricks or by combining traversal sequences with valid extensions.

How to eliminate wrong answers

Option A is wrong because storing files in a database BLOB does not prevent path traversal; it only changes the storage medium, and the vulnerability could still exist if the filename is used in retrieval logic. Option B is wrong because removing only "../" and "/" is insufficient; attackers can use encoded variants (e.g., "..%2f") or other traversal patterns like "....//" to bypass the filter. Option C is wrong because checking the file extension alone does not prevent path traversal; an attacker could still include directory traversal sequences in the filename (e.g., "../../etc/passwd.jpg") that pass the extension check.

52
Multi-Selecthard

Which TWO are secure coding practices for Java I/O that help prevent resource leaks and unauthorized access? (Choose two.)

Select 2 answers
A.Mark sensitive fields in a Serializable class as transient to prevent serialization.
B.Use Scanner instead of BufferedReader when reading untrusted input.
C.Always use BufferedReader for reading text files to improve performance.
D.Use try-with-resources for any stream, reader, or writer to ensure automatic closure.
E.Grant FilePermission in the security policy to restrict file access for untrusted code.
AnswersA, D

Prevents sensitive data from being exposed in serialized streams, reducing the risk of data leakage.

Why this answer

Using try-with-resources ensures that all resources are closed automatically, preventing resource leaks. Marking sensitive fields as transient prevents their serialization. Option C (using Scanner) is not inherently secure; Option D (BufferedReader) is fine but not specifically a security practice; Option E (FilePermission) is a security policy, not a coding practice.

53
MCQmedium

A Java application reads configuration from a file using FileInputStream. The application must handle the case where the configuration file is missing by logging a warning and using default values. Which design approach best meets this requirement?

A.Wrap the FileInputStream in a try-with-resources and catch Exception to handle missing file.
B.Use Files.exists() to check file existence before opening the stream, and if absent, log a warning and use defaults.
C.Catch FileNotFoundException inside the try block and set default values.
D.Use File.exists() to check file existence before opening the stream, and if absent, log a warning and use defaults.
AnswerB

Proactive check avoids exception overhead and is clear.

Why this answer

Option B is correct because it explicitly checks for file existence using `Files.exists()` before attempting to open the stream, allowing the application to log a warning and fall back to default values without throwing an exception. This approach aligns with the requirement to handle a missing configuration file gracefully, avoiding unnecessary exception handling overhead. The `Files.exists()` method is part of the modern `java.nio.file` API, which is preferred over the legacy `File.exists()` for its better integration with symbolic links and file system operations.

Exam trap

The trap here is that candidates often confuse `File.exists()` (legacy, less reliable) with `Files.exists()` (modern, recommended), and they may incorrectly assume that catching `FileNotFoundException` is the standard way to handle missing files, overlooking the cleaner pre-check approach that avoids exceptions entirely.

How to eliminate wrong answers

Option A is wrong because catching `Exception` is too broad and may mask other unexpected errors (e.g., security or permission issues), and `try-with-resources` alone does not provide a clean way to log a warning and set defaults without throwing an exception. Option C is wrong because catching `FileNotFoundException` inside the try block still requires the stream to be opened, which will throw the exception before any logging or default assignment can occur, and the code structure is awkward. Option D is wrong because `File.exists()` is a legacy method that does not handle symbolic links correctly and is less reliable than `Files.exists()` from the `java.nio.file` package, which is the recommended approach in modern Java.

54
MCQhard

A developer is building a batch processing application that reads a large CSV file (approx. 5 GB) from a network file system, transforms each row, and writes the result to a database. The initial implementation uses Files.lines(path) to obtain a Stream<String>, processes each line with forEach, and then does not explicitly close the stream. After running for several minutes, the application slows down, and eventually throws an IOException: 'Too many open files'. The database writes are also failing intermittently. The developer needs to fix the application. The environment is Java 17 on Linux with default settings. Which course of action best resolves the issues?

A.Use FileInputStream with a buffered byte array and manually scan for newline characters.
B.Replace Files.lines with Files.newBufferedReader, wrapping it in a try-with-resources block.
C.Use Files.readAllLines to load the entire file into memory and then iterate over the list.
D.Wrap the Files.lines call in a try-with-resources block to ensure the stream is closed automatically.
AnswerD

By using try-with-resources, the stream's underlying file handle is closed when the block exits, fixing the resource leak. This is the minimal and correct fix.

Why this answer

The 'Too many open files' error indicates that the file handle from Files.lines is not being closed, causing a resource leak. Using try-with-resources ensures the stream is closed after processing. Option A (BufferedReader) also requires try-with-resources to avoid leaks, and if not used, would have the same issue.

Option C (InputStream) would not handle lines. Option D (Files.readAllLines) would cause memory issues.

55
Multi-Selecteasy

Which TWO approaches are recommended to secure Java I/O operations? (Choose two.)

Select 2 answers
A.Use try-with-resources to ensure proper resource closure.
B.Use BufferedInputStream to wrap FileInputStream for better performance.
C.Use Serializable interface for all data objects.
D.Use FileLock to prevent concurrent write access.
E.Validate user input before using it in file path construction.
AnswersA, E

Ensures file handles are closed, preventing resource exhaustion.

Why this answer

Option A is correct because try-with-resources automatically closes each resource declared in its header when the block exits, whether normally or via exception. This eliminates the risk of resource leaks from forgotten or improperly handled close() calls, which is a fundamental security and reliability requirement for I/O operations.

Exam trap

The trap here is that candidates often confuse performance optimizations (like buffering) or concurrency mechanisms (like FileLock) with security practices, and they may also mistakenly think that serialization is a security measure when it is actually a data format concern with its own security risks.

56
MCQmedium

A method receives an InputStream and needs to compute its MD5 hash while reading the data. Which approach is most efficient?

A.Use DigestInputStream wrapping the original stream, then read the stream
B.Read all bytes into a byte array, then compute hash using MessageDigest
C.Use a custom filter that hashes bytes during read
D.Use Scanner to read tokens and update hash
AnswerA

DigestInputStream computes the hash as data is read, requiring no additional memory.

Why this answer

Option A is correct because `DigestInputStream` is a built-in Java class that computes a message digest (e.g., MD5) on the fly as data is read from the underlying stream. This avoids buffering the entire stream into memory, making it both memory-efficient and CPU-efficient for large or streaming data sources.

Exam trap

The trap here is that candidates may assume reading all bytes into memory first (Option B) is simpler or more straightforward, overlooking the memory and performance implications for large streams, and fail to recognize that `DigestInputStream` is the standard, efficient solution in the Java I/O API.

How to eliminate wrong answers

Option B is wrong because reading all bytes into a byte array before computing the hash requires O(n) memory, which is inefficient for large streams and may cause OutOfMemoryError. Option C is wrong because implementing a custom filter that hashes bytes during read is redundant and error-prone; `DigestInputStream` already provides this exact functionality with a well-tested, optimized implementation. Option D is wrong because `Scanner` is designed for tokenizing text input, not for binary hashing, and using it would introduce unnecessary overhead and potential data corruption for binary streams.

57
MCQhard

An application deserializes objects from a network stream. To protect against deserialization attacks, which approach is most effective in Java 17?

A.Declare all fields as transient
B.Set an ObjectInputFilter on the ObjectInputStream
C.Use try-with-resources to auto-close the stream
D.Mark the class as final
AnswerB

Allows rejection of classes based on criteria, preventing attacks.

Why this answer

Option B is correct because setting an ObjectInputFilter on the ObjectInputStream allows you to define a filter that can reject deserialization of arbitrary or malicious classes, which is the primary defense against deserialization attacks. This mechanism, introduced in Java 9 and enhanced in later versions, lets you whitelist or blacklist classes based on patterns, limits on array sizes, or depth of object graphs, directly mitigating the risk of remote code execution or denial-of-service via crafted serialized data.

Exam trap

Oracle often tests the misconception that making fields transient or closing streams properly is sufficient to prevent deserialization attacks, when in reality the core vulnerability lies in the deserialization process itself, which must be actively filtered.

How to eliminate wrong answers

Option A is wrong because declaring all fields as transient prevents their serialization but does not protect against deserialization of malicious data; the attacker can still trigger the deserialization process and exploit the constructor or readObject method of the class. Option C is wrong because try-with-resources ensures the stream is closed after use, which is good resource management but does not inspect or filter the incoming serialized data, leaving the application vulnerable to attacks. Option D is wrong because marking a class as final prevents subclassing but does not restrict which classes can be deserialized; an attacker can still deserialize any class that implements Serializable, including final ones.

58
Multi-Selectmedium

Which THREE are benefits of using the NIO.2 API over the java.io API?

Select 3 answers
A.Better performance for all I/O operations compared to java.io.
B.Simplified recursive file operations using FileVisitor.
C.Access to file attributes like creation time, owner, and permissions.
D.Automatic file compression when writing.
E.Support for symbolic links and other file system features.
AnswersB, C, E

walkFileTree and SimpleFileVisitor simplify recursive traversal.

Why this answer

Option B is correct because the NIO.2 API introduces the `FileVisitor` interface, which simplifies recursive file operations by allowing you to implement methods like `preVisitDirectory`, `visitFile`, and `visitFileFailed` that are automatically called during a tree walk. This eliminates the need for manual recursion and boilerplate code required in the `java.io` API, making directory traversal more efficient and less error-prone.

Exam trap

The trap here is that candidates assume NIO.2 always outperforms `java.io` (Option A) or conflate its channel-based I/O with automatic compression (Option D), when the exam specifically tests understanding of NIO.2's unique file system features like `FileVisitor`, symbolic links, and attribute access.

59
MCQmedium

Refer to the exhibit. Assuming the application is running from /home/application/lib/myapp.jar, which of the following actions is allowed by the policy?

A.All of the above
B.Write to the file /var/log/app.log
C.Queue a print job using the system printer
D.Read the file /etc/config/application.properties
AnswerA

All three actions are explicitly granted by the policy.

Why this answer

The policy grants all permissions (java.security.AllPermission) to the codebase file:/home/application/lib/myapp.jar, which means any action—including writing to /var/log/app.log, queuing a print job, and reading /etc/config/application.properties—is allowed. The AllPermission permission effectively disables all security checks for that code source, so all three listed actions are permitted.

Exam trap

Oracle often tests the misconception that a policy file with a single permission entry only allows the explicitly listed action, but AllPermission is a blanket grant that overrides all other permission checks, making every action permissible.

How to eliminate wrong answers

Option B is wrong because it is actually allowed by the policy, but the question asks which actions are allowed, and since all are allowed, B alone is not the complete answer. Option C is wrong because it is also allowed, but again it is not the complete answer. Option D is wrong because it is allowed as well, but selecting only D would miss the other permitted actions.

The correct answer is 'All of the above' because the policy grants AllPermission, which covers every possible action.

60
MCQeasy

Which interface is designed for recursively walking a file tree?

A.DirectoryStream
B.FilenameFilter
C.FileFilter
D.FileVisitor
AnswerD

FileVisitor is the callback interface for walking file trees.

Why this answer

The `FileVisitor` interface is designed for recursively walking a file tree, as it provides callback methods (`preVisitDirectory`, `postVisitDirectory`, `visitFile`, `visitFileFailed`) that are invoked during a depth-first traversal of a file tree, typically used with `Files.walkFileTree()`. This allows you to process each file and directory in the tree, including subdirectories, making it the correct choice for recursive file tree walking.

Exam trap

The trap here is that candidates often confuse `DirectoryStream` (which iterates a single directory) with a recursive walker, or they mistakenly think `FileFilter` or `FilenameFilter` can handle recursion, when in fact they only filter entries in a single directory listing.

How to eliminate wrong answers

Option A is wrong because `DirectoryStream` is designed for iterating over the entries in a single directory, not for recursively walking a file tree; it does not traverse subdirectories. Option B is wrong because `FilenameFilter` is a functional interface used to filter filenames in a directory listing (e.g., with `File.list(FilenameFilter)`), and it has no support for recursive traversal. Option C is wrong because `FileFilter` is similar to `FilenameFilter` but operates on `File` objects; it is used for filtering files in a single directory and does not provide recursive walking capabilities.

61
Multi-Selectmedium

Which TWO secure coding practices should be followed when developing a Java application that handles user input? (Choose two.)

Select 2 answers
A.Use PreparedStatement for database queries with user input.
B.Serialize sensitive data without encryption for performance.
C.Grant java.security.AllPermission to the application's codebase.
D.Validate and sanitize all user input before processing.
E.Use java.util.Random for generating session tokens.
AnswersA, D

Prevents SQL injection.

Why this answer

Option A is correct because using PreparedStatement with parameterized queries prevents SQL injection by separating SQL logic from user input. The database driver automatically escapes special characters in the input, ensuring that user-supplied data is treated as literal values, not executable SQL code.

Exam trap

Oracle often tests the distinction between predictable random generators (java.util.Random) and cryptographically secure ones (SecureRandom), expecting candidates to know that session tokens require unpredictability, not just randomness.

62
MCQeasy

A developer needs to read a large text file (several gigabytes) line by line as efficiently as possible, processing each line without loading the entire file into memory. Which approach should the developer use?

A.Use a FileReader wrapped in a BufferedReader, and process each line in a loop.
B.Use a FileInputStream to read bytes, then manually parse newline characters.
C.Use Files.readAllLines to read the entire file into a List<String> and then iterate.
D.Use Files.lines with a try-with-resources block, and process each line using the stream.
AnswerD

Files.lines returns a Stream that reads lines lazily, and try-with-resources ensures the underlying file handle is closed automatically. This is the most efficient and idiomatic solution.

Why this answer

Files.lines returns a Stream<String> that reads lines lazily from the file, allowing processing without loading the whole file into memory. Using try-with-resources ensures the stream is closed properly. Option A (FileReader wrapped in BufferedReader) also reads line by line but requires manual resource management to avoid leaks; while correct, it is not the most idiomatic and concise approach.

Option C (FileInputStream) reads raw bytes. Option D (Files.readAllLines) reads all lines into the memory, causing out-of-memory for large files.

63
MCQmedium

A developer wants to copy all files from one directory to another, preserving file attributes (e.g., last modified time, permissions). Which NIO.2 method is most appropriate?

A.Files.copy(source, target, COPY_ATTRIBUTES)
B.Files.copy(source, target, REPLACE_EXISTING)
C.Files.move(source, target, ATOMIC_MOVE)
D.Files.walkFileTree() with a custom FileVisitor that copies files
AnswerA

COPY_ATTRIBUTES ensures attributes are preserved during copy.

Why this answer

Option A is correct because the `Files.copy(source, target, COPY_ATTRIBUTES)` method from the NIO.2 API copies the content of the file and, when the `COPY_ATTRIBUTES` option is specified, also preserves the file's metadata attributes such as last modified time, last access time, and permissions (where supported by the underlying file system). This option is specifically designed for copying with attribute preservation, making it the most appropriate choice for the developer's requirement.

Exam trap

The trap here is that candidates often confuse `REPLACE_EXISTING` with attribute preservation, assuming that replacing the target file inherently copies all metadata, when in fact `COPY_ATTRIBUTES` must be explicitly specified to preserve attributes.

How to eliminate wrong answers

Option B is wrong because `Files.copy(source, target, REPLACE_EXISTING)` only replaces the target file if it already exists but does not include the `COPY_ATTRIBUTES` option, so file attributes are not preserved during the copy. Option C is wrong because `Files.move(source, target, ATOMIC_MOVE)` moves the file (not copies it) and ensures the move is atomic, but it does not copy files and does not guarantee attribute preservation in all cases; it is intended for moving rather than copying. Option D is wrong because `Files.walkFileTree()` with a custom `FileVisitor` is a more complex, manual approach for recursively copying directory trees, but it does not automatically preserve file attributes unless the developer explicitly implements attribute copying logic; it is not the most appropriate single method for the simple task of copying all files with attributes.

64
MCQmedium

A logging framework in Java has been writing logs to a file using a FileWriter with default buffer size. The logs are frequently lost when the application crashes because the buffer is not flushed. Which change ensures that log messages are written immediately without significantly impacting performance?

A.Use a FileWriter with autoFlush=true.
B.Set the buffer size to 0 to disable buffering.
C.Use a PrintWriter wrapping a FileWriter and set autoFlush=true.
D.Call flush() after every log message.
AnswerC

PrintWriter with autoFlush provides a balance: messages are flushed after each line, reducing data loss without excessive overhead.

Why this answer

Option C is correct because a PrintWriter wrapping a FileWriter with autoFlush=true ensures that every println, printf, or format call triggers an automatic flush of the underlying stream. This guarantees log messages are written to disk immediately upon each write, preventing data loss during a crash, while still allowing the FileWriter's internal buffer to aggregate small writes for performance. The autoFlush mechanism in PrintWriter is specifically designed for this use case in Java I/O.

Exam trap

The trap here is that candidates confuse FileWriter's lack of an autoFlush option with PrintWriter's autoFlush feature, or they incorrectly assume that disabling buffering (buffer size 0) is a practical solution, when in fact it causes severe performance degradation due to excessive system calls.

How to eliminate wrong answers

Option A is wrong because FileWriter does not have an autoFlush parameter; autoFlush is a feature of PrintWriter and PrintStream, not of FileWriter itself. Option B is wrong because setting the buffer size to 0 would disable buffering entirely, causing every single write to perform a costly system call, which significantly degrades performance—this is not a recommended approach. Option D is wrong because calling flush() after every log message would work but requires manual, error-prone code changes throughout the application, and it does not leverage the built-in autoFlush mechanism that provides the same effect with less developer overhead.

65
Drag & Dropmedium

Order the steps to create an immutable class in Java.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Immutability requires no way to change object state after construction. Defensive copying prevents internal state from being altered.

66
MCQhard

Given a requirement to efficiently copy a large file (over 2 GB) from one path to another, which approach is most appropriate for Java NIO.2?

A.Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING)
B.Using Files.readAllBytes() then Files.write()
C.Using FileInputStream and FileOutputStream with a buffer of 8192 bytes
D.Using FileChannel.transferTo() with position and count
AnswerD

FileChannel.transferTo() leverages OS-level file transfer mechanisms, making it most efficient for large files.

Why this answer

Option D is correct because `FileChannel.transferTo()` leverages zero-copy I/O, which allows data to be transferred directly between file system caches without unnecessary copying through user-space buffers. This is particularly efficient for large files (over 2 GB) as it minimizes context switches and memory overhead, and the method supports a `position` and `count` parameter to handle large file offsets correctly.

Exam trap

The trap here is that candidates often assume `Files.copy()` is the most straightforward and efficient NIO.2 method, but the exam specifically tests knowledge of zero-copy APIs (`FileChannel.transferTo()`) for large file operations, where the overhead of stream-based copying becomes a performance bottleneck.

How to eliminate wrong answers

Option A is wrong because `Files.copy()` internally uses a simple stream-based copy with a default buffer size (typically 8192 bytes), which does not take advantage of zero-copy or direct file system optimizations, making it suboptimal for very large files. Option B is wrong because `Files.readAllBytes()` loads the entire file into heap memory, which will cause an `OutOfMemoryError` for a file over 2 GB and is extremely inefficient. Option C is wrong because using `FileInputStream` and `FileOutputStream` with an 8192-byte buffer performs many small read/write operations, incurring high system call overhead and lacking the zero-copy optimization that `FileChannel.transferTo()` provides.

67
Matchingmedium

Match each concurrency utility to its purpose.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Allows one or more threads to wait until a count reaches zero

Allows a set of threads to wait for each other to reach a common barrier point

Controls access to a resource via a permit system

Allows two threads to exchange objects at a synchronization point

A reusable barrier that supports dynamic number of parties

Why these pairings

These are synchronization aids from java.util.concurrent.

68
MCQmedium

A company needs to read a large text file (over 2 GB) line by line in a Java application while minimizing memory footprint. Which approach is most efficient?

A.Use Files.readAllLines(path)
B.Use FileOutputStream with read() loop
C.Use Scanner with File and loop hasNextLine()
D.Use Files.lines(path) with try-with-resources
AnswerD

Lazy stream reading minimizes memory; auto-closes resource.

Why this answer

Option D is correct because `Files.lines(path)` returns a `Stream<String>` that lazily reads lines from the file, processing them one at a time without loading the entire file into memory. Combined with try-with-resources, the underlying `BufferedReader` is automatically closed, ensuring efficient resource management even for files over 2 GB.

Exam trap

The trap here is that candidates often choose `Scanner` (Option C) because it is familiar from simple file reading, but they overlook its higher memory overhead and lack of automatic resource management compared to the stream-based `Files.lines()` with try-with-resources.

How to eliminate wrong answers

Option A is wrong because `Files.readAllLines(path)` reads the entire file into a `List<String>` in memory, which would cause an `OutOfMemoryError` for a file over 2 GB. Option B is wrong because `FileOutputStream` is designed for binary byte output, not reading text; using its `read()` method would require manual byte-to-character conversion and lacks line-by-line parsing, making it inefficient and error-prone for text files. Option C is wrong because `Scanner` with `hasNextLine()` internally buffers the file and can be slower for large files due to its regex-based tokenization overhead, and it does not leverage the optimized lazy streaming of `Files.lines()`.

69
MCQhard

A class implements Serializable but the developer wants to completely prevent deserialization of its instances. Which approach accomplishes this?

A.Override readResolve() to return a null.
B.Override readObject() to throw an InvalidClassException.
C.Override writeObject() to encrypt the object.
D.Override writeReplace() to throw an exception.
AnswerB

This causes deserialization to fail immediately.

Why this answer

Option B is correct because overriding readObject() to throw an InvalidClassException (or any exception) prevents the deserialization mechanism from completing. When an ObjectInputStream calls readObject() on a class that defines its own readObject() method, that custom method is invoked instead of the default deserialization. Throwing an exception inside readObject() aborts the deserialization process, effectively blocking the reconstruction of the instance.

Exam trap

The trap here is that candidates often confuse readResolve() with readObject(), thinking that returning null from readResolve() prevents deserialization, when in fact readResolve() runs after the object is already created, so it does not stop the deserialization process itself.

How to eliminate wrong answers

Option A is wrong because overriding readResolve() to return null does not prevent deserialization; readResolve() is called after the object is already deserialized, and returning null simply replaces the deserialized object with null, but the object has already been created in memory. Option C is wrong because overriding writeObject() to encrypt the object only affects serialization, not deserialization; the attacker can still call readObject() on the encrypted stream if they have the decryption key or bypass the encryption entirely. Option D is wrong because overriding writeReplace() to throw an exception only prevents serialization (writing), not deserialization; the developer wants to prevent deserialization, and writeReplace() is invoked during serialization, not during reading.

70
MCQhard

An architect is designing a microservice that reads large CSV files (up to 500 MB) from a shared filesystem and processes each row. The processing is CPU-bound and must not block the main thread. The service is deployed in a container with limited memory (512 MB heap). Which approach is most suitable?

A.Use Files.readAllLines() to read the entire file into memory, then process in parallel using streams.
B.Use a BufferedReader on a separate thread, reading lines into a bounded queue, and a thread pool to process rows from the queue.
C.Use a FileChannel with a memory-mapped byte buffer of the entire file.
D.Use a java.nio.file.FileSystem with a WatchService to detect changes to the file.
AnswerB

This approach reads line by line, using a bounded queue to decouple reading and processing.

Why this answer

Option B is correct because it uses a bounded blocking queue to decouple I/O (reading lines from the CSV) from CPU-bound processing, preventing the main thread from being blocked while also avoiding memory exhaustion. The bounded queue acts as a back-pressure mechanism, ensuring that the limited 512 MB heap is not overwhelmed by the 500 MB file. Processing rows via a thread pool allows parallel CPU-bound work without blocking the reading thread.

Exam trap

The trap here is that candidates often assume memory-mapped files (FileChannel) are always efficient for large files, but they ignore the memory constraint and the need to keep the main thread responsive; Cisco tests whether you understand that bounded queues and separate threads are required for back-pressure and non-blocking processing in constrained environments.

How to eliminate wrong answers

Option A is wrong because Files.readAllLines() loads the entire file into memory as a List<String>, which would require at least 500 MB (plus overhead for String objects and UTF-16 encoding) and likely cause an OutOfMemoryError with a 512 MB heap. Option C is wrong because memory-mapping the entire file with a FileChannel would still map the full 500 MB into virtual memory, consuming significant heap or native memory and risking memory pressure; it also does not inherently offload CPU-bound processing to a separate thread. Option D is wrong because a WatchService is designed for monitoring file system changes (e.g., modifications, deletions) and has no role in reading or processing file contents; it would not help with reading or processing the CSV rows.

71
MCQeasy

Which statement about java.io and java.nio.file packages is true?

A.The java.nio.file package provides support for symbolic links and file attributes
B.Classes in java.nio.file are thread-safe by default
C.The java.io package includes the Path interface
D.The java.nio.file package is deprecated in favor of java.io
AnswerA

NIO.2 includes methods for creating symbolic links and reading file attributes.

Why this answer

Option A is correct because the java.nio.file package (part of NIO.2) explicitly provides support for symbolic links via methods like Files.createSymbolicLink() and Files.isSymbolicLink(), and it offers comprehensive file attribute access through classes like BasicFileAttributes, DosFileAttributes, and PosixFileAttributes, which are not available in java.io.

Exam trap

The trap here is that candidates often confuse the legacy java.io.File class with the modern java.nio.file.Path interface, assuming Path is in java.io because both deal with files, or they mistakenly think java.nio.file is deprecated due to its 'nio' naming, when in fact it is the recommended API.

How to eliminate wrong answers

Option B is wrong because classes in java.nio.file are not thread-safe by default; while some operations may be atomic, the API does not guarantee thread safety for all methods, and concurrent access requires external synchronization. Option C is wrong because the Path interface is part of the java.nio.file package, not java.io; java.io contains File, which is a legacy class. Option D is wrong because java.nio.file is not deprecated; it is the modern replacement for java.io, offering improved performance and features, and java.io itself is not deprecated but is considered legacy for many use cases.

72
MCQmedium

A developer needs to copy a large directory tree from one location to another, preserving file attributes. Which method should be used?

A.Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES)
B.Implement a FileVisitor using Files.walkFileTree and copy each file with COPY_ATTRIBUTES
C.Use Files.walk() and then Files.copy() for each entry
D.Use FileUtils.copyDirectory from Apache Commons IO
AnswerB

walkFileTree allows recursive traversal and attribute preservation.

Why this answer

Option B is correct because `Files.walkFileTree` with a custom `FileVisitor` allows you to recursively traverse a directory tree and copy each file individually using `Files.copy` with `StandardCopyOption.COPY_ATTRIBUTES`. This is necessary because `Files.copy` on a directory does not copy the directory tree recursively; it only copies the top-level directory entry. The `FileVisitor` pattern ensures that subdirectories and files are visited and copied in depth-first order, preserving file attributes at each step.

Exam trap

The trap here is that candidates assume `Files.copy` with `COPY_ATTRIBUTES` works recursively on directories, but it only copies the directory entry, not its contents, requiring a tree-walking approach like `Files.walkFileTree` to achieve a full recursive copy with attribute preservation.

How to eliminate wrong answers

Option A is wrong because `Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES)` on a directory only copies the directory entry itself, not its contents; it does not recursively copy the tree. Option C is wrong because `Files.walk()` returns a `Stream<Path>` that does not inherently handle directory creation or attribute preservation during copy; using `Files.copy` on each entry without a `FileVisitor` would fail to create parent directories and could overwrite or skip files incorrectly. Option D is wrong because `FileUtils.copyDirectory` from Apache Commons IO is a third-party library method, not part of the standard Java I/O API, and the question asks for a method within the standard Java API.

73
Multi-Selecthard

Which THREE are recommended practices to prevent privilege escalation when using doPrivileged in a security-sensitive Java application?

Select 3 answers
A.Restrict the codebase URLs in policy files to only trusted code locations.
B.Use SubjectDomainCombiner to merge multiple protection domains.
C.Always use a SecurityManager to enforce the policy.
D.Sign JARs and verify signatures to ensure code integrity.
E.Use AccessController.checkPermission to explicitly check permissions before privileged operations.
AnswersA, D, E

Limiting which code can be granted privileges reduces attack surface.

Why this answer

Option A is correct because restricting codebase URLs in policy files to only trusted code locations limits the sources from which privileged code can be loaded. This prevents an attacker from injecting malicious code from an untrusted URL that could otherwise be granted elevated permissions via doPrivileged. By narrowing the codebase, you reduce the attack surface for privilege escalation attacks.

Exam trap

The trap here is that candidates often confuse the mechanism (SecurityManager) with a preventive practice, or think that SubjectDomainCombiner is a security control when it actually aggregates permissions and can inadvertently widen the privilege scope.

74
Multi-Selectmedium

Which TWO statements are true about securing a Java application?

Select 2 answers
A.A security policy file can grant specific permissions to code from a particular codebase.
B.Enabling the security manager is required for all Java applications.
C.The Java Cryptography Extension (JCE) is deprecated and should not be used.
D.Using code signing guarantees that the application is secure.
E.The SecurityManager class can be used to set a security policy for the application.
AnswersA, E

Policy files allow granular permission assignments.

Why this answer

Option A is correct because a Java security policy file can use a codebase URL (e.g., `codeBase "file:/path/to/jar"`) to grant specific permissions, such as `java.io.FilePermission`, to code loaded from that location. This is a core feature of the Java security model, allowing fine-grained access control based on where the code originates.

Exam trap

The trap here is that candidates often confuse the optional nature of the SecurityManager (thinking it is mandatory) or assume code signing implies security, when in fact it only provides integrity and origin verification, not safety.

Page 1 of 2 · 81 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Java Io Security questions.