Text Box: Share on
Facebook
Google+
Linked in
Email
Copyright © 3S Technologies

Email: info@3s-technologies.com

Best viewed in Internet Explorer ver. 9.0 - 1024 X 768 resolution.

Java Objectives - Part 11

The reason for documenting this topic is to provide important technical questions and answers on Java language.  These questions can appear in an aptitude test, organized by different recruiting IT organizations.

 

Some questions and answers on Networking and its use in Java:

 

1) The API doesn't list any constructors for InetAddress- How do I create an InetAddress instance?

ANS: In case of InetAddress the three methods getLocalHost, getByName, getByAllName can be used to create instances.

E.g.

InetAddress add1;

InetAddress add2;

try{

add1 = InetAddress.getByName("java.sun.com");

add2 = InetAddress.getByName("199.22.22.22");

}catch(UnknownHostException e){}

 

2) Is it possible to get the Local host IP?

ANS: Yes. Use InetAddress's getLocalHost method.

 

3) What's the Factory Method?

ANS: 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.

 

4) What’s the difference between TCP and UDP?

ANS: 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 a two-way communication, while UDP is like mailing a letter.

 

5) What is the Proxy Server?

ANS: 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 web site, 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.

 

6) What are the seven layers of OSI model?

ANS: Application, Presentation, Session, Transport, Network, Data-Link, Physical Layer.

 

7) What Transport Layer does?

ANS: It ensures that the mail gets to its destination. If a packet fails to get to its destination, it handles the process of notifying the sender and requesting that another packet be sent.

 

8) What is DHCP?

ANS: Dynamic Host Configuration Protocol, a piece of the TCP/IP protocol suite that handles the automatic assignment of IP addresses to clients.

 

9) What is SMTP?

ANS: 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.

 

10) In OSI N/w architecture, the dialogue control and token management are responsibilities of...

a) Network layer

b) Session layer

c) Application layer

d) Data-Link layer

ANS: b

 

11) In OSI N/W Architecture, the routing is performed by ______

a) Network layer

b) Session layer

c) Application layer

d) Data-Link layer

Ans: a

 

12) What is the difference between URL instance and URLConnection instance?

ANS: 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.

 

13) How do I make a connection to URL?

ANS: 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 openConnection method on a URL instance, to get the right kind of connection for your URL.

Eg. URL url;

URLConnection connection;

try{ url = new URL("...");

conection = url.openConnection();

}catch (MalFormedURLException e) { }

 

14) What Is a Socket?

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.

 

15) What information is needed to create a TCP Socket?

ANS: The Local System’s IP Address and Port Number.

And the Remote System's IP Address and Port Number.

 

16) What are the two important TCP Socket classes?

ANS: Socket and ServerSocket.

ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets.

getInputStream() and getOutputStream() are the two methods available in Socket class.

 

17) When MalformedURLException and UnknownHostException throws?

ANS: When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress’ methods getByName and getLocalHost are unable to resolve the host name they throw an UnknownHostException.

 

 

Some questions and answers on Java Servlets:

 

1) What is the servlet?

Ans: Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.

Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

 

2) Whats the advantages using servlets than using CGI?

Ans: Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.

 

3) What are the uses of Servlets?

Ans: A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing.

Servlets can forward requests to other servers and servlets.Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

 

4) Which pakage provides interfaces and classes for writing servlets?

Ans: javax

 

5) Whats the Servlet Interfcae?

Ans: The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.

Servlets-->Generic Servlet-->HttpServlet-->MyServlet.

The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

 

6) When a servlet accepts a call from a client, it receives two objects- What are they?

Ans: ServeltRequest: Which encapsulates the communication from the client to the server.

ServletResponse: Whcih encapsulates the communication from the servlet back to the client.

ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

 

7) What information that the ServletRequest interface allows the servlet access to?

Ans: Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it.

The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

 

8) What information that the ServletResponse interface gives the servlet methods for replying to the client?

Ans: It Allows the servlet to set the content length and MIME type of the reply.

Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

 

9) What is the servlet Lifecycle?

Ans: Each servlet has the same life cycle:

A server loads and initializes the servlet (init())

The servlet handles zero or more client requests (service())

The server removes the servlet (destroy())

(some servers do this step only when they shut down)

 

10) How HTTP Servlet handles client requests?

Ans: An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request. 1

 

 

Some questions and answers on JDBC:

 

1) What are the steps involved in establishing a connection?

Ans: This involves two steps:

(1) loading the driver

(2) making the connection.

 

2) How can you load the drivers?

Ans: Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:

Eg.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:

Eg.

Class.forName("jdbc.DriverXYZ");

 

3) What Class.forName will do while loading drivers?

Ans: It is used to create an instance of a driver and register it with the DriverManager.

When you have loaded a driver, it is available for making a connection with a DBMS.

 

4) How can you make the connection?

Ans: In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:

Eg.

String url = "jdbc:odbc:Fred";

Connection con = DriverManager.getConnection(url, "Fernanda", "J8");

 

5) How can you create JDBC statements?

Ans: A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate.

Eg.

It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt :

Statement stmt = con.createStatement();

 

6) How can you retrieve data from the ResultSet?

Ans: Step 1.

JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

Eg.

ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

Step2.

String s = rs.getString("COF_NAME");

The method getString is invoked on the ResultSet object rs , so getString will retrieve (get) the value stored in the column COF_NAME in the current row of rs

 

7) What are the different types of Statements?

Ans: 1.Statement (use createStatement method) 2. Prepared Statement (Use prepareStatement method) and 3. Callable Statement (Use prepareCall)

 

8) How can you use PreparedStatement?

Ans: This special type of statement is derived from the more general class, Statement.If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead.

The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.

Eg.

PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

 

9) What setAutoCommit does?

Ans: When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode

Eg.

con.setAutoCommit(false);

Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.

Eg.

con.setAutoCommit(false);

PreparedStatement updateSales = con.prepareStatement(

"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

updateSales.setInt(1, 50);

updateSales.setString(2, "Colombian");

updateSales.executeUpdate();

PreparedStatement updateTotal = con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");

updateTotal.setInt(1, 50);

updateTotal.setString(2, "Colombian");

updateTotal.executeUpdate();

con.commit();

con.setAutoCommit(true);

 

10) How to call a Strored Procedure from JDBC?

Ans: The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection

object. A CallableStatement object contains a call to a stored procedure;

Eg.

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");

ResultSet rs = cs.executeQuery();

 

11) How to Retrieve Warnings?

Ans: SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned.

A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

Eg.

SQLWarning warning = stmt.getWarnings();

if (warning != null) {

System.out.println("\n---Warning---\n");

while (warning != null) {

System.out.println("Message: " + warning.getMessage());

System.out.println("SQLState: " + warning.getSQLState());

System.out.print("Vendor error code: ");

System.out.println(warning.getErrorCode());

System.out.println("");

warning = warning.getNextWarning();

}

}

 

12) How can you Move the Cursor in Scrollable Result Sets ?

Ans: One of the new features in the JDBC 2.0 API is the ability to move a result set's cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor.

Eg.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_READ_ONLY);

ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE .

The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE . The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order.

Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY

 

13) What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?

Ans: You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened

Eg.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

srs.afterLast();

while (srs.previous()) {

String name = srs.getString("COF_NAME");

float price = srs.getFloat("PRICE");

System.out.println(name + " " + price);

}

 

14) How to Make Updates to Updatable Result Sets?

Ans: Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.

Eg.

Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

ResultSet uprs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

3S Technologies

Online Education for all