Java Networking Interview Questions in Java

List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.

Java Networking Interview Questions in Java

Question 1.
What are Datagrams and Sockets?
Answer:
A socket represents a connection point into a TCP/IP network between two computers; one of which is the server and the other is the client. Sockets are used to access the Web server. These sockets are available in the Java Socket class. Sockets act as virtual passageways for communication through which the data travels from one host to another. Sockets are of two types, connection-oriented or connectionless. The connection-oriented socket operates similarly to a telephone where the connection is established prior to the transmission of data. The second type of socket is the connectionless socket. This type of socket is called a Datagram. This socket operates similarly to the mail. A characteristic of the Datagram is that it allows only one message to be sent at a time. The delivery of data is not guaranteed because Datagrams use the UDP protocol.

Question 2.
What’s the Factory Method?
Answer:
Factory methods are merely a convention whereby static methods in a class return an instance of that class. The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. In InetAddress the three methods getLocalHost, getByName, getByAllName can be used to create instances of InetAddress.

Question 3.
What’s the difference between TCP and UDP?
Answer:
These two protocols differ in the way they carry out the action of communicating. A TCP protocol establishes a two-way connection between a pair of computers, while the UDP protocol is a one-way message sender. The common analogy is that TCP is like making a phone call and carrying on two-way communication, while UDP is like mailing a letter.

Question 4.
What is the Proxy Server?
Answer:
A proxy server speaks the client side of a protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. And when several users are hitting a popular website, a proxy server can get the contents of the web server’s popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients. Also, we can get multiple connections for a single server.

Question 5.
What are the seven layers of the OSI model?
Answer:
Application
Presentation
Session
Transport
Network
DataLink
Physical Layer.

Question 6.
What Transport Layer does?
Answer:
It ensures that the mail gets to its destination. If a packet fails to get its destination, it handles the process of notifying the sender and requesting that another packet be sent.

Question 7.
What is DHCP?
Answer:
Dynamic Host Configuration Protocol, a piece of the TCP/IP protocol suite that handles the automatic assignment of IP addresses to clients.

Question 8.
What is SMTP?
Answer:
Simple Mail Transmission Protocol, the TCP/IP Standard for Internet mails. SMTP exchanges mail between servers; contrast this with POP, which transmits mail between a server and a client.

Question 9.
In OSI N/W architecture, the dialogue control and token management are responsibilities of which layer?
Answer:
b) Session Layer.

Question 10.
In OSI N/W Architecture, the routing is performed by which layer?
Answer:
Network Layer.

Question 11.
What is the difference between URL instances and URLConnection instances?
Answer:
A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location.

Question 12.
How do I make a connection to the URL?
Answer:
You obtain a URL instance and then invoke openConnection on it. URLConnection is an abstract class, which means you can’t directly create instances of it using a constructor. We have to invoke the openConnection method on a URL instance, to get the right kind of connection for your URL.

Question 13.
What Is a Socket?
Answer:
A socket is one end-point of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes-Socket and ServerSocket–which implement the client-side of the connection and the server-side of the connection, respectively.

Question 14.
What information is needed to create a TCP Socket?
Answer:
The Local System’s IP Address and Port Number. And the Remote System’s IPAddress and Port Number.

Question 15.
what are the two important TCP Socket classes?
Answer:
Socket and ServerSocket.
ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets.
getlnputStream( ) and getOutputStream( ) are the two methods available in Socket class.

Question 16.
When MalformedURLException and UnknownHostException throws?
Answer:
When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress’ methods getByName and getLocalHost are unable to resolve the hostname they throw an UnknownHostException.

Question 17.
Define Network Programming?
Answer:
It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

Question 18.
What is a Socket?
Answer:
Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

Question 19.
Advantages of Java Sockets?
Answer: Sockets are flexible and sufficient. Efficient socket-based programming can be easily implemented for general communications. It causes low network traffic.

Question 20.
Disadvantages of Java Sockets?
Answer:
Socket-based communications allow only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Question 21.
Which class is used by server applications to obtain a port and listen for client requests?
Answer:
java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests.

