DirectoryTechnologyBlog Details for "Interview Questions in Java and Java EE"

Interview Questions in Java and Java EE

Interview Questions in Java and Java EE
Interview Questions on Core Java and Java EE
Articles: 1, 2, 3, 4

Articles

How do you connect to a MySql Database using JDBC?
2007-10-24 14:24:00
Recently some newbie asked me a simple question of connecting to MySql database using JDBC.Here is a code snippet for that.The important thing here is to ensure that you have added MySql database driver classes(mysql.jar) in your classpath. Here goes the code snippet:import java.sql.*;public class MySqlConnect { public static void main (String[] args) { Connection connection = null; try { String userName = "root"; String password = "bunty"; String url = "jdbc:mysql://localhost:3306/systdb"; Class.forName ("com.mysql.jdbc.Driver").newInstance (); connection = DriverManager.getConnection (url, userName, password); System.out.println ("Database connection established"); } catch (Exception e) { System.err.println ("Connection to database server cannot be establish"); } finally { if (connection != null) ...
More About: Mysql
Explain different inheritance mapping models in Hibernate.
2007-10-22 08:29:00
There can be three kinds of inheritance mapping in hibernate1. Table per concrete class with unions2. Table per class hierarchy3. Table per subclassExample:We can take an example of three Java classes like Vehicle, which is an abstract class and two subclasses of Vehicle as Car and UtilityVan.1. Table per concrete class with unionsIn this scenario there will be 2 tablesTables: Car, UtilityVan, here in this case all common attributes will be duplicated.2. Table per class hierarchySingle Table can be mapped to a class hierarchyThere will be only one table in database named 'Vehicle' which will represent all attributes required for all three classes.Here it is be taken care of that discriminating columns to differentiate between Car and UtilityVan3. Table per subclassSimply there will be three tables representing Vehicle, Car and UtilityVan
More About: Models , Hibernate , Inheritance , Mapping , Diff
Explain Facade Design Pattern in Java
2007-10-12 08: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...
More About: Design , Java , Pattern
Give an example where upcasting takes advantage of polymorphism.
2007-10-08 10: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.
More About: Give , Polymorphism , Poly , Morph , Xamp
Java Tools
2007-10-03 15:31:00
To increase the efficiency and productivity of Java Developers,they all need a set of tools which equip them to design,code and test their work in consolidated ways.Here I tried to summarize various essentials or must have Java tools for all those who are fascinated with this language. Eclipse.org - It is an open source development platform for Java based applications, as well as other languages.Hibernate.org - An open source persistent classes development tool; due to licensing, it can be included in to other open source projects.JUnit.org - An open source testing platform for Java that works towards understanding your intentions.PMD - A Sourceforge project that scans Java apps and looks for bad code.SpringFramework.org - A Java/JEE application framework with a large support system and training sessions all over the world.Idevelopment Java Examples - A large collection of examples of Java programming along with documentation.JAD - A non-commercial use Java decompiler.Java.net - ...
More About: Tools
Test Java Programming Hands-on Skills
2007-09-19 09:21:00
Maxim Glaezer is a friend whose efforts in order make you a better programmer are highly commendable.His 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 employers 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 environmen...
More About: Programming , Hands , Test , Skills
Explain Decorator Design Pattern in Java
2007-09-17 08: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.
More About: Design , Pattern
Explain Adapter Design Pattern in Java
2007-09-17 07: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.
More About: Design , Pattern , Adapter
Code Snippets:XML Parsing using SAX
2007-07-26 15: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 { Node firstEmpNode = listOfEmployees.item(i); if (fi...
More About: Code , Snippet , Parsi
What is difference between Abstract Factory and Factory Method design patte
2007-07-20 16:48:00
In order to answer this question we must first understand what are Abstract Factory 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 v...
More About: Design , Design Patterns , Difference
What is Singleton Design Pattern?
2007-07-19 17: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() {Sin...
More About: Design Patterns
Code Snippets:File Operations
2007-07-16 09: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.readLin...
More About: Code , Snippet
Interview Questions On Java Design Patterns
2007-07-10 13:44:00
What are Design Patterns and why one needs them?What are different types of design patterns?
More About: Questions , Java , Interview
Interview Questions On JMS
2007-07-10 13: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.
More About: Questions , Interview
Explain Publish/Subscribe Messaging Domain.
2007-07-10 13: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)
More About: Subscribe , Subs , Scribe
Explain Point-to-Point Messaging Domain
2007-07-10 13: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 Mess aging Model(Image Source:java.sun.com)
More About: Domain , Point
Explain JMS API Architecture.
2007-07-10 12: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
More About: Architecture , Architect
How Does the JMS API Work with the Java EE Platform?
2007-07-10 12: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,...
More About: Work , Platform
When is JMS needed?
2007-07-10 12: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 11: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 ...
More About: Rent , Diff , Mess
What are different types of design patterns?
2007-07-09 11: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 together by wrapping its own interface around that of an already existing class. * Bridge...
More About: Design , Patterns , Types , Design Patterns , Rent
What are Design Patterns and why one needs them?
2007-07-09 11: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.
More About: Design Patterns , Needs
Code Snippets:Experimenting With java.util.Date
2007-07-05 12: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 = t...
More About: Java , Code , Snippet , Peri , Rime
What are ORMs supported by Spring and how it integrates with Hibernate?
2007-07-04 13: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.  
More About: Spring , Integra , Rates , Rate
Explain typical Bean life cycle in Spring Bean Factory Container.
2007-07-04 12: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 Bean NameAware 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.
More About: Life , Cycle
What are the problems you have with JDBC and how does Spring framework help
2007-07-04 12: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 pr...
More About: Problems , Framework , Frame , Ework
Interview Questions On Spring Framework
2007-06-28 17:41:00
What is Spring frameworkWhy is Spring Frame work 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?
More About: Questions , Interview
What is Aspect Oriented Programming and how is it related with Spring?
2007-06-28 17:27:00
Aspect Oriented Programming (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 generatio...
More About: Late , Related , Ming
Explain ApplicationContext in Spring framework.
2007-06-28 15:07:00
A Spring Application Context 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.
More About: Framework , Frame
What is BeanFactory?
2007-06-28 14:49:00
In core packages of Spring org.springframework.beans.factory there is an interface named Bean Factor y 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 pro...
More About: Tory , Actor
More articles from this author:
1, 2, 3, 4
82292 blogs in the directory.
Statistics resets every week.


Contact | About
© Blog Toplist 2009 - Supported by Web Catalog - SEO by FeWorks
eXTReMe Tracker