Unit 3: File I/O and JDBC - Practice Quiz

CSE406 — Advanced Java Programming 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which method is commonly used to create a Path object from a path string?

Using the Path interface to operate on file and directory paths Easy
A. File.path()
B. Paths.open()
C. Files.create()
D. Path.of()

2 Which Path method returns the final element of a file path?

Using the Path interface to operate on file and directory paths Easy
A. getFileName()
B. getParent()
C. getNameCount()
D. getRoot()

3 Which Path method combines the current path with another path?

Using the Path interface to operate on file and directory paths Easy
A. relativize()
B. normalize()
C. resolve()
D. toAbsolutePath()

4 Which method checks whether a file or directory exists?

Using the Files class to check, delete, copy, or move a file or directory Easy
A. Files.contains()
B. Files.isOpen()
C. Files.available()
D. Files.exists()

5 Which method deletes a file only when it exists and avoids an exception when it is missing?

Using the Files class to check, delete, copy, or move a file or directory Easy
A. Files.clearIfExists()
B. Files.deleteIfExists()
C. Files.eraseIfFound()
D. Files.removeIfFound()

6 Which Files method is used to copy a file to another path?

Using the Files class to check, delete, copy, or move a file or directory Easy
A. Files.duplicate()
B. Files.copy()
C. Files.clone()
D. Files.transfer()

7 Which method returns a stream of lines from a text file?

Using Stream API with NIO2 Easy
A. Files.tokens()
B. Files.lines()
C. Files.records()
D. Files.entries()

8 Which method returns a stream containing entries directly inside a directory?

Using Stream API with NIO2 Easy
A. Files.find()
B. Files.list()
C. Files.lines()
D. Files.walk()

9 Why should a stream returned by Files.lines() usually be used in a try-with-resources statement?

Using Stream API with NIO2 Easy
A. It modifies the source file
B. It creates a database transaction
C. It holds an open file resource
D. It starts a background thread

10 Which Java package contains core JDBC interfaces such as Connection and Statement?

Defining the layout of the JDBC API Easy
A. java.sql
B. java.database
C. java.jdbc
D. javax.jdbc

11 Which JDBC interface represents an active session with a database?

Defining the layout of the JDBC API Easy
A. ResultSet
B. Statement
C. DriverManager
D. Connection

12 Which method is commonly used to obtain a JDBC database connection?

Connecting to a database by using a JDBC driver Easy
A. DataSource.openDriver()
B. DriverManager.openDatabase()
C. Connection.createSession()
D. DriverManager.getConnection()

13 What is the main purpose of a JDBC driver?

Connecting to a database by using a JDBC driver Easy
A. Store query results permanently
B. Replace the database server
C. Create SQL tables automatically
D. Translate JDBC calls for a database

14 Which method is normally used to execute a SQL SELECT statement?

Submitting queries and getting results from the database Easy
A. executeSelect()
B. executeQuery()
C. executeUpdate()
D. executeInsert()

15 Which JDBC interface stores rows returned by a database query?

Submitting queries and getting results from the database Easy
A. ResultSet
B. DriverManager
C. PreparedStatement
D. Connection

16 Which ResultSet method moves the cursor to the next row?

Submitting queries and getting results from the database Easy
A. next()
B. advance()
C. forward()
D. move()

17 Which file type is commonly used to store a JDBC URL, username, and password outside Java source code?

Specifying JDBC driver information externally Easy
A. A class file
B. A manifest file
C. A properties file
D. A bytecode file

18 What is a key benefit of storing JDBC configuration externally?

Specifying JDBC driver information externally Easy
A. Tables are created at startup
B. Queries execute without a driver
C. Connections never need credentials
D. Settings can change without recompiling

19 Which CRUD operation adds a new row to a database table?

Performing CRUD operations using the JDBC API Easy
A. Read
B. Update
C. Delete
D. Create

20 Which JDBC method is commonly used for SQL INSERT, UPDATE, and DELETE statements?

Performing CRUD operations using the JDBC API Easy
A. executeUpdate()
B. readRows()
C. fetchResults()
D. executeQuery()