Question 22.
Which class represents the socket that both the client and server use to communicate with each other?
Answer:
java.net.Socket class represents the socket that both the client and server use to communicate with each other.

Question 23.
How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
Answer:
By InetAddress.getByName(“192.18.97.39”).getHostName( ) where 192.18.97.39 is the IP address.

Question 24.
How do I get the IP address of a machine from its hostname?
Answer:
The InetAddress class is able to resolve IP addresses for you. Obtain an instance of InetAddress for the machine, and call the get host address( ) method, which returns a string in the xxx.xxx.xxx.xxx address form.

InetAddress inet = InetAddress.getByNameC“www.davidreilly.com”); 
System.out.println (“IP: “ + inet.getHostAddress( )) ;

Question 25.
How do I perform a hostname lookup for an IP address?
Answer:
The InetAddress class contains a method that can return the domain name of an IP address. You need to obtain an InetAddress class and then call its get hostname( ) method. This will return the hostname for that IP address. Depending on the platform, a partial or a fully qualified hostname may be returned.

InetAddress inet = InetAddress.getByName(“209.204.220.121”); 
system. out.println (“Host: “ + inet.get hostname( ));

Question 26.
How can I find out who is accessing my server?
If you’re using a DatagramSocket, every packet that you receive will contain the address and port from which it was sent.

