π Iterative Programming in Java (10 MCQs)
Repeated Network Operations with Java Socket Classes
Java network programs can use loops to serve successive clients or exchange repeated application messages. The java.net package provides classes such as Socket, ServerSocket, DatagramSocket, and DatagramPacket. These classes wrap common networking operations, while Java streams or packet objects expose data to the application for processing. The loop structure determines whether clients are handled sequentially or concurrently in practice.
Socket Objects, Streams and Packet Containers
A TCP Socket provides input and output streams for an ordered byte stream, and ServerSocket accepts incoming connections. UDP communication uses DatagramSocket with DatagramPacket objects containing payload data and endpoint information. Java object methods simplify resource handling, but applications still need correct message framing, buffer sizing, and error management. The programmer chooses how application records are encoded and separated.
Looping Through Accept or Receive Operations
A TCP server repeatedly calls accept, handles the returned client Socket, and closes it before accepting another. A UDP server repeatedly receives into a DatagramPacket, processes its payload and sender address, then sends a reply. Both loops continue until the service is stopped or an unrecoverable error occurs. The selected transport determines whether each receive preserves a message boundary.
Java TCP Server Handling Successive Clients
A Java server constructs ServerSocket on port 6300 and enters a loop calling accept. For each returned Socket, it reads a line from the input stream, writes a response through the output stream, and closes the client socket. The ServerSocket remains open so another client can connect. The accept loop resumes only after the current handler finishes or fails.
Exceptions, Resource Scope and Application State
Java networking methods can throw IOException and related exceptions when connections fail, streams close, or data cannot be transferred. try-with-resources can close Socket and stream resources reliably. A sequential handler can still block on a slow client, and Java's object-oriented API does not make the server concurrent automatically. Applications should also distinguish malformed input from ordinary connection termination.
Misconceptions About Java Network Programming
'ServerSocket sends application data' is misleading because accepted Socket streams carry the client exchange. 'One read call returns one complete line' is unsafe unless a reader method explicitly reads through the delimiter. 'Java automatically handles all network errors' ignores checked exceptions and application-level validation. A method call can fail even when the local object was created successfully.
Java Class Roles and Loop Execution
Identify the roles of ServerSocket, Socket, DatagramSocket, and DatagramPacket, then trace which object accepts, sends, or receives data. Explain how stream readers and writers handle text framing, why try-with-resources matters, and where a sequential server blocks. Distinguish API convenience from transport guarantees. Trace object ownership as well as the order of network method calls.
Java Network Programming Class Terms
- ServerSocket - TCP server object that accepts connections.
- Socket - TCP endpoint used by a client or server.
- InputStream - Byte-oriented interface for incoming data.
- OutputStream - Byte-oriented interface for outgoing data.
- DatagramSocket - Java endpoint for sending and receiving UDP.
- try-with-resources - Closes declared resources after the block ends.
π All Iterative Programming in Java MCQs
Q1. Which Java class is primarily used to represent an IP address (both IPv4 and IPv6) in socket programming?
π Explanation: The InetAddress class encapsulates both IPv4 and IPv6 addresses as objects. While Socket represents an endpoint for communication, File handles file I/O, and ArrayList is a generic collection. Therefore, InetAddress is the correct class for representing IP addresses.
Q2. If the call to new Socket(host, port) throws an IOException, what is the most likely behavior of the surrounding code that does not catch the exception?
π Explanation: When an IOException is not caught, it propagates up the call stack, causing the thread to terminate and the JVM to display a stack trace. The program does not automatically skip iterations or retry; it stops execution unless the exception is handled.
Q3. How does InetAddress.getByName(String host) differ from InetAddress.getAllByName(String host)?
π Explanation: getByName resolves the host name to one address, typically the first returned by the DNS resolver, whereas getAllByName returns every address associated with the host in an InetAddress array. Both methods perform DNS lookups and may return IPv4 or IPv6 addresses depending on the system configuration.
Q4. Which pattern correctly implements an iterative read loop that continues until the end of stream is reached?
π Explanation: The condition != -1 signals that the InputStream has reached EOF. Using > 0 would miss cases where zero bytes are read, and the doβwhile loop with bytesRead == 0 could become infinite. The for loop does not correctly handle variable read lengths. Hence, option B is the proper iterative pattern.
Q5. Given the following code snippet, what will be printed if the server sends the string \Hello\ and then closes the connection?\n\nBufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));\nString line;\nwhile((line = br.readLine()) != null) {\n System.out.print(line);\n}\n
π Explanation: readLine() reads characters until it encounters a line terminator or EOF. When the server sends \Hello\ and closes the socket, readLine() returns the string \Hello\ on the first iteration, then null on the next, causing the loop to exit after printing \Hello\.
Q6. What is a key advantage of using BufferedReader over DataInputStream for iterative text-based communication?
π Explanation: BufferedReader offers convenient methods such as readLine() that handle line delimiters and buffering internally, simplifying iterative text processing. While it does not eliminate IOExceptions, it reduces the need for manual byteβarray handling compared to DataInputStream, which reads raw bytes and requires explicit conversion for text data.
Q7. Which construct best implements a retry mechanism that attempts to connect up to three times with a oneβsecond pause between attempts?
π Explanation: The while loop with a tryβcatch inside allows the program to attempt a connection, catch any IOException, pause for one second, and retry until the maximum number of attempts is reached. Option A lacks exception handling, option C creates an infinite loop, and option D does not retry on failure.
Q8. If a programmer forgets to reset the buffer index after processing a received message, what is the most likely result in subsequent reads?
π Explanation: When the buffer index is not reset, subsequent reads continue writing from the previous end position, causing new bytes to be placed after old bytes. This leads to concatenated or garbled messages, making the output incorrect. No automatic exception or clearing occurs.
Q9. How does Java's handling of IPv4 and IPv6 differ when using InetAddress?
π Explanation: InetAddress is the superclass for both Inet4Address and Inet6Address. When a lookup returns an IPv4 address, the runtime creates an Inet4Address instance; for IPv6, it creates an Inet6Address. The reference type remains InetAddress, allowing polymorphic handling of both address families.
Q10. Why can a poorly designed iterative I/O loop cause thread starvation in a multithreaded Java server?
π Explanation: An iterative I/O loop that continuously reads without blocking or yielding can monopolize CPU resources, especially if it polls a socket aggressively. This reduces the time other threads have to execute, leading to thread starvation. Proper use of blocking reads, sleep intervals, or selector mechanisms mitigates this risk.