21 Given Path base = Paths.get("/data/reports");, which expression refers to the file /data/reports/2024/summary.txt without converting the path to a string?

Using the Path interface to operate on file and directory paths Medium
A. base.append("2024/summary.txt")
B. base.resolve("2024").resolve("summary.txt")
C. base.concat("2024").concat("summary.txt")
D. base.join("2024", "summary.txt")

22 What is the result of Paths.get("/home/user/docs/report.txt").getParent() on a Unix-like system?

Using the Path interface to operate on file and directory paths Medium
A. report.txt
B. /home/user/docs/report.txt
C. /home/user
D. /home/user/docs

23 A program needs to compare two paths that may contain . and .. elements, but it must not access the file system. Which operation is appropriate?

Using the Path interface to operate on file and directory paths Medium
A. Files.readAttributes()
B. normalize()
C. Files.isSameFile()
D. toRealPath()

24 Which statement correctly checks whether a path exists while avoiding an exception if the path is inaccessible?

Using the Files class to check, delete, copy, or move a file or directory Medium
A. Files.isAvailable(path)
B. Files.check(path)
C. Files.valid(path)
D. Files.exists(path)

25 What happens when Files.copy(source, target) is used and target already exists as a regular file?

Using the Files class to check, delete, copy, or move a file or directory Medium
A. It appends source bytes to the target file
B. It silently replaces the target file
C. It throws FileAlreadyExistsException
D. It returns false without changing either file

26 Which option allows an existing target file to be replaced during a copy operation?

Using the Files class to check, delete, copy, or move a file or directory Medium
A. StandardCopyOption.REPLACE_EXISTING
B. StandardCopyOption.OVERWRITE
C. StandardCopyOption.ALLOW_REPLACE
D. StandardCopyOption.UPDATE_TARGET

27 Why can Files.delete(directory) fail even when the directory exists?

Using the Files class to check, delete, copy, or move a file or directory Medium
A. Directories cannot be deleted by Java
B. The delete method only handles regular files
C. The directory is not empty
D. The directory must first be copied

28 Which statement correctly creates a stream containing the entries directly inside the directory represented by dir?

Using Stream API with NIO2 Medium
A. Files.entries(dir)
B. dir.listFiles()
C. Files.stream(dir)
D. Files.list(dir)

29 Which code correctly finds all regular .java files under sourceDir, including files in nested directories?

Using Stream API with NIO2 Medium
A. Files.search(sourceDir, p -> p.toString().endsWith(".java"))
B. Files.find(sourceDir, Integer.MAX_VALUE, (p, a) -> a.isRegularFile() && p.toString().endsWith(".java"))
C. Files.walkFileTree(sourceDir).filter(p -> p.toString().endsWith(".java"))
D. Files.list(sourceDir).filter(p -> p.toString().endsWith(".java"))

30 A method uses Files.lines(path) to process a large text file. What is the most appropriate resource-management approach?

Using Stream API with NIO2 Medium
A. Close only the Path object after processing
B. Use it inside a try-with-resources statement
C. Convert it to a list before processing
D. Store the stream in a static field

31 Which expression counts regular files in the directory tree rooted at root?

Using Stream API with NIO2 Medium
A. Files.walk(root).filter(Files::isRegularFile).count()
B. Files.readAllLines(root).filter(Files::isRegularFile).count()
C. Files.list(root).filter(Files::isRegularFile).size()
D. Files.walk(root).filter(Files::isDirectory).count()

32 Which JDBC component is primarily responsible for creating Connection objects from database URLs?

Defining the layout of the JDBC API Medium
A. ResultSet
B. DriverManager
C. SQLException
D. Statement

33 Which JDBC object represents the active session between an application and a database?

Defining the layout of the JDBC API Medium
A. Connection
B. DatabaseMetaData
C. ResultSet
D. Driver

34 Which sequence is generally required before an application can execute a SQL statement through JDBC?