DatagramPacket packet = null;
// Receive next packet 
myDatagramsocket.receive (packet);
// Print address + port
system.out.println (“Packet From: “ + packet.getAddress( ). 
getHostAddress( ) + ' : ’ + packet. getPort( ));

If you’re using a ServerSocket, then every socket connection you accept will contain similar information. The Socket class has a getlnetAddress( ) and getPort( ) method which will allow you to find the same information.

socket mysock = myServersocket.accept( );
// Print address + port
System.out.println (“connection From: “ + mySock.getlnetAddress( ). 
getHostAddress( ) + ‘:’ + mysock. getPort( ));

27. How can I find out the current IP address for my machine?
Answer:
The InetAddress has a static method called get localhost( ) which will return the current address of the local machine. You can then use the getHostAddressO method to get the IP address.

InetAddress local = InetAddress.getLocalHost( );
// print address
System.out.println (“Local IP: “ + local .getHostAddress( ));

Question 28.
Why can’t my applet connect via sockets, or bind to a local port?
Applets are subject to heavy security constraints when executing under the control of a browser. Applets are unable to access the local file system, bind to local ports, or connect to a computer via sockets other than the computer from which the applet is loaded. While it may seem to be an annoyance for developers, there are many good reasons why such tight constraints are placed on applets. Applets could bind to well-known ports, and service network clients without authorization or consent. Applets executing within firewalls could obtain privileged information, and then send it across the network.

Applets could even be infected by viruses, such as the Java StrangeBrew strain. Applets might become infected without an applet author’s knowledge and then send information back that might leave hosts vulnerable to attack.

Signed applets may be allowed greater freedom by browsers than unsigned applets, which could be an option. In cases where an applet must be capable of network communication, HTTP can be used as a communication mechanism. An applet could communicate via java.net.URLConnection with a CGI script or a Java servlet. This has an added advantage – applets that use the URLConnection will be able to communicate through a firewall.

Question 29.
What are socket options, and why should I use them?
Socket options give developers greater control over how sockets behave. Most socket behavior is controlled by the operating system, not Java itself, but as of JDKl.l, you can control several socket options, including SOJTIMEOUT, SO_LINGER, TCP_ NODELAY, SO.RCVBUF and SO_SNDBUF.
These are advanced options, and many programmers may want to ignore them. That’s OK, but be aware of their existence for the future. You might like to specify a timeout for reading operations, to control the amount of time a connection will linger for before a reset is sent, whether Nagle’s algorithm is enabled/disabled, or the send and receive buffers for datagram sockets.

Question 30.
How do I display more than one page from an applet?
The show document method of the AppletContext interface is overloaded – meaning that it can accept more than one parameter. It can accept a second parameter, which represents the name of the browser window that should display a page.
For example,
myAppletContext.show document (myurl, “frame 1”) will display the document in frame 1. If there exists no window named frame 1, then a brand new window will be created.

Question 31.
How do I use a proxy server for HTTP requests?
When a Java applet under the control of a browser (such as Netscape or Internet Explorer) fetches content via an URLConnection, it will automatically and transparently use the proxy settings of the browser.
If you’re writing an application, however, you’ll have to manually specify the proxy server settings. You can do this when running a Java application or you can write code that will specify proxy settings automatically for the user (providing you allow the users to customize the settings to suit their proxy servers).
To specify proxy settings when running an application, use the -D parameter:

jre -DproxySet=true -DproxyHost=myhost -DproxyPort=myport MyApp

Alternately, your application can maintain a configuration file, and specify proxy settings before using an URLConnection:

// Modify system properties
Properties sysProperties = System.getProperties( );
 // Specify proxy settings
sysProperties.put(“proxyHost”, “myhost”);
 sysProperties.put(“proxyPort”, “myport”); 
sysProperties.put(“proxySet”, “true”);

Question 32.
What is a malformed URL, and why is it exceptional?
When you create an instance of the java.net.URL class, its constructor can throw a MalformedURLException. This occurs when the URL is invalid. When it is thrown, it isn’t because the host machine is down, or the URL path points to a missing file; a malformed URL exception is thrown when the URL cannot be correctly parsed. Common mistakes include:-

  • leaving out a protocol (eg “www.microsoft.com” instead of “http://www.microsoft. com/”)
  • specifying an invalid protocol (eg “www://netscape.com”)
  • leaving out the character (eg http//www.micrsoft.com/)

MalformedURLException will not be thrown if:-

  • the hostname is invalid (eg “www.microsoft-rules-the-world.com”)
  • the path is invalid (eg “http://www.microsoft.com/company_secrets.htm”)

Question 33.
Why is a security exception thrown when using java.net.URL or java.net. URLConnection from an applet?
Answer:
Web browsers impose security restrictions on applets, which prevent applets from establishing network connections to servers other than that from which they were loaded. Like socket connections, HTTP connections will cause security exceptions to be thrown. If you absolutely, positively, have to access other hosts (and replacing your applet with a Java servlet is impractical), consider using a digitally signed applet.

Question 34.
How do I prevent caching of HTTP requests?
Answer:
By default, caching will be enabled. You must use a URLConnection, rather than the URL.openStreamO method, and explicitly specify that you do not want to cache the requests. This is achieved by calling the URLConnection.setup caches (boolean) method with a value of false.

Question 35.
What’s the Factory Method?
Answer:
Factory methods are merely a convention whereby static methods in a class return an instance of that class. The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. In InetAddress the three methods getLocalHost, getByName, getByAllName can be . used to create instances of InetAddress.

Question 36.
What’s the difference between TCP and UDP?
Answer:
These two protocols differ in the way they carry out the action of communicating. A TCP protocol establishes a two-way connection between a pair of computers, while the UDP protocol is a one-way message sender. The common analogy is that TCP is like making a phone call and carrying on two-way communication, while UDP is like mailing a letter.

Question 37.
What is the Proxy Server?
Answer:
A proxy server speaks the client side of a protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. And when several users are hitting a popular website, a proxy server can get the contents of the web server’s popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients. Also, we can get multiple connections for a single server.

Question 38.
How do I make a connection to the URL?
Answer:
You obtain a URL instance and then invoke open Connection on it. URLConnection is an abstract class, which means you can’t directly create instances of it using a constructor. We have to invoke the openConnection method on a URL instance, to get the right kind of connection for your URL.
E.g.

URL url;
URLConnection connection; 
try{ url = new URL(“...”); 
conection = url.openConnection( );
} catch (MaiFormedURLException e) {  }

Question 39.
When MalformedURLException and UnknownHostException throw?
Answer:
When the specified URL is not connected then the URL throw Malforme- dURLExceptiop and If InetAddress’ methods
getByName( ) and getLocalHost( ) are unable to resolve the host name they throw an UnknownHostException.

Question 40.
What are the two important TCP Socket classes?
Answer:
Socket and ServerSocket.
ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets.
getlnputStream( ) and getOutputStream( ) are the two methods available in the Socket class.