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
Interview Questions On Spring Framework 2007-06-28 10:41:00 What is Spring
frameworkWhy is Spring Framework needed anyway?What do you understand by Inversion of Control/Dependency Injection?What is BeanFactory?Explain ApplicationContext in Spring framework.What is Aspect Oriented Programming and how is it related with Spring?
What is Aspect Oriented Programming and how is it related with Spring? 2007-06-28 10:27:00 Aspect OrientedProgramming
(AOP) is a paradigm of developmental approach which is based on:-separation of concerns encompasses breaking down a program in parts which overlap in functionality as little as possible.-cross-cutting concerns is how modules,classes,procedures intersect each other and defy concern like encapsulation-advancement in modularization.An AOP language consists of crosscutting expressions that encapsulate the concern in one place. AspectJ has a number of such expressions and encapsulates them in a special class, an aspect.An aspect can-change the behavior of the base code (the non-aspect part of a program) by applying advice(additional behavior) at various joint points (points in a program) specified by query called a point cut (that detects whether a given join point matches).-make structural changes to other classes, like adding members or parents.Spring
implements AOP using -dynamic proxies (where an interface exists) or-CGLIB byte code generation a Read more:Aspect
, related
Explain ApplicationContext in Spring framework. 2007-06-28 08:07:00 A Spring
ApplicationContext is a subinterface of BeanFactory.It is somewhat similar to BeanFactory in terms that both define beans,bind them together and make them available on request.In its functioning and ApplicationContext has following advanced features:-Resolving Messages, supporting internationalization-Support for an eventing mechanism, allowing application objects to publish events and they can register to be notified of events optionally.-Supports generic loading and access of file resources like image files.-Supports customization of container behavior through automatic recognition of special application-specific or generic, bean definitions.
Read more:framework
What is BeanFactory? 2007-06-28 07:49:00 In core packages of Spring org.springframework.beans.factory there is an interface named BeanFactory that can be implemented in various ways.It represents a generic factory that enables objects to be retrieved by name and which can manage relationships between objects.A BeanFactory contains different beans definitions which can be instantiated whenever a client wishes to do so , it is, hence, associated with life cycle of bean instances.Bean factories support two modes of object:-Singleton : a single,uniquely named, shared instance of an object which will be retrieved on lookup. It is the default, and most often used. It's ideal for stateless service objects.-Prototype or non-singleton: each retrieval results in an independent object creation.It could be used in stateful service objects scenarios where each caller has its own independent object.The most commonly used bean factory objects are: -XmlBeanFactory which parses a simple XML structure defining classes and proper
What do you understand by Inversion of Control/Dependency Injection? 2007-06-26 10: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 provide a specifi
Why is Spring Framework needed anyway? 2007-06-26 05: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 Framework 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 be done.
Code Snippets:Experimenting With java.util.Date 2007-07-05 05:10:00 import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class ExperimentingWithDates { public static void daysInMonth() { Calendar c1 = Calendar.getInstance(); // new GregorianCalendar(); c1.set(2096, 2, 20); int year = c1.get(Calendar.YEAR); int month = c1.get(Calendar.MONTH); int[] daysInMonths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; daysInMonths[1] += ExperimentingWithDates.isLeapYear(year) ? 1 : 0; String st = ""; if (month == 1) { st = "st"; } else if (month == 2) { st = "nd"; } else if (month == 3) { st = "rd"; } else { st = "th"; } System.out.println("Days in " + month + st + " month for year " + year + " are " + daysInMonths[c1.get(Calendar.MONTH) - 1]); System.out.println(); System.out.println(); } public static boolean isLeapYear(int year) { boolean value = false; if (year % 100 == 0) { if (year % 400 == 0) { value = true; } } else if (year % 4 == 0) { value = tru
What are ORMs supported by Spring and how it integrates with Hibernate? 2007-07-04 06:01:00 Spring framework supports the following ORMs: -Hibernate
-TopLink -JDO -iBatis -JPA and more.. With Hibernate,Spring can be integrated in following steps: -Wire with datasource -Declaring Hibernate properties -Tell Spring about the Hibernate Mapping files.
Read more:Spring
Explain typical Bean life cycle in Spring Bean Factory Container. 2007-07-04 05:54:00 The following steps talk about throw light on how a bean life cycle is inside a bean factory container: The bean's definition is found by the bean factory container from the XML file and instantiates the bean. The Spring
framework populates all of the properties as specified in the bean definition using DI. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean's ID. If the bean implements the BeanFactory
Aware interface, the factory calls setBeanFactory(), passing an instance of itself. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called. If an init-method is specified for the bean, it will be called. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
Read more:Container
What are the problems you have with JDBC and how does Spring framework help to resolve them? 2007-07-04 05:46:00 JDBC helps in accessing underlying RDBMS but it sometimes be quite cumbersome to use them and in following situations it become problematic: -You have to ensure that ResultSets, Statements and (most importantly) Connections are closed after use. Hence correct use of JDBC results in a lot of code which is a common source of errors. Connection leaks can quickly bring applications down under load. -The SQLException does not provide much information about what actually the probelm is as JDBC does not offer an exception hierarchy, but throws SQLException in response to all errors.The meaning of these values varies among databases. Spring
addresses these problems
in two ways: -By providing APIs that move tedious and error-prone exception handling out of application code into the framework
. The framework takes care of all exception handling; application code can concentrate on issuing the appropriate SQL and extracting results. -By provi
What are different types of design patterns? 2007-07-09 04:26:00 There are three kinds of design
patterns:Creational patterns:They are related with how objects and classes are created. While class-creation patterns use inheritance effectively in the instantiation process,while object-creation patterns use delegation to get the job done. * Abstract Factory groups object factories that have a common theme. * Builder constructs complex objects by separating construction and representation. * Factory Method creates objects without specifying the exact object to create. * Prototype creates objects by cloning an existing object. * Singleton restricts object creation for a class to only one instance.Structural patterns:They are related to class and object composition.This pattern uses inheritance to define new interfaces in order to compose new objects and hence new functionalities. * Adapter allows classes with incompatible interfaces to work to Read more:different
, types
What are Design Patterns and why one needs them? 2007-07-09 04:01:00 A pattern based designing approach is best suited in devising solutions for problems occurring over and over again.The design patterns are language-independent strategies for solving common object-oriented design problems. When you design, you should have advanced knowledge of such solutions in order to overcome problems that may occur in your system. GoF ,Gang-Of-Four,because of the four authors who wrote, Design Patterns
: Elements of Reusable Object-Oriented Software(ISBN 0-201-63361-2) is a software engineering book describing recurring solutions to common problems in software design. The book's authors are Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. It is language independent approach of designing systems on the based of patterns. My posts on questions asked on design patterns will be focused on most frequently used Java Design patterns.
Read more:Design Patterns
Interview Questions On JMS 2007-07-10 06:33:00 What is messaging and how is it different from RMI?When is JMS needed?How Does the JMS API Work with the Java EE Platform?Explain JMS API Architecture.Explain Point-to-Point Messaging Domain.Explain Publish/Subscribe Messaging Domain.
Explain Publish/Subscribe Messaging Domain. 2007-07-10 06:14:00 In a publish/subscribe (pub/sub) product or application, clients(publishers as well as subscribers) address messages to a topic, which functions similar to a bulletin board. Both publishers and subscribers are generally anonymous and can dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic's multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers. Pub/sub messaging has the following characteristics. Each message can have multiple consumers. Publish
ers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages. Pub-Sub Messaging
Domain(Image Source:java.sun.com)
Read more:Subscribe
Explain Point-to-Point Messaging Domain 2007-07-10 06:04:00 The constituents of a point-to-point (PTP) product or application are message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from specific queue(s) . Queues retain all messages sent to them until the messages are consumed or until the messages expire.So in PTP messaging domain:-Each message has only one consumer. There are no timing dependencies on a sender and a receiver of a message . The receiver can fetch the message oblivious of its availability when the client sent the message. The receiver acknowledges the successful processing of a message. PTP messaging is used when every message sent must be processed successfully by one consumer. PTP Messaging
Model(Image Source:java.sun.com)
Explain JMS API Architecture. 2007-07-10 05:49:00 A JMS application is consisted of the following parts as shown in the figure at the end of this post:-JMS Provider is a messaging system that implements the JMS interfaces and provides administrative and control features.-JMS Clients are any Java EE application component except Applets.-Messages are objects that exchange information between JMS clients.-Administrative objects are preconfigured JMS objects created by an administrator for the use of clients.Administrative tools bind destinations and connection factories into a JNDI namespace. A JMS client can then use resource injection to access the administered objects in the namespace and then establish a logical connection to the same objects through the JMS provider.Image Source:java.sun.com
Read more:Architecture
How Does the JMS API Work with the Java EE Platform? 2007-07-10 05:41:00 The JMS API in the Java EE platform has the following features. Application clients, Enterprise JavaBeans (EJB) components, and web components can send or synchronously receive a JMS message. Application clients can in addition receive JMS messages asynchronously. (Applets, however, are not required to support the JMS API.) Message-driven beans, which are a kind of enterprise bean, enable the asynchronous consumption of messages. A JMS provider can optionally implement concurrent processing of messages by message-driven beans. Message send and receive operations can participate in distributed transactions, which allow JMS operations and database accesses to take place within a single transaction. The JMS API enhances the Java EE platform by-allowing loosely coupled, reliable, asynchronous interactions among Java EE components and legacy systems capable of messaging.-supporting distributed transactions and allowing for the concurrent consumption of messages. For more information, s Read more:Platform
When is JMS needed? 2007-07-10 05:26:00 JMS can be used in following scenarios:- When distributed components,applications within an enterprise need to communicate with one another without creating any sort of dependencies(loose coupling support by JMS).This communication could either be synchronous or asynchronous.- When an application has to communicate with a provider without worrying its availability,.i.e. in an asynchronous way.A synchronous communication occurs when message requested is consumed immediately that means both producer and consumer are up and running at the same time while in case of asynchronous communication it is not necessary to have both entities available at the same time. An application may like to send a message to other without waiting for response and keep on doing its job.
What is messaging and how is it different from RMI? 2007-07-10 04:09:00 Messaging occurs between applications or software components which may or may not be distributive in nature.In enterprise applications where the possibility of distributed components across the geographies are too high, messaging comes as an obvious choice to make them communicate with each other.In Java , middleware(which acts as an infrastructural support for messaging) level messaging is supported with Java Message Service(JMS) APIs.JMS is a specification (java.sun.com/products/jms ) that describes the properties and behavior of an information pipe for Java software. It also describes how Java client applications interact with the information pipe.JMS helps business applications asynchronously send and receive critical business data and events.It supports both message queueing and publish-subscribe styles of messaging.The constituents of JMS are producers,consumers and messages themselves through interfaces' abstraction.The beauty lies here in loose coupling and infact message bro Read more:different
Code Snippets:File Operations 2007-07-16 02:48:00 import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class FileOperation { /** * @param args */ public static void main(String[] args) { FileOperation fio = new FileOperation(); //Creating a source file File sourceFile=new File("test.txt"); //Creating a destination file File destinationFile=new File("testDest.txt"); // Writing to a file fio.writeFile("test.txt", "Writing inside files is fun."); // Reading from a file fio.readFile("test.txt"); // Copy from a source file to a destination file fio.copyFile(sourceFile, destinationFile); } // Read from a file void readFile(String fileName) { BufferedReader bufferedReader; String line; try { bufferedReader = new BufferedReader(new FileReader(fileName)); while ((line = bufferedReader.readLine()
What is difference between Abstract Factory and Factory Method design patterns? 2007-07-20 09:48:00 In order to answer this question we must first understand what are AbstractFactory
and Factory Method design
patterns.An Abstract Factory(AF) provides an interface for creating families of related or dependent objects without specifying their concrete classes. you usually have multiple factory implementations. Each factory implementation is responsible for creating objects that are usually in a related hierarchy.In case of Factory Method(or simply called Factory pattern), generally a key or parameter is provided and method obtains an object of that type.The classic example can be creating a Database Connection Factory which is responsible for providing a vendor specific database connection objects(like Oracle,DB2,MS SQL Server etc.) depending upon the kind of parameter is provided.AF is very similar to the Factory Method pattern.One difference
between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via
What is Singleton Design Pattern? 2007-07-19 10:29:00 The Singleton Design Pattern
is a Creational type of design pattern which assures to have only a single instance of a class, as it is necessary sometimes to have just a single instance.The examples can be print spooler,database connection or window manager where you may require only a single object.In a Singleton design pattern,there is a public, static method which provides an access to single possible instance of the class.The constructor can either be private or protected.public class SingletonClass {private static SingletonClass instance = null;protected SingletonClass() {// can not be instantiated.}public static SingletonClass getInstance() {if(instance == null) {instance = new SingletonClass();}return instance;}}In the code above the class instance is created through lazy initialization,unless getInstance() method is called,there is no instance created.This is to ensure that instance is created when needed.public class SingletonInstantiator {public SingletonInstantiator() {Single
Code Snippets:XML Parsing using SAX 2007-07-26 08:58:00 This code snippet shows parsing of an XML
document using SAX parser.import java.io.File;import org.w3c.dom.Document;import org.w3c.dom.*;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.DocumentBuilder;import org.xml.sax.SAXException;import org.xml.sax.SAXParseException;public class ReadXML {public static void main(String argv[]) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File("employee.xml")); doc.getDocumentElement().normalize(); System.out.println("Root element of the document is " + doc.getDocumentElement().getNodeName()); NodeList listOfEmployees = doc.getElementsByTagName("employee"); int totalEmployees = listOfEmployees.getLength(); System.out.println("Total no of employees : " + totalEmployees); for (int i = 0; i < listOfEmployees.getLength(); i++) { Node firstEmpNode = l
Test Java Programming Hands-on Skills 2007-09-19 02:21:00 The website betterprogrammer lets you test your Java programming skills online.The employers will find this website useful in testing programming hands-on skills of future employees online.For Java programmers,by the end of the test you will get your permanent certificate which will show what percentage of programmers you outperformed on the test.Isn't this cool to assess one's current programming skills status,which also gives an insight on gap areas where one can improve upon with time.The test completion criterion is simple:-You will need to program 4 short tasks in Java with increasing complexity.-To solve each task you will need to: a) copy the task into a java file (you should use you favorite Java IDE) b) implement the missing parts c) copy your class back-You can use all standard JDK 1.5-1.6 classes.-The website will verify your solutions in a secure environment.-As the test progresses, try not to skip tasks. Position yourself as high as possible as a programmer.The pr Read more:Programming
, Hands
, Skills
Explain Decorator Design Pattern in Java 2007-09-17 01:28:00 Decorator design pattern attaches additional responsibilities or functions, dynamically or statically on an object.One can add new functionalities on an object without affecting other objects enhancing flexibility of an object.The best example of Decorator pattern in a visual manner can be illustrated from JScrollPane object which can be used to decorate a JTextArea object or a JEditorPane object. The different borders of a window like BevelBorder, CompoundBorder, EtchedBorder TitledBorder etc. are other examples of classes working as decorators existent in Java API.Decorator pattern can be used in a non-visual fashion. For example, BufferedInputStream, DataInputStream, and CheckedInputStream are decorating objects of FilterInputStream class. These decorators are standard Java API classes.
Read more:Decorator
, Pattern
Explain Adapter Design Pattern in Java 2007-09-17 00:49:00 Adapter design pattern lets unrelated classes communicate and work with each other.It achieves this objective by creating new interfaces for creating compatibility amongst otherwise non communicable classes.The adapter classes in Java API are WindowAdapter,ComponentAdapter, ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter and MouseMotionAdapter.In case of listener interfaces,whenever a class implements such an interface, one has to implement all of the seven methods.In case of WindowListener interface,it has seven methods.WindowAdapter class implements WindowListener interface and make seven empty implementation. When a class subclasses WindowAdapter class, one may choose the implementation of a method as per one's choice of implementation.Adapter design pattern is also referred as Wrapper pattern when it is introduced by composition of classes.
Read more:Pattern
, Adapter
Master List Of Code Snippets 2015-01-26 08:18:00 XML Parsing Using SAXFile OperationsExperimenting with java.util.Date.Using java.lang.reflect.* APIsUsing java.lang.Comparable.* interfaceThread Interruption
Read more:Master
Explain Facade Design Pattern in Java 2007-10-12 01:13:00 The objective of Facade pattern is to make a complex system simple. It is achieved by providing a unified or general interface, which is a higher layer to these subsystems.Facade pattern decouples subsystems, reduce its dependency, and improve portability,makes an entry point to your subsystems and hides clients from subsystem components and their implementation.JDBC design is a good example of Façade pattern. A database design is complicated. JDBC is used to connect the database and manipulate data without exposing details to the clients.A client is exposed to certain set of methods like just getting a single instance of database connection or closing it when not required.Another possibility is designing security of a system with Façade pattern. Clients' authorization to access information may be classified. General users may be allowed to access general information, special guests may be allowed to access more information,administrators and executives may be allowed to access the Read more:Pattern
Give an example where upcasting takes advantage of polymorphism. 2007-10-08 03:48:00 Here it goes:class Parent { }class Child extends Parent { }Child can be referred as an object of type Parent or Child.Upcasting works like this:Child aChildObj = new Child();Parent aParentObj = (Parent)aChildObj;As aChildObj can be referred to by the class names Child andParent,you can say that this upcasting and type extension is theimplementation of polymorphism in Java.