Connecting to a database by using a JDBC driver Medium
A. Close a connection, create a statement, execute SQL
B. Create a result set, obtain a connection, execute SQL
C. Execute SQL, create a statement, obtain a connection
D. Obtain a connection, create a statement, execute SQL

35 What is the main advantage of using PreparedStatement instead of concatenating user input into SQL?

Connecting to a database by using a JDBC driver Medium
A. It removes the need for a JDBC driver
B. It automatically commits every transaction
C. It helps prevent SQL injection
D. It converts every query into a stored procedure

36 Which method is normally used to execute a SELECT statement and obtain its rows?

Submitting queries and getting results from the database Medium
A. executeInsert()
B. executeQuery()
C. executeUpdate()
D. executeRows()

37 When iterating through a ResultSet, what does resultSet.next() do?

Submitting queries and getting results from the database Medium
A. Executes the SQL statement again
B. Moves to the next column and returns its value
C. Closes the current database connection
D. Moves to the next row and reports whether one exists

38 An application reads the database URL, username, and password from a properties file. What is the primary benefit?

Specifying JDBC driver information externally Medium
A. SQL statements no longer require validation
B. Database settings can change without recompiling code
C. The JDBC driver is automatically installed
D. Transactions are committed without application code

39 Which configuration item identifies the JDBC implementation class when explicit driver loading is required?

Specifying JDBC driver information externally Medium
A. The transaction isolation level
B. The result set type
C. The column label
D. The driver class name

40 Which mapping correctly associates CRUD operations with common SQL commands?

Performing CRUD operations using the JDBC API Medium
A. Create-UPDATE, Read-DELETE, Update-SELECT, Delete-INSERT
B. Create-DELETE, Read-UPDATE, Update-INSERT, Delete-SELECT
C. Create-SELECT, Read-INSERT, Update-DELETE, Delete-UPDATE
D. Create-INSERT, Read-SELECT, Update-UPDATE, Delete-DELETE

41 Given Path base = Paths.get("/srv/app"); and Path input = Paths.get("../logs/app.log");, what is the result of base.resolve(input) on a Unix-like system?

Using the Path interface to operate on file and directory paths Hard
A. /srv/app/logs/app.log
B. ../logs/app.log
C. /srv/app/../logs/app.log
D. /srv/logs/app.log

42 Which statement best describes Path.normalize() when applied to a path containing . and .. elements?

Using the Path interface to operate on file and directory paths Hard
A. It verifies that the normalized path exists
B. It resolves symbolic links before simplifying
C. It converts every path to an absolute path
D. It removes redundant name elements lexically

43 A program must compare two paths to determine whether they identify the same existing file, even when one path contains symbolic links. Which operation is most appropriate?

Using the Path interface to operate on file and directory paths Hard
A. path1.toAbsolutePath().equals(path2.toAbsolutePath())
B. path1.getFileName().equals(path2.getFileName())
C. path1.toRealPath().equals(path2.toRealPath())
D. path1.normalize().equals(path2.normalize())

44 A directory contains files and subdirectories. The program calls Files.delete(directory). What is the normal result?

Using the Files class to check, delete, copy, or move a file or directory Hard
A. Only the directory entry is deleted
B. DirectoryNotEmptyException is thrown
C. The directory and all descendants are deleted
D. AccessDeniedException is always thrown

45 Which behavior is guaranteed when copying an existing file with Files.copy(source, target) and no copy options?

Using the Files class to check, delete, copy, or move a file or directory Hard
A. Symbolic links are always followed recursively
B. The target is always overwritten
C. An existing target normally causes FileAlreadyExistsException
D. The source is always deleted afterward

46 A move must fail rather than silently degrade if the file system cannot perform an atomic rename. Which option should be supplied to Files.move?

Using the Files class to check, delete, copy, or move a file or directory Hard
A. StandardCopyOption.COPY_ATTRIBUTES
B. StandardCopyOption.REPLACE_EXISTING
C. StandardCopyOption.ATOMIC_MOVE
D. LinkOption.NOFOLLOW_LINKS

47 What is the most important resource-management requirement when processing a file with Files.lines(path)?

