Unit 3: File I/O and JDBC - Subjective Questions
CSE406 — Advanced Java Programming • Practice Questions with Detailed Answers
20 questions
Define the Path interface in Java NIO.2. Explain how it is used to represent and operate on file and directory paths, with suitable examples.
Answer:
The Path interface, available in the java.nio.file package, represents a path to a file or directory in a file system. It provides methods for examining and manipulating paths without directly accessing the file contents.
Important features:
- A
Pathcan represent an absolute or relative path. - It is platform-independent and adapts to the operating system.
- It can be created using
Paths.get()orPath.of(). - It supports operations such as resolving, normalizing, and comparing paths.
Example:
Path path = Path.of("documents", "report.txt");
System.out.println(path.getFileName());
System.out.println(path.getParent());
System.out.println(path.toAbsolutePath());Common methods include getFileName(), getParent(), getRoot(), toAbsolutePath(), normalize(), resolve(), and relativize().
Explain the difference between absolute paths and relative paths in Java. How can the Path interface convert one form into the other?
Answer:
An absolute path specifies the complete location of a file or directory from the root of the file system. A relative path specifies a location in relation to the current working directory.
Example:
Path relative = Path.of("data", "input.txt");
Path absolute = relative.toAbsolutePath();
System.out.println(relative);
System.out.println(absolute);Differences:
- An absolute path is independent of the current working directory.
- A relative path depends on the current working directory.
- Absolute paths normally begin with a root such as
/on Unix-like systems or a drive letter on Windows. - Relative paths are generally more portable for application resources.
The toAbsolutePath() method converts a relative path into an absolute path. The toRealPath() method can additionally resolve symbolic links and verify that the path exists.
Describe the path manipulation methods resolve(), relativize(), and normalize() provided by the Path interface.
Answer:
The Path interface provides several methods for constructing and simplifying paths.
resolve()combines a base path with another path.
Path base = Path.of("/home/user");
Path result = base.resolve("notes/file.txt");The result is /home/user/notes/file.txt.
relativize()calculates the path needed to travel from one path to another.
Path start = Path.of("/home/user");
Path target = Path.of("/home/user/docs/file.txt");
Path relative = start.relativize(target);The result is docs/file.txt.
normalize()removes redundant elements such as.and...
Path path = Path.of("docs/./java/../notes");
Path normalized = path.normalize();These methods simplify platform-independent path construction and navigation.
Explain how the Files class is used to test the properties of files and directories in Java NIO.2.
Answer:
The Files class in java.nio.file provides static methods for interacting with files and directories. It can check whether a path exists and determine its type and accessibility.
Frequently used methods:
Files.exists(path)checks whether the path exists.Files.notExists(path)checks whether the path is known not to exist.Files.isRegularFile(path)checks whether the path identifies a normal file.Files.isDirectory(path)checks whether the path identifies a directory.Files.isReadable(path)checks read permission.Files.isWritable(path)checks write permission.Files.isExecutable(path)checks execute permission.Files.isHidden(path)checks whether the path is hidden.
Example:
Path path = Path.of("data.txt");
if (Files.exists(path) && Files.isRegularFile(path)) {
System.out.println("The file exists and is regular.");
}These methods often accept LinkOption.NOFOLLOW_LINKS when symbolic links must not be followed.
Describe the procedures for creating and deleting files and directories using the Files class. Mention important exceptions and precautions.
Answer:
The Files class provides methods for creating and deleting file-system objects.
Creating objects:
Files.createFile(path)creates an empty file.Files.createDirectory(path)creates one directory.Files.createDirectories(path)creates the directory and any missing parent directories.
Deleting objects:
Files.delete(path)deletes the file or directory and throws an exception if it does not exist.Files.deleteIfExists(path)deletes the object only when it exists.
Example:
Path directory = Path.of("reports/2025");
Files.createDirectories(directory);
Path file = directory.resolve("summary.txt");
Files.createFile(file);
Files.deleteIfExists(file);Important exceptions:
IOExceptionfor general I/O failures.FileAlreadyExistsExceptionwhen creating an existing object.NoSuchFileExceptionwhen deleting a missing object withdelete().DirectoryNotEmptyExceptionwhen deleting a non-empty directory.
A directory must normally be emptied before it is deleted.
Explain how to copy and move files or directories using Files.copy() and Files.move(). Discuss the role of standard copy options.
Answer:
The Files.copy() method copies a file or directory from a source path to a target path. The Files.move() method changes its location or name.
Example:
Path source = Path.of("input.txt");
Path backup = Path.of("backup/input.txt");
Files.copy(source, backup, StandardCopyOption.REPLACE_EXISTING);
Path archived = Path.of("archive/input.txt");
Files.move(backup, archived, StandardCopyOption.REPLACE_EXISTING);Important options:
StandardCopyOption.REPLACE_EXISTINGreplaces the target if it exists.StandardCopyOption.COPY_ATTRIBUTESattempts to copy file attributes.StandardCopyOption.ATOMIC_MOVErequests an atomic move when supported by the file system.
By default, copying an existing target causes FileAlreadyExistsException. Moving a directory does not automatically move all of its contents in every situation, so recursive processing may be required. These operations can throw IOException and other file-system exceptions.
Explain how the Stream API can be used with NIO.2 to list, walk, and process files in a directory tree.
Answer:
NIO.2 integrates with the Stream API through methods such as Files.list(), Files.walk(), and Files.find().
Files.list(path)returns a stream of entries directly inside a directory.Files.walk(path)returns a stream that recursively visits the directory tree.Files.find()searches recursively using a predicate and a file attribute condition.
Example:
try (Stream<Path> files = Files.walk(Path.of("src"))) {
files.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".java"))
.forEach(System.out::println);
}The stream must be closed, so it should be used in a try-with-resources statement. Stream operations such as filter(), map(), sorted(), and forEach() make file processing concise and declarative. I/O failures are reported through IOException or an UncheckedIOException depending on the operation.
Compare Files.list(), Files.walk(), and Files.find(). State the situations in which each method is most appropriate.
Answer:
| Method | Scope | Main purpose |
|---|---|---|
Files.list() |
Immediate directory entries only | Listing files and subdirectories in one directory |
Files.walk() |
Recursive directory tree | Processing every entry below a starting path |
Files.find() |
Recursive directory tree | Searching entries using a predicate and file attributes |
Examples of use:
- Use
Files.list()to display the contents of a single folder. - Use
Files.walk()to calculate the total number of files in a project tree. - Use
Files.find()to locate regular files larger than a specified size or files modified after a particular date.
All three methods return streams that should be closed. They may follow symbolic links only when the appropriate FileVisitOption is supplied. Recursive operations must also be used carefully because very large directory trees can consume significant resources.
Describe the layout and major components of the JDBC API. Explain the roles of DriverManager, Connection, Statement, PreparedStatement, CallableStatement, and ResultSet.
Answer:
JDBC, or Java Database Connectivity, is a standard API for communicating with relational databases. It separates Java application code from database-specific driver implementations.
Major components:
DriverManagermanages registered JDBC drivers and establishes database connections.Connectionrepresents an active session with a database and manages transactions.Statementexecutes simple static SQL statements.PreparedStatementrepresents precompiled SQL with parameter placeholders and is preferred for user-supplied values.CallableStatementinvokes stored procedures.ResultSetrepresents tabular data returned by a query and provides a cursor for reading rows.SQLExceptionreports database and driver errors.
The normal flow is to obtain a Connection, create a statement object, execute SQL, process the result, and close all resources.
Explain the steps involved in connecting a Java application to a database using a JDBC driver.
Answer:
A Java application generally follows these steps:
- Include the appropriate JDBC driver dependency in the project.
- Specify the database URL, username, and password.
- Load or allow automatic discovery of the JDBC driver.
- Call
DriverManager.getConnection(). - Use the returned
Connectionto execute SQL. - Close the connection and related resources.
Example:
String url = "jdbc:postgresql://localhost:5432/school";
String user = "appuser";
String password = "secret";
try (Connection connection = DriverManager.getConnection(url, user, password)) {
System.out.println("Database connection established.");
}Modern JDBC drivers are discovered automatically through the service-provider mechanism. Older applications may explicitly call Class.forName() to load the driver class. Connection failures should be handled using SQLException.
What is a JDBC URL? Explain its structure and describe the information it provides to the JDBC driver.
Answer:
A JDBC URL is a string that identifies the database to which a Java application wants to connect. It is passed to DriverManager.getConnection().
A common structure is:
jdbc:subprotocol:subnameFor a network database, it may contain the server, port, database name, and connection properties:
jdbc:mysql://localhost:3306/college?useSSL=falseParts of the URL:
jdbcidentifies the JDBC protocol.- The subprotocol identifies the database vendor or driver type.
- The subname contains vendor-specific details such as host, port, and database name.
- Optional properties configure behavior such as encryption, timeouts, or character encoding.
The JDBC driver examines the URL and determines whether it can handle the request. A malformed or unsupported URL can cause a connection error.
Explain how SQL queries are submitted and how results are obtained using JDBC. Include the difference between executeQuery(), executeUpdate(), and execute().
Answer:
JDBC provides different execution methods according to the kind of SQL statement.
executeQuery()is used for statements that return a result set, normallySELECT. It returns aResultSet.executeUpdate()is used forINSERT,UPDATE, andDELETEstatements, as well as some DDL statements. It returns the number of affected rows.execute()is used when the statement may return either a result set or an update count. It returns a Boolean indicating whether the first result is aResultSet.
Example:
String sql = "SELECT id, name FROM students";
try (PreparedStatement statement = connection.prepareStatement(sql);
ResultSet result = statement.executeQuery()) {
while (result.next()) {
int id = result.getInt("id");
String name = result.getString("name");
}
}The ResultSet cursor initially points before the first row. Calling next() advances it and returns true when a row is available.
Explain the structure and navigation of a JDBC ResultSet. How are column values retrieved from it?
Answer:
A ResultSet represents rows returned by a database query. It contains a cursor that moves through the rows.
Navigation:
- The cursor initially points before the first row.
next()moves to the next row.previous()moves backward when supported.first()andlast()move to boundary rows for scrollable result sets.absolute()moves to a specified row when supported.
Retrieving values:
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
Date date = resultSet.getDate("enrollment_date");
}Values can be retrieved by column label or column index. Common methods include getInt(), getLong(), getString(), getBoolean(), getDate(), and getObject(). The ResultSetMetaData interface provides information about column names, types, and counts.
Why is PreparedStatement preferred over Statement for parameterized SQL? Explain its security and performance advantages with an example.
Answer:
PreparedStatement represents SQL containing parameter placeholders. Values are supplied separately using setter methods.
Example:
String sql = "SELECT id, name FROM students WHERE department = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, "Computer Science");
try (ResultSet result = statement.executeQuery()) {
while (result.next()) {
System.out.println(result.getString("name"));
}
}
}Advantages:
- It helps prevent SQL injection because values are bound separately from SQL syntax.
- The database may reuse the compiled execution plan.
- It handles type conversion through methods such as
setInt(),setString(), andsetDate(). - It improves readability and avoids manual string concatenation.
- It is suitable for repeated execution with different parameter values.
Statement is appropriate mainly for trusted, fixed SQL that has no parameters.
Explain how JDBC driver information can be specified externally. Discuss the use of configuration files, environment variables, and system properties.
Answer:
JDBC connection information should generally be kept outside the source code so that the same application can run in different environments and sensitive credentials are easier to manage.
External configuration may contain:
- JDBC URL.
- Database username.
- Database password.
- Driver-specific options.
- Connection pool settings.
Example using a properties file:
Properties properties = new Properties();
try (InputStream input = Files.newInputStream(Path.of("db.properties"))) {
properties.load(input);
}
try (Connection connection = DriverManager.getConnection(
properties.getProperty("db.url"), properties)) {
// Use the connection.
}Environment variables and system properties can also be read using System.getenv() and System.getProperty(). External configuration improves portability, but passwords must be protected through secret managers, restricted file permissions, or deployment-specific credential mechanisms.
Describe the JDBC transaction model. Explain auto-commit, commit(), rollback(), and the importance of transactions during CRUD operations.
Answer:
A transaction is a group of database operations treated as one logical unit. It helps preserve consistency when several operations must succeed or fail together.
By default, a JDBC connection usually operates in auto-commit mode. Each SQL statement is committed automatically after execution.
For a controlled transaction:
try {
connection.setAutoCommit(false);
// Execute related INSERT, UPDATE, or DELETE statements.
connection.commit();
} catch (SQLException exception) {
connection.rollback();
throw exception;
} finally {
connection.setAutoCommit(true);
}setAutoCommit(false)begins manual transaction control.commit()permanently saves changes.rollback()cancels changes made during the current transaction.
Transactions are essential when partial updates could produce invalid data, such as transferring money from one account to another.
Explain how to implement the Create, Read, Update, and Delete operations using JDBC. Provide representative SQL and JDBC methods for each operation.
Answer:
CRUD operations correspond to the main data manipulation operations in a relational database.
- Create: Add a new row with
INSERTand execute it usingexecuteUpdate().
String sql = "INSERT INTO students(name, department) VALUES (?, ?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, "Anita");
ps.setString(2, "Physics");
ps.executeUpdate();- Read: Retrieve rows with
SELECTand process the returnedResultSetusingexecuteQuery(). - Update: Modify existing rows with
UPDATE, bind parameters, and callexecuteUpdate(). - Delete: Remove rows with
DELETE, bind a condition value, and callexecuteUpdate().
Each operation should use parameterized SQL, check the affected-row count where appropriate, handle SQLException, and close statements using try-with-resources.
Explain JDBC resource management using try-with-resources. Why should Connection, Statement, and ResultSet objects be closed?
Answer:
JDBC objects consume external resources such as network connections, database cursors, and driver buffers. Failing to close them can cause resource leaks, connection exhaustion, and poor application performance.
The JDBC interfaces Connection, Statement, and ResultSet implement AutoCloseable, so they can be managed using try-with-resources.
String sql = "SELECT id, name FROM students";
try (Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet result = statement.executeQuery()) {
while (result.next()) {
System.out.println(result.getString("name"));
}
} catch (SQLException exception) {
exception.printStackTrace();
}Resources are closed automatically in reverse order. This approach is safer than manually closing resources in a finally block and also preserves exceptions that occur during resource cleanup.
Distinguish between Statement, PreparedStatement, and CallableStatement in JDBC.
Answer:
| Interface | Purpose | Parameters | Typical use |
|---|---|---|---|
Statement |
Executes static SQL | No parameter binding | Fixed, trusted SQL |
PreparedStatement |
Executes precompiled parameterized SQL | Uses ? placeholders |
Secure CRUD operations |
CallableStatement |
Calls stored procedures and functions | Supports input and output parameters | Database-side business logic |
Examples:
Statement s = connection.createStatement();
PreparedStatement p = connection.prepareStatement(
"SELECT * FROM students WHERE id = ?");
CallableStatement c = connection.prepareCall(
"{call calculate_grade(?, ?)}");PreparedStatement is usually preferred for dynamic values because it improves security and may improve performance. CallableStatement extends the capabilities of PreparedStatement for stored procedure calls and supports registering output parameters.
What is JDBC metadata? Explain the purpose of DatabaseMetaData and ResultSetMetaData.
Answer:
Metadata is information about the database, its structures, or the results returned by a query.
DatabaseMetaDataprovides information about the database and JDBC driver, including the database product name, supported SQL features, tables, columns, transaction support, and driver version.
DatabaseMetaData meta = connection.getMetaData();
System.out.println(meta.getDatabaseProductName());
System.out.println(meta.getDriverVersion());ResultSetMetaDataprovides information about columns in a query result, including column count, names, labels, SQL types, precision, and nullability.
ResultSetMetaData meta = resultSet.getMetaData();
int count = meta.getColumnCount();
for (int i = 1; i <= count; i++) {
System.out.println(meta.getColumnName(i));
}Metadata is useful for database tools, generic reporting systems, diagnostics, and dynamic applications.
Define the Path interface in Java NIO.2. Explain how it is used to represent and operate on file and directory paths, with suitable examples.
Answer:
The Path interface, available in the java.nio.file package, represents a path to a file or directory in a file system. It provides methods for examining and manipulating paths without directly accessing the file contents.
Important features:
- A
Pathcan represent an absolute or relative path. - It is platform-independent and adapts to the operating system.
- It can be created using
Paths.get()orPath.of(). - It supports operations such as resolving, normalizing, and comparing paths.
Example:
Path path = Path.of("documents", "report.txt");
System.out.println(path.getFileName());
System.out.println(path.getParent());
System.out.println(path.toAbsolutePath());Common methods include getFileName(), getParent(), getRoot(), toAbsolutePath(), normalize(), resolve(), and relativize().
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →