Owner: Interview Questions In Java And Java EE URL:http://interviewjava.blogspot.com/ Join Date: Fri, 08 Jun 2007 16:46:10 -0500 Rating:0 Site Description: World of tricky Core Java Q&A Covering Object Oriented Analysis and Design,JVM Internals,Java Language Fundamentals(Datatypes,Keywords,Operators and Assignments,Identifies etc.,Declarations and Modifiers,Conversion,Casting and Promotion,Flow control,Asser Site statistics:Click here
Explain Struts1.x in a nutshell? 2007-06-10 07:05:00 Struts is consisted of technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages, like BeanUtils and Chain of Responsibility. It helps one create an extensible development environment for one's application, based on published standards and proven design patterns.Struts FlowWhenever a request comes from web browser then application's controller handles this request.When request is received then Controller invokes an Action class.This Action class object then communicates with Model class(which actually is a set of JavaBeans representation) to examine or update the application's state..The Struts ActionForm class helps in data exchange between Model and View layers.A web application uses 'web.xml', a deployment descriptor to initialize resources like servlets and taglibs. Similarly, Struts uses a configuration file( struts-config.xml) to initialize its own resources. These resources include ActionForms to collect input f
What is Struts and how it helps in web development? 2007-06-10 06:26:00 Apache Struts is a free open-source framework for creating Java web applications.Struts helps in providing dynamism to a web based application in contrast with many websites that deliver only static pages.A web application interacts with databases and business logic engines to customize a response.Struts is based on MVC(Model-View-Controller) architecture based and it clearly segregate business logic from presentation which is somehow difficult to achieve with JavaServer Pages that sometimes mingle database code, page design code, and control flow code. Unless these components are not separated then it becomes quite difficult to maintain in large web based applications. The Model represents the business or database code, the View represents the page design code, and the Controller represents the business logic or navigational code.
How to get count of rows there are in a Result Set? 2007-06-09 16:31:00 There are three ways:- Do a query like "select count
(*) from ... "-If you need all the data, count the rows as you loop through the data:int count = 0;while (rs.next()) { count++; // anything that you like to do here }-If you have a JDBC 3 driver, you can call rs.afterLast() to move to the end and then rs.getRow() to get the row number. This Result
Set MUST have a scrollable cursor. Either ScrollSensitive or Insensitive but it does not work with a Forward Only cursor
Is it must to close all my ResultSets, Statements and Connections? 2007-06-09 16:29:00 This is absolutely necessary and critical to close all the JDBC resources.When you are using JDBC API you are not only allocating resources on Java side but in a database server as well. Failure to properly close ResultSets, Statements (and PreparedStatements and CallableStatements) and Connections can cause -Exhaustion of connections that can be opened or used - No new result sets creation - No execution of any queries of any kind - DB server get very slow - Your program/database server will crash
Differentiate TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE? 2007-06-09 15:43:00 TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction. TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.This needs a small coding effort to verify this differntiation.Any volunteers? Please write in your comments to put your understanding about this concept.
How can a cursor move in scrollable result sets? 2007-06-09 14:35:00 JDBC result sets are created with three properties: type, concurrency and holdability.The type can be one of-TYPE_FORWARD_ONLY-TYPE_SCROLL_INSENSITIVE -TYPE_SCROLL_SENSITIVE. The concurrency can be one of-CONCUR_READ_ONLY-CONCUR_UPDATABLE.The holdability can be one of-HOLD_CURSORS_OVER_COMMIT-CLOSE_CURSORS_AT_COMMIT.JDBC allows the full cross product of these. Some database like SQL 2003 prohibits the combination {TYPE_SCROLL_INSENSITIVE, CONCUR_UPDATABLE}, but this combination is supported by some vendors, notably Oracle.The movable cursors,moving forward and backward on a resultset is one of the new features in the JDBC 2.0 API. There are also methods that let you move the cursor to a particular row and check the position of the cursor.Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);ResultSet resultSet = stmt.executeQuery("SELECT FNAME, LNAME FROM EMPLOYEE");while (resultSet.next()) { . . . // iterates forward through resultSet } . .
How will you differentiate the following two ways of loading a database driver? 2007-05-22 15:55:00 (1)DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());(2)Class.forName("oracle.jdbc.driver.OracleDriver");In case one, to load the driver, one needs an appropriate class to load, make a driver instance and register it with the JDBC driver manager. Class.forName() will cause the class to create an instance, and call the current class loader's DriverManager.registerDriver() method to announce its presence.While DriverManager.registerDriver registers an instance of the with driver manager.
Questions on Java Database Connectivity 2007-05-02 08:21:00 What is JDBC ? What are four drivers available in JDBC? How do you establish database connection using JDBC?What are the different types of Statements? What is PreparedStatement and how is different from Statement? What is the difference between executeQuery () and execute() ?What is the difference between executeQuery () and executeUpdate()? How do you call a stored procedure in Java? What are new features from JDBC2.0 onwards?How can a cursor move in scrollable result sets?(new)Differentiate TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?(new) How will you differentiate the following two ways of loading a database driver?(new)
Read more:Database
, Connectivity
Can you compare JDBC/DAO with Hibernate? 2007-06-14 09:53:00 Hibernate and straight SQL through JDBC are different approaches.They both have their specific significance in different scenarios.If your application is not to big and complex,not too many tables and queries involved then it will be better to use JDBC. While Hibernate is a POJO based ORM tool,using JDBC underneath to connect to database, which lets one to get rid of writing SQLs and associated JDBC code to fetch resultset,meaning less LOC but more of configuration work.It will suit better when you have large application involving large volume of data and queries.Moreover lazy loading,caching of data helps in having better performance and you need not call the database every time rather data stays in object form which can be reused.
Read more:Hibernate
Interview Questions on Hibernate 2007-06-14 08:53:00 What is Hibernate
?Why Hibernate?What is ORM?What are core interfaces of Hibernate Framework?What is dirty checking in Hibernate?What are different fetch strategies Hibernate have?Can you compare JDBC/DAO with Hibernate?More Hibernate Questions
What are different fetch strategies Hibernate have? 2007-06-14 06:09:00 A fetching strategy in Hibernate
is used for retrieving associated objects if the application needs to navigate the association. They may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query. Hibernate3 defines the following fetching strategies:Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN. Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association. Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly Read more:different
What is dirty checking in Hibernate? 2007-06-13 10:05:00 Hibernate automatically detects object state changes in order to synchronize the updated state with the database, this is called dirtychecking
. An important note here is, Hibernate will compare objects by value, except for Collections, which are compared by identity. For this reason you should return exactly the same collection instance as Hibernate passed to the setter method to prevent unnecessary database updates.
Read more:Hibernate
What are core interfaces for Hibernate framework? 2007-06-13 08:51:00 Most Hibernate
-related application code primarily interacts with four interfaces provided by Hibernate Core:org.hibernate.Sessionorg.hibernate.SessionFactoryorg.hibernate.Criteriaorg.hibernate.QueryThe Session is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not thread safe.The application obtains Session instances from a SessionFactory. SessionFactory instances are not lightweight and typically one instance is created for the whole application. If the application accesses multiple databases, it needs one per database.The Criteria provides a provision for conditional search over the resultset.One can retrieve entities by composing Criterion objects. The Session is a factory for Criteria.Criterion instances are usually obtained via the factory methods on Restrictions.Query represents object oriented representation of a Hibernate query. A Query instance is Read more:framework
More Hibernate Questions 2007-06-13 08:51:00 Question: What are common mechanisms of configuring Hibernate
?Answer: 1. By placing hibernate.properties file in the classpath.2. Including elements in hibernate.cfg.xml in the classpath. Question:How can you create a primary key using Hibernate?Answer: The 'id' tag in .hbm file corresponds to primary key of the table:Here Id ="empid", that will act as primary key of the table "EMPLOYEE".Question: In how many ways one can map files to be configured in Hibernate?Answer: 1. Either mapping files are added to configuration in the application code or,2.hibernate.cfg.xml can be used for configuring in . Question: How to set Hibernate to log all generated SQL to the console?Answer: By setting the hibernate.show_sql property to true. Question: What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath?Answer: The settings of the XML configuration file will override the settings used in the properties. Question: What methods must the persistent classes impleme
What is ORM ? 2007-06-13 08:06:00 Object Relational Mapping(ORM) is a technique/solution that provides an object-based view of data to applications which it can manipulate.The basic purpose of ORM is to allow an application written in an object oriented language to deal with the information it manipulates in terms of objects, rather than in terms of database-specific concepts such as rows, columns and tables. In the Java world, ORM's first appearance was under the form of entity beans. But entity beans have limited scope in Java EE domain,they can not be exploited for Java SE based applications.The mapping of class lever attributes is done to table columns.For example a String variabe of a class will directly map onto a VARCHAR column. A relationship mapping is the one that you use when you have an attribute of a class that holds a reference to an instance of some other class in your domain model. The most common types of relationship mappings are "one to one", "one to many" or "many to many".
Why Hibernate? 2007-06-13 08:04:00 The reasons are plenty,weighing in favor of Hibernate
clearly. -Cost effective.Just imagine when you are using EJBs instead of Hibernate.One has to invest in Application Server(Websphere,Weblogic etc.),learning curve for EJB is slow and requires special training if your developers are not equipped with the EJB know-how. -The developers get rid of writing complex SQLs and no more need of JDBC APIs for resultset handling.Even less code than JDBC.In fact the OO developers work well when they have to deal with object then writing lousy queries. -High performance then EJBs(if we go by their industry reputation),which itself a container managed,heavyweight solution. -Switching to other SQL database requires few changes in Hibernate configuration file and requires least clutter than EJBs. -EJB itself has modeled itself on Hibernate principle in its latest version i.e. EJB3 because of apparent reasons.
What is Hibernate? 2007-06-13 07:54:00 Hibernate is a powerful, high performance object/relational persistence and query service.It is an open-source technology which fits well both with Java and .NET technologies.Hibernate lets developers write persistence classes with hibernate query features of HQL within principles of Object Oriented paradigm.It means one can include association,inheritance,polymorphism,composition and collection of these persisting objects to build applications. Hibernate ArchitectureThe main objective of Hibernate is to relieve the developers from manual handling of SQLs,JDBC APIs for resultsets handling and it helps in keeping your data portable to various SQL databases,just by switching the delegate and driver details in hibernate.cfg.xml file. Hibernate offers sophisticated query options, you can write plain SQL, object-oriented HQL (Hibernate Query Language), or create programmatic criteria and example queries. Hibernate can optimize object loading all the time, with various fetching and caching Read more:Hibernate
Explain the usage of java.util.Date and more classes and APIs for date handling in Java? 2007-04-18 04:46:00 The class java.util.Date-Represents a point in time.-Corresponds to the number of milliseconds since the start of the Unix epoch on January 1, 1970, 00:00:00 GMT.-This class depends on System.currentTimeMillis() to obtain the current point in time,which actually returns a long value and its accuracy and precision is determined by the implementation of System and underlying OS.Apart from this class there are several other classes like GregorianCalendar,SimpleTimeZone,SimpleDateFormat,DateFormatSymbols,java.sql.Date,java.sql.Time ,java.sql.Timestamp which are used for handling date and time related problems.In the table shown below a very brief purposes of these classes have been summarized:
How do you set Java library path programatically? 2007-04-18 04:10:00 Java library path can be set by choosing an option as:- -Djava.library.path=your_pathWhile setting the java.library.path property to "." instructs the Java virtual machine to search for native libraries in the current directory.And you execute your code as : java -Djava.library.path=. HelloWorldThe "-D" command-line option sets a Java platform system property. But these values are 'read only' like many of the system properties, the value in java.library.path is just FYI and changing it doesn't actually change the behaviour of the JVM.If you want to load a library from a specific location, you can use System.load() instead with the full path to the library.
Code Snippets: Using java.lang.reflect.* APIs 2007-06-20 05:00:00 import java.lang.reflect
.*;public class ReflectionExample { public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { ClassLoader j = ClassLoader.getSystemClassLoader(); Class someClass = j.loadClass("GlobalVillage"); Object instanceOfSomething = someClass.newInstance(); // the second parameter specifies the type of the argument(s) passed to method Method aMethod = someClass.getMethod("showMessage", new Class[]{Strin
Code Snippets: Thread Interruption 2007-06-20 03:46:00 Explain following code snippet: class Thread
Interrupted extends Thread { public void run() // called when start method executes. { System.out.println("Inside run"); try { synchronized (this) { System.out.println("Before calling wait"); wait(); System.out.println("wait is called"); } } catch (InterruptedException ie) { System.out.println("value of interrupted():"+interrupted()); System.out.println("Here goes printStackTrace"); ie.printStackTrace(); } } public static void main(String[] args) { ThreadInterrupted threadInterrupted = new ThreadInterrupted(); threadInterrupted.start(); // control goes to run method. System.out.println ("Before calling interrupt()"); threadInterrupted.interrupt(); }} Once you execute this snippet of code the output shown at console looks something like: Before calling inter Read more:Interruption
Interview Questions on java.net.* 2007-06-19 10:08:00 How can you display a particular web page from an applet?How can you get the hostname on the basis of IP addres ?How can you get an IP address of a machine from its hostname? How do you know who is accessing your server?What are different socket options?What should I use a ServerSocket or DatagramSocket in my applications?
What are different socket options? 2007-06-19 09:55:00 The different
Socket options are :SO_TIMEOUTSO_LINGERTCP_NODELAYSO_RCVBUFSO_SNDBUF.They may be specified in various scenarios e.g. one might like to specify a timeout for read 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.
How can you get the hostname on the basis of IP addres ? 2007-06-19 09:52:00 The following snippet of code helps you in finding hostname on the basis of IP address:-InetAddress inetAddress = InetAddress.getByName("67.83.45.98");System.out.println ("Host Name: " + inetAddress.getHostName());
How will you get an IP address of a machine from its hostname? 2007-06-19 09:47:00 The following code snippet gives you the IP address on the basis of Hostname:InetAddress inetAddress = InetAddress.getByName("www.interviewjava.blogspot.com");System.out.println ("IP Address: " + inetAddress.getHostAddress());
How do you know who is accessing your server? 2007-06-19 09:44:00 In case of TCP protocol i.e. ServerSocket:Each Socket connection accepted corresponds to who is connecting to your server
, that means relevant method calls on ServerSocket will fetch IP address and port of the same.Socket socket = serverSocket.accept();// Print IP address and portSystem.out.println ("Connecting from : " + socket.getInetAddress().getHostAddress() + ':' + socket.getPort()); In case of UDP i.e. DatagramSocketThe DatagramPacket received contains all the necessary information:DatagramPacket datagramPacket = null;// Receive next packetdatagramSocket.receive ( datagramPacket );// Print address + portSystem.out.println ("Packet received from : " + datagramPacket.getAddress().getHostAddress() + ':' + datagramPacket.getPort());
What should I use a ServerSocket or DatagramSocket in my applications? 2007-06-19 09:43:00 DatagramSocket accepts only UDP packets, whereas ServerSocket allows TCP connections in an application. It depends on the protocol one implements. Here are few things which one should keep in mind while implementing a new protocol:-UDP is not a reliable protocol as you may loose data packets over the network so while coding you will have to handle missing packets in your client/server.-ServerSockets use TCP connections for communication.TCP is safe and reliable protocol and guarantees delivery, all you need is InputStream to read and OutputStream to write over TCP.
How can you display a particular web page from an applet? 2007-06-19 09:32:00 The following code snippet shows you how to achieve that using showPage method is capable of displaying any URL passed to it.import java.net.*;import java.awt.*;import java.applet
.*;public class TestApplet extends Applet{ // Applet code goes here // Show a page public void showPage ( String showPage) { URL url = null; // Create a URL object try { url = new URL ( showPage ); } catch (MalformedURLException e) { // Invalid URL } // Show URL if (url != null) { getAppletContext().showDocument (url); } }}
Read more:particular
What is Spring Framework? 2007-06-25 05:46:00 Now the answer of this question can go to a great depth.But my focus here is to cover following points under the periphery of answer of question framed:-Definition of Spring
-Structure/Modules/Components of SpringDefinition: Spring is a lightweight container,sometimes referred as framework also, which provides runtime support for different enterprise level services and frameworks.Spring has Inversion of Control(IoC) and Aspect Oriented Programming(AOP) concepts at its core(These concepts will be answered under separate questions).Spring has provided a platform for existing projects,technologies,concepts to combine and provide a cohesive enterprise level application development support. Spring framework is consisted of seven modules as shown in the diagram below:Spring Framework(Image Source: springframework.org)Core package-most fundamental-provides the IoC and Dependency Injection features-The concept of BeanFactory that helps in decoupling configuration and specification of dependenci