Using Stream API with NIO2 Hard
A. The stream should be sorted before closing
B. The stream should be consumed inside try-with-resources
C. The stream should be marked parallel before reading
D. The stream should be converted to an array immediately

48 Which statement correctly distinguishes Files.list(directory) from Files.walk(directory)?

Using Stream API with NIO2 Hard
A. list requires a regular file, while walk requires an empty directory
B. list returns direct children, while walk can recursively traverse descendants
C. list follows every symbolic link, while walk never follows links
D. list recursively visits descendants, while walk visits siblings only

49 A program uses Files.find(root, 3, matcher) to locate files. Which paths can be examined when root has depth zero?

Using Stream API with NIO2 Hard
A. Only descendants exactly three levels below it
B. root and descendants up to three levels below it
C. Only root itself
D. All descendants regardless of their depth

50 A Files.walk(root) pipeline uses filter(Files::isRegularFile) and then count(). What is the primary limitation of this approach for a very large tree?

Using Stream API with NIO2 Hard
A. It loads every file's contents into memory
B. It cannot inspect nested directories
C. It may retain an open traversal resource until the stream closes
D. It automatically follows all symbolic links

51 Which JDBC component is primarily responsible for managing a set of JDBC drivers and selecting an appropriate driver for a connection URL?

Defining the layout of the JDBC API Hard
A. ResultSet
B. DatabaseMetaData
C. Connection
D. DriverManager

52 Which JDBC object represents the database session through which statements are created and transactions are controlled?

Defining the layout of the JDBC API Hard
A. SQLException
B. ResultSet
C. Connection
D. Driver

53 A JDBC 4-compliant driver is packaged correctly and available on the class path. Which statement is generally true before calling DriverManager.getConnection?

Connecting to a database by using a JDBC driver Hard
A. The driver can be discovered through the JDBC service-provider mechanism
B. The driver must be instantiated through Connection
C. The driver is loaded only after the first ResultSet is created
D. The driver must always be registered with Class.forName

54 A connection URL is valid, but no installed driver accepts its subprotocol. What is the most likely result of DriverManager.getConnection(url)?

Connecting to a database by using a JDBC driver Hard
A. A SQLException indicating no suitable driver is available
B. A connection using the default system driver is returned
C. A read-only connection is returned
D. A ResultSet containing the URL is returned

55 Why is a PreparedStatement generally preferred over string concatenation when inserting user-supplied values into a SQL statement?

Submitting queries and getting results from the database Hard
A. It automatically commits every successful query
B. It separates SQL structure from parameter values
C. It disables transaction isolation changes
D. It guarantees that every query uses an index

56 After executing a query, the cursor of a newly created JDBC ResultSet is initially positioned where?

Submitting queries and getting results from the database Hard
A. After the final row
B. On the last row
C. Before the first row
D. On the first row

57 Which design best separates JDBC connection configuration from application code?

Specifying JDBC driver information externally Hard
A. Derive the password from the database product name
B. Store URL, user, and password in external configuration
C. Place credentials in SQL comments next to each query
D. Hard-code the URL and password in every DAO

58 An application loads JDBC settings from a Properties object and calls DriverManager.getConnection(url, properties). Which statement is correct?

Specifying JDBC driver information externally Hard
A. The properties replace the URL's subprotocol
B. The properties convert all values into SQL literals
C. The driver may use standard and vendor-specific properties
D. The properties force auto-commit to remain enabled

59 An application inserts a row and must obtain the database-generated primary key. Which approach is most appropriate?

Performing CRUD operations using the JDBC API Hard
A. Use executeQuery on an INSERT statement
B. Call getString on the Connection object
C. Use executeUpdate with RETURN_GENERATED_KEYS
D. Read the largest existing key after insertion

60 A transfer updates two account rows. Which sequence provides the required all-or-nothing behavior when auto-commit is disabled?

Performing CRUD operations using the JDBC API Hard
A. Execute both updates without calling either commit or rollback
B. Call rollback after each successful update
C. Commit after the first update, then execute the second update
D. Execute both updates, then call commit; call rollback on failure