Directory
Technology
Blog Details for "Interview Questions in Java and Java EE"
Interview Questions in Java and Java EEInterview Questions in Java and Java EEInterview Questions on Core Java and Java EE Articles
What do you understand by Inversion of Control/Dependency Injection?
2007-06-26 17:44:00 Spring is an Inversion of Control container through its bean factory concept.IoC helps in loose coupling of the code .Spring is most closely identified with a flavor of Inversion of Control known as Dependency Injection (DI)--a name coined by Martin Fowler, Rod Johnson and the PicoContainer team in late 2003.DI is an old concept which caught the fancy of Java EE community not so long ago.DI is quite useful in test driven development and avoiding dependencies on other collaborating objects helps in building unit tests of objects behavior that is under test. It follows famous Hollywood principle "Don't call me.I will call you". IoC moves the responsibility for making things happen into the framework, and away from application code. Whereas your code calls a traditional class library, an IoC framework calls your code. It segregates the calling mechanism of methods from actual implementation.Dependency Injection is a form of IoC.In DI an object uses the other object to... More About: Understand , Under , Version
Why is Spring Framework needed anyway?
2007-06-26 12:29:00 The main aim of Spring is to make J2EE easier to use and promote good programming practice.It does not reinvent the wheel but makes existing technologies easier to use. The main advantages of Spring framework are enumerated as given below:- -No matter whether you use EJBs or Struts Frame work or any other framework for writing business objects, Spring organizes your business objects in an effective manner with configuration management services on any runtime environment.You can keep one calling mechanism for your business objects while changing the implementation technology of them altogether.-Spring allows you to get rid of EJBs,if one wants to,no more compulsory to have,with alternative technologies like POJOs for building business objects and AOP provides a way to handle declarative transaction management, making EJB container absolutely not required. -Increased development productivity -Increased runtime performance -Improving test coverage as unit testing of code can easily b... More About: Ework
What is Spring Framework?
2007-06-25 12: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 Frame work (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 depende... More About: Ework
Code Snippets: Using java.lang.reflect.* APIs
2007-06-20 12:00:00 import java.lang.reflect.*;public class ReflectionExample { public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException &nbs p; { ClassLoader j = ClassLoader.getSystemClassLoader(); Class someClass = j.loadClass("GlobalVillage");&n bsp; Object instanceOfSomething = someClass.newInstance(); // the second parameter specifies the type of the argument(s) passed to method Method aMethod = someClass.getMethod("showMessage&quo t;, new Class[]{Str... More About: Java , Code , Snippet
Code Snippets: Using java.lang.Comparable Interface
2007-06-20 11:40:00 import java.util.Arrays;class Employee implements Compa rable { String empName; String empCode ; int totalMarks; double totalSalary; /** * @return */ public String getName() { return empName; } /** * @return */ public String getEmpCode() { return empCode; } /** * @param strEmpName */ public void setName(String strEmpName) { empName = strEmpName; } /** * @param strEmpCode */ public void setEmpCode(String strEmpCode) { empCod... More About: Java , Interface , Snippet
Code Snippets: Thread Interruption
2007-06-20 10:46:00 Explain following code snippet: class Thread Interrupt ed 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 in... More About: Code , Snippet
Interview Questions on java.net.*
2007-06-19 17: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? More About: Questions , Java , Interview
What are different socket options?
2007-06-19 16:55:00 The different Socket options are :SO_TIMEOUTSO_LINGERTCP_NODELAYSO_RCVBUFS O_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. More About: Options , Rent , Opti , Diff
How can you get the hostname on the basis of IP addres ?
2007-06-19 16: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");Syst em.out.println ("Host Name: " + inetAddress.getHostName()); More About: Hostname
How will you get an IP address of a machine from its hostname?
2007-06-19 16: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()); More About: Machine , Mach
How do you know who is accessing your server?
2007-06-19 16:44:00 In case of TCP protocol i.e. Serve r Socket: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().getHostAddres s() + ':' + datagramPacket.getPort());
What should I use a ServerSocket or DatagramSocket in my applications?
2007-06-19 16:43:00 DatagramSocket accepts only UDP packets, whereas Server Socket 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. More About: Applications , Application , Agra
How can you display a particular web page from an applet?
2007-06-19 16: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); } }} More About: Display , Artic
Can you compare JDBC/DAO with Hibernate?
2007-06-14 16: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. More About: Hibernate , Compare , Compa , Nate , Pare
Interview Questions on Hibernate
2007-06-14 15: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 More About: Interview , Nate
What are different fetch strategies Hibernate have?
2007-06-14 13: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 explicit... More About: Strategies , Stra , Rent , Rate
What is dirty checking in Hibernate?
2007-06-13 17:05:00 Hibernate automatically detects object state changes in order to synchronize the updated state with the database, this is called dirty checking. 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. More About: Hibernate , Dirty , Nate
What are core interfaces for Hibernate framework?
2007-06-13 15:51:00 Most Hibernate -related application code primarily interacts with four interfaces provided by Hibernate Core :org.hibernate.Sessionorg.hibernate.S essionFactoryorg.hibernate.Criteriaorg.hi bernate.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 obtained b... More About: Framework , Frame , Interfaces
More Hibernate Questions
2007-06-13 15: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 impl... More About: Questions , Nate
What is ORM ?
2007-06-13 15: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 15: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. More About: Nate
What is Hibernate?
2007-06-13 14: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,comp osition 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 cach... More About: Hibernate , Nate
Interview Questions on Struts Framework
2007-06-10 20:45:00 What is Struts and how it helps in web development? Explain Struts1.x in a nutshell? What are the methods in Action class? How you will handle errors and exceptions in Struts? How does Validator framework work in Struts? What is DispatchAction? More About: Questions , Interview , Framework , Frame
What is DispatchAction?
2007-06-10 20:33:00 org.apache.struts.actions.Dispatch Action is responsible for-Dispatches to a public method named on a request parameter-Method name corresponds to the 'parameter' property of corresponding ActionMapping-useful when multiple similar actions are to be clubbed within a singe Action class in order to simplify the design.If you want to to insert,update and delete all actions on a database from a JSP with the same Action class in such case it will come quite handy.Here is how this JSP looks like: <html:form action="/saveSubscription"> <html:submit> <bean:message key="insert"/> </html:submit> <html:submit> <bean:message key="update"/> </html:submit> <html:submit> <bean:message key="delete"/> </html:submit> </html:form>To configure the use of this action in your struts-config.xml file, create an entry like this:<action path="/saveSubscription" type="org.apache.struts.actions.DispatchA ctio... More About: Struts
How does Validator framework work in Struts ?
2007-06-10 19:20:00 The Validator framework is an open source project and is part of the Jakarta Commons subproject. The Commons project was created for the purpose of providing reusable components like the Validator. Other well-known Commons components include BeanUtils, Digester, and the Logging framework.It was first released in November 2002.Validator framework consists of the following components:- -Validators -Configuration Files -Resource Bundle -JSP Custom Tags -Validator Form ClassesValidators are Java classes which execute validation rule.The framework knows how to invoke a Validator class based on its method signature, as defined in a configuration file. Typically, each Validator provides a single validation rule, and these rules can be chained together to form a more complex set of rules.Configuration Files:There are two configuration files -validator.xml and -validator-rules.xmlvalidator-rules.xml contains all possible validations available to an application. ... More About: Work , Struts , Framework , Frame , Ework
How you will handle errors and exceptions in Struts?
2007-06-10 17:53:00 An efficient error and exception handling makes an application behave gracefully under abnormal conditions.Struts has errors and exception handling done in different ways.The form validations using Struts require a proper mechanism.For handling errors in Struts,it has two objects ActionError and ActionErrors .Whenever a form is submitted then cotroller receives request and then create ActionForm object which calls reset() method and stores ActionForm object to required scope and then it loads ActionForm object from request and calls validate() method.If validate method fails then errors are displayed on the form itself through <html:errors> tags. Exception Hand ling can be done in following ways:-try-catch block within -Using declarative exception handling.In struts-config.xml we can declare on which type of exception, a request should be redirected to.Use Global Exceptions tag in struts-config.xml<global-exceptions> ; <exception key="errors.MyException"...
What are the methods in Action class?
2007-06-10 14:48:00 An Action class in the struts application extends Struts 'org.apache.struts.action.Action" class. Action class acts as wrapper around the business logic and provides an interface to the application's Model layer. Action class mediates between the View and Model layer in both directions it means it transfers data to and fro from the view layer and the specific business process layer.If you look at the sequence diagram, it gives you a correct picture how an Action class instance is invoked.When it is invoked then overridden execute() method is invoked.It is advisable not to put the business process logic inside execute method which should ideally have navigational logic details, instead move the database and business process logic to DAO layer.Struts Sequence DiagramThe return type of the execute() method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object,mapping of which is provided in... More About: Class , Methods , Method
Explain Struts1.x in a nutshell?
2007-06-10 14: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 inpu... More About: Struts , Nuts
What is Struts and how it helps in web development?
2007-06-10 13: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. ... More About: Web Development , Development , Develop
How to get count of rows there are in a Result Set?
More articles from this author:2007-06-09 23: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 More About: Count , There 1, 2, 3, 4 |



