πŸŽ“ BookMCQ
← Back to 25. Introduction to Application Layer

πŸ“ 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.
2
Easy
5
Medium
3
Hard

πŸ“ 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?

A.java.net.Socket
B.java.net.InetAddress βœ…
C.java.io.File
D.java.util.ArrayList
πŸ’‘ Difficulty: easy | βœ… Correct: B

πŸ“– 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?

A.The program will continue to the next statement
B.The current iteration of a loop will be skipped
C.The program will terminate with an error message βœ…
D.The runtime will automatically retry the connection
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– 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)?

A.getByName returns a single InetAddress object, while getAllByName returns an array of all possible addresses βœ…
B.getByName performs a DNS lookup, getAllByName does not
C.getByName returns only IPv4 addresses, getAllByName returns both IPv4 and IPv6
D.getByName throws a checked exception, getAllByName does not
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– 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?

A.while((bytesRead = in.read(buf)) > 0) {...}
B.while((bytesRead = in.read(buf)) != -1) {...} βœ…
C.do { bytesRead = in.read(buf); } while(bytesRead == 0);
D.for(int i=0;i<buf.length;i++) { in.read(buf,i,1); }
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– 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

A.Hello βœ…
B.Hello followed by a newline character
C.No output, because readLine() returns null immediately
D.An exception is thrown due to closed socket
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– 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?

A.BufferedReader automatically parses integers
B.BufferedReader provides built-in line‑oriented reading, reducing manual buffer management
C.DataInputStream supports UTF‑8 encoding while BufferedReader does not
D.BufferedReader prevents all IOException occurrences βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– 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?

A.for(int i=0;i<3;i++) { Thread.sleep(1000); new Socket(host,port); } βœ…
B.while(attempts++ < 3) { try { new Socket(host,port); break; } catch(IOException e) { Thread.sleep(1000); } }
C.do { new Socket(host,port); } while(true);
D.int retries = 0; try { new Socket(host,port); } catch(IOException e) { retries++; }
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– 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?

A.The new data will overwrite the old data correctly
B.The new data will be appended after the previous data, causing corrupted output βœ…
C.The program will throw an ArrayIndexOutOfBoundsException immediately
D.The socket will automatically clear the buffer
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– 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?

A.IPv4 addresses are stored in Inet4Address, IPv6 in Inet6Address, but both are returned as InetAddress references βœ…
B.IPv4 is not supported by InetAddress, only IPv6 is
C.InetAddress automatically converts IPv6 to IPv4 if possible
D.IPv6 addresses require a separate library, unlike IPv4
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– 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?

A.Because the loop consumes excessive CPU time, preventing other threads from obtaining CPU slices βœ…
B.Because iterative loops automatically lock the entire JVM
C.Because Java's garbage collector pauses threads during I/O
D.Because iterative loops disable thread scheduling
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– 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.

πŸ”— Related Topics (MCQs)