006 Misc 37
006 Misc 37
Ques 2. Can you name few design patterns used in standard JDK library?
Ans. Decorator design pattern which is used in various Java IO classes, Singleton pattern which is used in Runtime , Calendar and
various other classes, Factory pattern which is used along with various Immutable classes likes Boolean e.g. Boolean.valueOf and
Observer pattern which is used in Swing and many event listener frameworks.
Ques 3. What is Singleton design pattern in Java ? write code for thread-safe singleton in Java.
Ans. Singleton pattern focus on sharing of expensive object in whole system. Only one instance of a particular class is maintained in
whole application which is shared by all modules. Java.lang.Runtime is a classical example of Singleton design pattern. From Java 5
onwards you can use enum to thread-safe singleton.
Ques 4. What is main benefit of using factory pattern? Where do you use it?
Ans. Factory pattern’s main benefit is increased level of encapsulation while creating objects. If you use Factory to create object you
can later replace original implementation of Products or classes with more advanced and high performance implementation without
any change on client layer.
Ques 6. Give example of decorator design pattern in Java ? Does it operate on object level or class level?
Ans. Decorator pattern enhances capability of individual object. Java IO uses decorator pattern extensively and classical example is
Buffered classes like BufferedReader and BufferedWriter which enhances Reader and Writer objects to perform Buffer level reading
and writing for improved performance.
Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern
provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a
common interface.
We're going to create a Mobile interface and concrete classes implementing the Mobile interface. A factory class MobileFactory is
defined as a next step.
FactoryPatternDemo, our demo class will use MobileFactory to get a Mobile object. It will pass information (SAMSUNG / SONY /
BLACKBERRY) to MobileFactory to get the type of object it needs.
Step 1: Create an interface.
Mobile.java
public interface Mobile {
void draw();
}
Step 2
Create concrete classes implementing the same interface.
Sony.java
public class Sony implements Mobile {
@Override
public void draw() {
System.out.println("Inside Sony::draw() method.");
}
}
Blackberry.java
public class Blackberry implements Mobile {
@Override
public void draw() {
System.out.println("Inside Blackberry::draw() method.");
}
}
Samsung.java
public class Samsung implements Mobile {
@Override
public void draw() {
System.out.println("Inside Samsung::draw() method.");
}
}
Step 3
Create a Factory to generate object of concrete class based on given information.
MobileFactory.java
public class MobileFactory {
//use getMobile method to get object of type Mobile
public Mobile getMobile(String MobileType){
if(MobileType == null){
return null;
}
if(MobileType.equalsIgnoreCase("SAMSUNG")){
return new Samsung();
} else if(MobileType.equalsIgnoreCase("SONY")){
return new Sony();
} else if(MobileType.equalsIgnoreCase("BLACKBERRY")){
return new Blackberry();
}
return null;
}
}
Step 4
Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
public class FactoryPatternDemo {
public static void main(String[] args) {
MobileFactory MobileFactory = new MobileFactory();
//get an object of Samsung and call its draw method.
Mobile Mobile1 = MobileFactory.getMobile("SAMSUNG");
//call draw method of Samsung
Mobile1.draw();
//get an object of Sony and call its draw method.
Mobile Mobile2 = MobileFactory.getMobile("SONY");
//call draw method of Sony
Mobile2.draw();
//get an object of Blackberry and call its draw method.
Mobile Mobile3 = MobileFactory.getMobile("BLACKBERRY");
//call draw method of Blackberry
Mobile3.draw();
}
}
Step 5
Verify the output.
Inside Samsung::draw() method.
Inside Sony::draw() method.
Inside Blackberry::draw() method.
Blackberry.java
public class Blackberry implements Mobile {
@Override
public void make() {
System.out.println("Inside Blackberry::make() method.");
}
}
Samsung.java
public class Samsung implements Mobile {
@Override
public void make() {
System.out.println("Inside Samsung::make() method.");
}
}
Step 3
Create an interface for Colors.
Color.java
public interface Color {
void fill();
}
Step4
Create concrete classes implementing the same interface.
Red.java
public class Red implements Color {
@Override
public void fill() {
System.out.println("Inside Red::fill() method.");
}
}
Green.java
public class Green implements Color {
@Override
public void fill() {
System.out.println("Inside Green::fill() method.");
}
}
Blue.java
public class Blue implements Color {
@Override
public void fill() {
System.out.println("Inside Blue::fill() method.");
}
}
Step 5
Create an Abstract class to get factories for Color and Mobile Objects.
AbstractFactory.java
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Mobile getMobile(String shape) ;
}
Step 6
Create Factory classes extending AbstractFactory to generate object of concrete class based on given information.
MobileFactory.java
public class MobileFactory extends AbstractFactory {
@Override
public Mobile getMobile(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("SAMSUNG")){
return new Samsung();
} else if(shapeType.equalsIgnoreCase("SONY")){
return new Sony();
} else if(shapeType.equalsIgnoreCase("BLACKBERRY")){
return new Blackberry();
}
return null;
}
@Override
Color getColor(String color) {
return null;
}
}
ColorFactory.java
public class ColorFactory extends AbstractFactory {
@Override
public Mobile getMobile(String shapeType){
return null;
}
@Override
Color getColor(String color) {
if(color == null){
return null;
}
if(color.equalsIgnoreCase("RED")){
return new Red();
} else if(color.equalsIgnoreCase("GREEN")){
return new Green();
} else if(color.equalsIgnoreCase("BLUE")){
return new Blue();
}
return null;
}
}
Step 7
Create a Factory generator/producer class to get factories by passing an information such as Mobile or Color
FactoryProducer.java
public class FactoryProducer {
public static AbstractFactory getFactory(String choice){
if(choice.equalsIgnoreCase("SHAPE")){
return new MobileFactory();
} else if(choice.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
}
}
Step 8
Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by passing an information such as type.
AbstractFactoryPatternDemo.java
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
//get shape factory
AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");
//get an object of Mobile Samsung
Mobile shape1 = shapeFactory.getMobile("SAMSUNG");
//call make method of Mobile Samsung
shape1.make();
//get an object of Mobile Sony
Mobile shape2 = shapeFactory.getMobile("SONY");
//call make method of Mobile Sony
shape2.make();
//get an object of Mobile Blackberry
Mobile shape3 = shapeFactory.getMobile("BLACKBERRY");
//call make method of Mobile Blackberry
shape3.make();
//get color factory
AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");
//get an object of Color Red
Color color1 = colorFactory.getColor("RED");
Ques 10. What is Singleton Design Pattern with example in java design patterns?
Ans.
Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this
pattern provides one of the best way to create an object.
This pattern involves a single class which is responsible to creates own object while making sure that only single object get created.
This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.
We're going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself.
SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use
SingleObject class to get a SingleObject object.
Step 1
Create a Singleton Class.
SingleObject.java
public class SingleObject {
This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when
creation of object directly is costly. For example, a object is to be created after a costly database operation. We can cache the object,
returns its clone on next request and update the database as as and when needed thus reducing database calls.
We're going to create an abstract class Mobile and concrete classes extending the Mobile class. A class MobileCache is defined as a
next step which stores shape objects in a Hashtable and returns their clone when requested.
PrototypPatternDemo, our demo class will use MobileCache class to get a Mobile object.
Step 1
Create an abstract class implementing Clonable interface.
Mobile.java
public abstract class Mobile implements Cloneable {
private String id;
protected String type;
abstract void make();
public String getType(){
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
Step 2
Create concrete classes extending the above class.
Sony.java
public class Sony extends Mobile {
public Sony(){
type = "Sony";
}
@Override
public void make() {
System.out.println("Inside Sony::make() method.");
}
}
Blackberry.java
public class Blackberry extends Mobile {
public Blackberry(){
type = "Blackberry";
}
@Override
public void make() {
System.out.println("Inside Blackberry::make() method.");
}
}
Samsung.java
public class Samsung extends Mobile {
public Samsung(){
type = "Samsung";
}
@Override
public void make() {
System.out.println("Inside Samsung::make() method.");
}
}
Step 3
Create a class to get concreate classes from database and store them in a Hashtable.
MobileCache.java
import java.util.Hashtable;
public class MobileCache {
private static Hashtable<String, Mobile> shapeMap = new Hashtable<String, Mobile>();
public static Mobile getMobile(String shapeId) {
Mobile cachedMobile = shapeMap.get(shapeId);
return (Mobile) cachedMobile.clone();
}
// for each shape run database query and create shape
// shapeMap.put(shapeKey, shape);
// for example, we are adding three shapes
public static void loadCache() {
Samsung circle = new Samsung();
circle.setId("1");
shapeMap.put(circle.getId(),circle);
Blackberry square = new Blackberry();
square.setId("2");
shapeMap.put(square.getId(),square);
Sony rectangle = new Sony();
rectangle.setId("3");
shapeMap.put(rectangle.getId(),rectangle);
}
}
Step 4
PrototypePatternDemo uses MobileCache class to get clones of shapes stored in a Hashtable.
PrototypePatternDemo.java
public class PrototypePatternDemo {
public static void main(String[] args) {
MobileCache.loadCache();
Step 5
Verify the output.
Mobile : Samsung
Mobile : Blackberry
Mobile : Sony
Step 2
Create concrete classes implementing the same interface.
Sony.java
public class Sony implements Mobile {
@Override
public void make() {
System.out.println("Mobile: Sony");
}
}
Blackberry.java
public class Blackberry implements Mobile {
@Override
public void make() {
System.out.println("Mobile: Blackberry");
}
}
Step 3
Create abstract decorator class implementing the Mobile interface.
MobileDecorator.java
public abstract class MobileDecorator implements Mobile {
protected Mobile decoratedMobile;
public MobileDecorator(Mobile decoratedMobile){
this.decoratedMobile = decoratedMobile;
}
public void make(){
decoratedMobile.make();
}
}
Step 4
Create concrete decorator class extending the MobileDecorator class.
RedMobileDecorator.java
public class RedMobileDecorator extends MobileDecorator {
public RedMobileDecorator(Mobile decoratedMobile) {
super(decoratedMobile);
}
@Override
public void make() {
decoratedMobile.make();
setRedBorder(decoratedMobile);
}
private void setRedBorder(Mobile decoratedMobile){
System.out.println("Border Color: Red");
}
}
Step 5
Use the RedMobileDecorator to decorate Mobile objects.
DecoratorPatternDemo.java
public class DecoratorPatternDemo {
public static void main(String[] args) {
Mobile circle = new Blackberry();
Mobile redBlackberry = new RedMobileDecorator(new Blackberry());
Mobile redSony = new RedMobileDecorator(new Sony());
System.out.println("Blackberry with normal border");
circle.make();
System.out.println("\nBlackberry of red border");
redBlackberry.make();
System.out.println("\nSony of red border");
redSony.make();
}
}
Step 6
Verify the output.
Blackberry with normal border
Mobile: Blackberry
Blackberry of red border
Mobile: Blackberry
Border Color: Red
Sony of red border
Mobile: Sony
Border Color: Red
HexaObserver.java
public class HexaObserver extends Observer{
public HexaObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Hex String: "
+ Integer.toHexString( subject.getState() ).toUpperCase() );
}
}
Step 4
Use Subject and concrete observer objects.
ObserverPatternDemo.java
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new HexaObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);
System.out.println("First state change: 15");
subject.setState(15);
System.out.println("Second state change: 10");
subject.setState(10);
}
}
Step 5
Verify the output:
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010
Step 5
Verify the output:
Employee:
Name: Maxwell
Salary: 30000
Employee:
Name: Kate
Salary: 30000
Creating an Item interface representing food items such as pizzas and cold drinks and concrete classes implementing the Item
interface and a Packing interface representing packaging of food items and concrete classes implementing the Packing interface as
burger would be packed in wrapper and cold drink would be packed as bottle.
We then create a Meal class having ArrayList of Item and a MealBuilder to build different types of Meal object by combining Item.
BuilderPatternDemo, our demo class will use MealBuilder to build a Meal.
Step 1
Create an interface Item representing food item and packing.
Item.java
public interface Item {
public String name();
public Packing packing();
public float price();
}
Packing.java
public interface Packing {
public String pack();
}
Step 2
Create concreate classes implementing the Packing interface.
Wrapper.java
public class Wrapper implements Packing {
@Override
public String pack() {
return "Wrapper";
}
}
Bottle.java
public class Bottle implements Packing {
@Override
public String pack() {
return "Bottle";
}
}
Step 3
Create abstract classes implementing the item interface providing default functionalities.
Pizza.java
public abstract class Pizza implements Item {
@Override
public Packing packing() {
return new Wrapper();
}
@Override
public abstract float price();
}
ColdDrink.java
public abstract class ColdDrink implements Item {
@Override
public Packing packing() {
return new Bottle();
}
@Override
public abstract float price();
}
Step 4
Create concrete classes extending Pizza and ColdDrink classes
ItalianPizza.java
public class ItalianPizza extends Pizza {
@Override
public float price() {
return 200.0f;
}
@Override
public String name() {
return "Italian Pizza";
}
}
AmericanPizza.java
public class AmericanPizza extends Pizza {
@Override
public float price() {
return 300.0f;
}
@Override
public String name() {
return "American Pizza";
}
}
Coke.java
public class Coke extends ColdDrink {
@Override
public float price() {
return 30.0f;
}
@Override
public String name() {
return "Coke";
}
}
Pepsi.java
public class Pepsi extends ColdDrink {
@Override
public float price() {
return 40.0f;
}
@Override
public String name() {
return "Pepsi";
}
}
Step 5
Create a Meal class having Item objects defined above.
Meal.java
import java.util.ArrayList;
import java.util.List;
public class Meal {
private List<Item> items = new ArrayList<Item>();
public void addItem(Item item){
items.add(item);
}
public float getCost(){
float cost = 0.0f;
for (Item item : items) {
cost += item.price();
}
return cost;
}
public void showItems(){
for (Item item : items) {
System.out.print("Item : "+item.name());
System.out.print(", Packing : "+item.packing().pack());
System.out.println(", Price : "+item.price());
}
}
}
Step 6
Create a MealBuilder class, the actual builder class responsible to create Meal objects.
MealBuilder.java
public class MealBuilder {
public Meal prepareVegMeal (){
Meal meal = new Meal();
meal.addItem(new ItalianPizza());
meal.addItem(new Coke());
return meal;
}
public Meal prepareNonVegMeal (){
Meal meal = new Meal();
meal.addItem(new AmericanPizza());
meal.addItem(new Pepsi());
return meal;
}
}
Step 7
BuiderPatternDemo uses MealBuider to demonstrate builder pattern.
BuilderPatternDemo.java
public class BuilderPatternDemo {
public static void main(String[] args) {
MealBuilder mealBuilder = new MealBuilder();
Meal vegMeal = mealBuilder.prepareVegMeal();
System.out.println("Veg Meal");
vegMeal.showItems();
System.out.println("Total Cost: " +vegMeal.getCost());
Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
System.out.println("\n\nNon-Veg Meal");
nonVegMeal.showItems();
System.out.println("Total Cost: " +nonVegMeal.getCost());
}
}
Step 8
Verify the output.
Veg Meal
Item : Italian Pizza, Packing : Wrapper, Price : 200.0
Item : Coke, Packing : Bottle, Price : 30.0
Total Cost: 230.0
Non-Veg Meal
Item : American Pizza, Packing : Wrapper, Price : 300.0
Item : Pepsi, Packing : Bottle, Price : 40.0
Total Cost: 340.0
2. What is Observer design pattern in Java? When do you use Observer pattern in Java?
This is one of the most common Java design pattern interview question. Observer pattern is based upon notification, there are two
kinds of object Subject and Observer. Whenever there is change on subject's state observer will receive notification. SeeWhat is
Observer design pattern in Java with real life example for more details.
4. What is decorator pattern in Java? Can you give an example of Decorator pattern?
Decorator pattern is another popular java design pattern question which is common because of its heavy usage
in java.iopackage. BufferedReader and BufferedWriter are good example of decorator pattern in Java. See How to use Decorator
pattern in Java fore more details.
5. When to use Composite design Pattern in Java? Have you used previously in your project?
This design pattern question is asked on Java interview not just to check familiarity with Composite pattern but also, whether
candidate has real life experience or not. Composite pattern is also a core Java design pattern, which allows you to treat both whole
and part object to treat in similar way. Client code, which deals with Composite or individual object doesn't differentiate on them, it
is possible because Composite class also implement same interface as there individual part. One of the good example of Composite
pattern from JDK is JPanel class, which is both Component and Container. Whenpaint() method is called on JPanel, it internally
called paint() method of individual components and let them draw themselves. On second part of this design pattern interview
question, be truthful, if you have used then say yes, otherwise say that you are familiar with concept and used it by your own. By the
way always remember, giving an example from your project creates better impression.
8. When to use Template method design Pattern in Java?Template pattern is another popular core Java design pattern interview
question. I have seen it appear many times in real life project itself. Template pattern outlines an algorithm in form of template
method and let subclass implement individual steps. Key point to mention, while answering this question is that template method
should be final, so that subclass can not override and change steps of algorithm, but same time individual step should be abstract, so
that child classes can implement them.
9. What is Factory pattern in Java? What is advantage of using static factory method to create object?
Factory pattern in Java is a creation Java design pattern and favorite on many Java interviews.Factory pattern used to create object
by providing static factory methods. There are many advantage of providing factory methods e.g. caching immutable objects, easy to
introduce new objects etc. See What is Factory pattern in Java and benefits for more details.
10. Difference between Decorator and Proxy pattern in Java?Another tricky Java design pattern question and trick here is that both
Decorator and Proxy implements interface of the object they decorate or encapsulate. As I said, many Java design pattern can have
similar or exactly same structure but they differ in there intent. Decorator pattern is used to implement functionality on already
created object, while Proxy pattern is used for controlling access to object. One more difference between Decorator and Proxy
design pattern is that, Decorator doesn't create object, instead it get object in it's constructor, while Proxy actually creates objects.
11. When to use Setter and Constructor Injection in Dependency Injection pattern?
Use Setter injection to provide optional dependencies of an object, while use Constructor injection to provide mandatory
dependency of an object, without which it can not work. This question is related to Dependency Injection design pattern and mostly
asked in context of Spring framework, which is now become an standard for developing Java application. Since Spring provides IOC
container, it also gives you way to specify dependencies either by using setter methods or constructors. You can also take a look
my previous post on same topic.
13. When to use Adapter pattern in Java? Have you used it before in your project?
Use Adapter pattern when you need to make two class work with incompatible interfaces. Adapter pattern can also be used to
encapsulate third party code, so that your application only depends upon Adapter, which can adapt itself when third party code
changes or you moved to a different third party library. By the way this Java design pattern question can also be asked by providing
actual scenario.
14. Can you write code to implement producer consumer design pattern in Java?
Producer consumer design pattern is a concurrency design pattern in Java which can be implemented using multiple way. if you are
working in Java 5 then its better to use Concurrency util to implement producer consumer pattern instead of plain oldwait and notify
in Java. Here is a good example of implementing producer consumer problem using BlockingQueue in Java.
16. What is Builder design pattern in Java? When do you use Builder pattern ?
Builder pattern in Java is another creational design pattern in Java and often asked in Java interviews because of its specific use
when you need to build an object which requires multiple properties some optional and some mandatory. See When to use Builder
pattern in Java for more details
17. Can you give an example of SOLID design principles in Java?
There are lots of SOLID design pattern which forms acronym SOLID, read this list of SOLID design principles for Java programmer to
answer this Java interview question.
18. What is difference between Abstraction and Encapsulation in Java?
I have already covered answer of this Java interview question in my previous post as Difference between encapsulation and
abstraction in Java. See there to answer this question.
1) How to find all the links in a folder in UNIX or Linux ?
This is a tricky UNIX question as there is no specific command to find all symbolic links. Though you have ln command for creating
and updating soft links but nothing which gives you all the links in a directory. You need to use ls command which list everything in
directory and then you need to list all the links, as they starts with "l" as first characters, as shown in above article .
linux@nyj872:~ ls -lrt
total 2.0K
-rw-r--r-- 1 Linux Domain Users 0 Dec 6 2011 a
drwxr-xr-x+ 1 Linux Domain Users 0 Sep 19 12:30 java/
lrwxrwxrwx 1 Linux Domain Users 4 Sep 19 12:31 version_1.0 -> java/
9) How do you find all files which are modified 10 minutes before ?
This is another the Linux interview questions from frequently used command e.g. find and grep. you can use -mtime option of find
command to list all the files which are modified 10 or m minutes before. see these find command examples for more details.
These are questions which not only relates to design patterns but also related to software design. These questions requires
some amount of thinking and experience to answer. In most of the cases interviewer is not looking for absolute answers but looking
for your approach, how do you think about a problem, do you able to think through, do you able to bring out things which are not
told to you. This is where experience come in picture, What are things you consider while solving a problem etc. overall these design
questions kicks off your thought process. Some time interviewer ask you to write code as well so be prepare for that. you can excel
in these questions if you know the concept, example and application of your programming and design skill.
1. Give an example where you prefer abstract class over interface ?
This is common but yet tricky design interview question. both interface and abstract class follow "writing code for interface than
implementation" design principle which adds flexibility in code, quite important to tackle with changing requirement. here are some
pointers which help you to answer this question:
1. In Java you can only extend one class but implement multiple interface. So if you extend a class you lost your chance of extending
another class.
2. Interface are used to represent adjective or behavior e.g. Runnable, Clonable, Serializable etc, so if you use an abstract class to
represent behavior your class can not be Runnable and Clonable at same time because you can not extend two class in Java but if
you use interface your class can have multiple behavior at same time.
3. On time critical application prefer abstract class is slightly faster than interface.
4. If there is a genuine common behavior across the inheritance hierarchy which can be coded better at one place than abstract class
is preferred choice. Some time interface and abstract class can work together also where defining function in interface and default
functionality on abstract class.
To learn more about interface in Java check my post 10 things to know about Java interfaces
2. Design a Vending Machine which can accept different coins, deliver different products?
This is an open design question which you can use as exercise, try producing design document, code and Junit test rather just
solving the problem and check how much time it take you to come to solution and produce require artifacts, Ideally this question
should be solve in 3 hours, at least a working version.
3. You have a Smartphone class and will have derived classes like IPhone, AndroidPhone,WindowsMobilePhone
can be even phone names with brand, how would you design this system of Classes.
This is another design pattern exercise where you need to apply your object oriented design skill to come with a design which is
flexible enough to support future products and stable enough to support changes in existing model.
4. When do you overload a method in Java and when do you override it ?
Rather a simple question for experienced designer in Java. if you see different implementation of a class has different way of doing
certain thing than overriding is the way to go while overloading is doing same thing but with different input. method signature varies
in case of overloading but not in case of overriding in java.
5. Design ATM Machine ?
We all use ATM (Automated Teller Machine) , Just think how will you design an ATM ? for designing financial system one must
requirement is that they should work as expected in all situation. so no matter whether its power outage ATM should
maintain correct state (transactions), think about locking, transaction, error condition, boundary condition etc. even if you not able
to come up exact design but if you be able to point out non functional requirement, raise some question , think about boundary
condition will be good progress.
6. You are writing classes to provide Market Data and you know that you can switch to different vendors overtime
like Reuters, wombat and may be even to direct exchange feed , how do you design your Market Data system.
This is very interesting design interview question and actually asked in one of big investment bank and rather common scenario if
you have been writing code in Java. Key point is you will have a MarketData interface which will have methods required by client
e.g. getBid(), getPrice(), getLevel() etc and MarketData should be composed with a MarketDataProvider by using dependency
injection. So when you change your MarketData provider Client won't get affected because they access method
form MarketData interface or class.
7. Why is access to non-static variables not allowed from static methods in Java
You can not access non-static data from static context in Java simply because non-static variables are associated with a particular
instance of object while Static is not associated with any instance. You can also see my post why non static variable are not
accessible in static context for more detailed discussion.
8. Design a Concurrent Rule pipeline in Java?
Concurrent programming or concurrent design is very hot now days to leverage power of ever increasing cores in
advanced processor and Java being a multi-threaded language has benefit over others. Do design a concurrent system key point to
note is thread-safety, immutability, local variables and avoid using static or instance variables. you just to think that one class can be
executed by multiple thread a same time, So best approach is that every thread work on its own data, doesn't interfere on other
data and have minimal synchronization preferred at start of pipeline. This question can lead from initial discussion to full coding of
classes and interface but if you remember key points and issues around concurrency e.g. race condition, deadlock, memory
interference, atomicity, ThreadLocal variables etc you can get around it.
XML interview questions and answers for freshers and experienced below
What is XML?
XML (Extensible markup language) is all about describing data. Below is a XML which describes book store.
< ?xml version="1.0" encoding="ISO-8859-1"? >
< book>
< php>php by pcds infotech< /php>
< java>Jave j2ee by pcds infotec< /java>
An XML tag is not something predefined but it is something you have to define according to your needs. For
instance in the above example of books all tags are defined according to business needs. The XML document is
self explanatory, any one can easily understand looking at the XML data what exactly it means.
What is the version information in XML?
"version" tag shows which version of XML is used.
What is ROOT element in XML ?
In our XML sample given previously < book> tag is the root element. Root element is the top most elements for a
XML. and it's must be unique
If XML does not have closing tag will it work ?
No, every tag in XML which is opened should have a closing tag. For instance in the top if we remove tag that
XML will not be understood by lot of application.
Is XML case sensitive ?
Yes, they are case sensitive. .
What is the difference between XML and HTML?
XML describes data while HTML describes how the data should be displayed. So HTML is about displaying
information while XML is about describing and storing the information.
Is XML meant to replace HTML?
No, they both go together one is for describing data while other is for displaying data.
Can you explain why your project needed XML ? or why you have chosen XML.
Remember XML was meant to exchange data between two entities as we can define our user friendly tags with
ease. In real world scenarios XML is meant to exchange data. For instance we have two applications who want to
exchange information. But because they work in two complete opposite technologies it’s difficult to do it
technically. For instance one application is made in JAVA and the other in .NET. But both languages understand
XML so one of the applications will spit XML file which will be consumed and parsed by other applications
we can give a scenario of two applications which are working separately and how you chose XML as the data
transport medium.
What is DTD ( Document Type definition )?
It defines how our XML should structure.means type of element like integer or value char etc
What is well formed XML?
If a XML document is confirming to XML rules (all tags started are closed, there is a root element , all valid char
have used etc) then it’s a well formed XML.
What is a valid XML?
If XML is confirming to DTD rules then it’s a valid XML.
What is CDATA section in XML?
All data is normally parsed in XML but if you want to exclude some elements you will need to put those elements
in CDATA.
What is element and attributes in XML?
In the below example book is the element and the price the attribute < book price=1002>< /book>
What is XSL?
XSL (the eXtensible Stylesheet Language) is used to transform XML document to some other document. So its
transformation document which can convert XML to some other document. For instance you can apply XSL to
XML and convert it to HTML document or probably CSV files.
What are the standard ways of parsing XML document? or What is a XML parser?
XML parser sits in between the XML document and the application who want to use the XML document. Parser
exposes set of well defined interfaces which can be used by the application for adding, modifying and deleting
the XML document contents. Now whatever interfaces XML parser exposes should be standard or else that
would lead to different vendors preparing there own custom way of interacting with XML document.
There are two standard specifications which are very common and should be followed by a XML parser:-
DOM: - Document Object Model.
DOM is a W3C recommended way for treating XML documents. In DOM we load entire XML document into
memory and allows us to manipulate the structure and data of XML document.
SAX: - Simple API for XML.
SAX is event driven way for processing XML documents. In DOM we load the whole XML document in to memory
and then application manipulates the XML document. But this is not always the best way to process large XML
documents which have huge data elements. For instance you only want one element from the whole XML
document or you only want to see if the XML is proper which means loading the whole XML in memory will be
quiet resource intensive. SAX parsers parse the XML document sequentially and emit events like start and end of
the document, elements, text content etc. So applications who are interested in processing these events can
register implementations of callback interfaces. SAX parser then only sends those event messages which the
application has demanded.
In What scenarios will you use a DOM parser and SAX parser ?
=> If we do not need all the data from the XML file then SAX approach is much preferred than DOM as DOM can
quiet memory intensive. In short if you need large portion of the XML document its better to have DOM.
=> With SAX parser you have to write more code than DOM.
=> If we want to write the XML in to a file DOM is the efficient way to do it.
=> Some time you only need to validate the XML structure and do not want to retrieve any Data for those
instances SAX is the right approach.
Define XPATH? and What is XSLT?
XPATH is an XML query language to select specific parts of an XML document. Using XPATH we can address or
filter elements and text in a XML document. For instance a simple XPATH expression like "book/price" states find
"price" node which are children of “Invoice” node.
XSLT is a rule based language used to transform XML documents in to other file formats. XSLT are nothing but
generic transformation rules which can be applied to transform XML document to HTML, CS, Rich text etc.
What is the concept of XPOINTER?
XPOINTER is used to locate data within XML document. XPOINTER can point to a particular portion of a XML
document, for instance
address.xml#xpointer(/descendant::streetnumber[@id=9])
So the above XPOINTER points streetnumber=9 in "address.xml".
Ques 1. What is Log4j?
Ans. Log4j (Log for Java) is logging framework provided by apache foundation for java based applications.
In the applicaitons, if you want to log some information, like any event triggered, or any Database updated is happened, we have the
need to log the specific information or error for the useful of the application.
To debug any issues in applications, we have to log the error/exceptions in the logs. For this we will use log4j mechanism .
Log4j logs the information and shows this information in different targets. The different targets are called appenders (console, file etc
).
2.Application logs:- We can define logging at each applicaiton level, For this we have to create log4j.xml or logging.properties in
WEB-INF/classes folder.
In distributed applications (e.g. web/remote applications), the logging is very important. The administrator can read logs to learn
about the problems that occurred during some interval.
Java's built-in APIs provide logging options but they are not that flexible. Another option is to use Apache’s open source logging
framework called log4j.
These are important points because, we ultimately want efficient applications. Log4J has the solution to this. You may turn on or turn
off the logging at runtime by changing the configuration file. This means no change in the Java source code (binary).
To reduce the code now in Spring Framework you can use of AOP where you can configure log mechanisms easily.
Q: What is an IDE?
A: An IDE or Integrated Development Environment is a software program that is designed to help programmers and developers build
software.
Q: What are the basic things an IDE includes?
A: Most IDEs include:
1. A source code editor
2. A compiler and/or an interpreter
3. Build automation tools
4. A debugger
Q: What is eclipse?
A: Eclipse is an open source community whose projects are focused on building an extensible development platform, runtimes and
application frameworks for building, deploying and managing software across the entire software lifecycle.
Eclipse is used in several different areas, e.g. as a development environment for Java or Android applications.
Q: Who governs the Eclipse projects?
A: The Eclipse projects are governed by the Eclipse Foundation. The Eclipse Foundation is a non-profit, member supported
corporation that hosts the Eclipse Open Source projects.
Q: What is Rich Client Platform?
A: The minimal set of plugins needed to build a rich client application is collectively known as the Rich Client Platform. It means your
application need only require two plugins, org.eclipse.ui andorg.eclipse.core.runtime, and their prerequisites.
Q: What are the prerequisite for installing Eclipse?
A: Eclipse requires an installed Java runtime. You may either install a Java Runtime Environment (JRE), or a Java Development Kit
(JDK), depending on what you want to do with Eclipse. If you intend to use Eclipse for Java development, then you should install a
JDK. If you aren't planning to use Eclipse for Java development and want to save some disk space, install a JRE.
Q: What is a workspace?
A: The workspace is the physical location (file path) you are working in. Your projects, source files, images and other artifacts can be
stored and saved in your workspace. The workspace also contains preferences settings, plugin specific meta data, logs etc
Q: What is an Eclipse project?
A: An Eclipse project contains:
1. source
2. configuration and
3. binary files related to a certain task
Eclipse groups the above into buildable and reusable units. An Eclipse project can have natures assigned to it which describe the
purpose of this project. For example the Java nature defines a project as Java project. Projects can have multiple natures combined
to model different technical aspects.
Natures for a project are defined via the .project file in the project directory.
Q: What are visible parts or user interface components of an Eclipse Window?
A: The major visible parts of an eclipse window are:
1. Views
2. Editors (all appear in one editor area)
3. Menu Bar
4. Toolbar
Q: What are views?
A: A view is typically used to work on a set of data, which might be a hierarchical structure. If data is changed via the view, the
change is directly applied to the underlying data structure. A view sometimes allows us to open an editor for a selected set of data.
E.g.:Package Explorer is a view, which allows you to browse the files of Eclipse projects.
Q: What are Editors?
A: Editors are typically used to modify a single data element, e.g. a file or a data object.
Q: What is difference between Views and Editors?
A: Editors are used to edit the project data and Views are used to view the project metadata. For example the package explorer
shows the java files in the project and the java editor is used to edit a java file.
Q: What is a Perspective?
A: An eclipse perspective is the name given to an initial collection and arrangement of views and an editor area. The default
perspective is called java.
Q: What is Refactoring and how is Refactoring in eclipse done?
A: Refactoring is the process of restructuring the code without changing its behavior. For example renaming a Java class or method
is a refactoring activity.
Eclipse supports several refactoring activities, for example renaming or moving. E.g.:To use the Rename refactoring, you can right-
click on your class (in the editor or Package Explorer) and select Refactor ? Rename to rename your class. Eclipse will make sure that
all calls in your Workspace to your class or method are renamed.
Q: Where do you set the memory heap size in Eclipse?
A: Eclipse installation contains a file called eclipse.ini which allows you to configure the memory parameters for the Java virtual
machine which runs the Eclipse IDE. For example the -Xmx parameter can be used to define how large the Java heap size can get. -
Xms defines the initial heap size of the Java virtual machine
Q: Why should we close a project in Eclipse?
A: An eclipse workspace can contain any number of projects. A project can be either in the open state or closed state. Open projects:
Consume memory
Take up build time especially when the Clean All Projects (Project > Clean all projects) with the Start a build immediately option is
used.
A closed project is visible in the Package Explorer view but its contents cannot be edited using the Eclipse user interface.
Q: What are extensions and extension points in eclipse?
A: Loose coupling in Eclipse is achieved partially through the mechanism of extensions and extension points. A general example for
this would be: electrical outlets. The outlet, or socket, is the extension point; the plug, or light bulb that connects to it, is the
extension. As with electric outlets, extension points come in a wide variety of shapes and sizes, and only the extensions that are
designed for that particular extension point will fit.
When a plugin wants to allow other plugins to extend or customize portions of its functionality, it will declare an extension point.
The extension point declares typically a combination of XML markup and Java interfaces. The extensions must conform to this.
plugins that want to connect to that extension point must implement that contract in their extension. Extension points are define in
the plugin.xml
Q: What are eclipse plugins?
A: A software component in Eclipse is called a plugin. The Eclipse IDE allows the developer to extend the IDE functionality via plugins.
For example you can create new menu entries and associated actions via plugins.
Q: When does a plugin get started?
A: Each plugin can be viewed as having a declarative section and a code section. The declarative part is contained in the plugin. xml
file. This file is loaded into a registry when the platform starts up and so is always available, regardless of whether a plugin has
started. The code section is activated only when their functionality has been explicitly invoked by the user.
Q: Does Eclipse save any report or log file?
A: Yes, whenever it encounters a problem that does not warrant launching a dialog, Eclipse saves a report in the workspace log file.
You can find the log file at :workspace/.metadata/.log.
Q: What is "Cannot find a VM" start up problem in Eclipse?
A: Eclipse requires a JVM to run and does not include one in the download. You may have a VM, but Eclipse cannot find it. To avoid
possible conflicts, always specify the VM you are using with the -vm command-line argument.
Q: What is "Disk full or out of memory" problem?
A: Eclipse, especially 2.1 and earlier, does not always gracefully report disk-full errors or out-of-memory errors. Make sure that you
have adequate disk space and that you are giving the Java VM enough heap space.
Q: How to install new plugins?
A: Best approach is to use the Eclipse Update Manager. The Update Manager allows you to find new plugins on your machine, your
network, or the Internet, compare new plugins to your configuration, and install only those that are compatible with your current
configuration. The Update Manager is invoked byHelp > Software Updates.
Q: How to remove a plugin?
A: plugins from Eclipse should never be removed. Instead they can be disabled by using the Eclipse Update Manager.
Run Help > About Eclipse >Installation Details, select the software you no longer want and click Uninstall.
Q: Where does System.out and System.err output logged?
A: Eclipse is simply a Java program and when launched from a shell or command line, the output will generally go back to that shell.
In Windows, the output will disappear completely if Eclipse is launched using the javaw.exe VM. As output is lost, it's better to log
error information by using the platform logging facility.
Q: What is autobuilding of Java code in Eclipse?
A: Eclipse provides autobuild facilities. If a resource changes, the platform checks the project description file ( .project in your
projects). When the file contains a reference to the Java builder, the builder gets notified of the change and will then compile the
Java source file and it's dependents.
Q: What is a Quick Fix?
A: As you type characters into an eclipse editor it analyzes the document content for potential error and warnings. The java editor
uses the java syntax to detect errors in the code. When it finds error it highlights errors using red wavy lines under the offending
code and a marker in the left editor margin.
The marker can be selected with the left mouse to activate the Quick Fix pop-up dialog. It provides a list of possible corrections for
the error.
Q: What is hot code replace?
A: Hot code enables you to change code while debugging. It simply means that you may change the code in debug mode and see its
affect.
Q: Why does the Eclipse compiler create a different serialVersionUID from javac?
A: Serializable classes compiled with Eclipse are not compatible with the same classes compiled using javac. When classes compiled
in Eclipse are written to an object stream, you may not be able to read them back in a program that was compiled elsewhere. Many
people blame this on the Eclipse compiler, assuming that it is somehow not conforming properly to spec. In fact, this can be a
problem between any two compilers or even two versions of a compiler provided by the same vendor.
If you need object serialization, the only way to be safe is to explicitly define the serialVersionUID in your code:
class MyClass implements Serializable {
public static final long serialVersionUID = 1;
}
whenever your class changes say it is incompatible with previously serialized versions, simply increment this number.
Q: What is the difference between a perspective and a workbench page?
A: The workbench page is the main body of a workbench window: between the toolbar and the status line, the area that contains
views and editors.The workbench page can have one or more perspectives associated with it that define the layout of the views and
editors in the page.
Project Manager Round FAQs
Q1. What is the architecture of your project?
Q2. What is your role and responsibilities in the project?
Q3. What are the corporate trainings you have attended?
Q4. What are the technologies you have worked on?
Q5. What are the tools that were used in your project?
Q6. What are the IDEs you have worked on?
Q7. What are the DBs you have worked on?
Q8. What are the Servers you have worked on?
Q9. Have you ever been involved in Testing?
Q10. Have you ever been involved in Design?
Q11. What is the reporting tool in your project?
Q12. What are your strengths and weakness in general and technical?
Q13. What is your team size?
Q14. What are all the different standards you employed for the project?(TCS)
Q15. Tell and explain to us about a specific situation during the project where you have to cope with a less
experienced candidate in your team and what are the measures you took to meet your deadlines?(Verizon)
Q16. Tell us some of your extraordinary skills which place you in the leading position over the other technical
associates?(Juniper Networks)
Q17. What was the criticism/difficulties you got during your projects, how did you handle it and what are the
measures you took to avoid repetition of the same?(Mecedes Benz, ORACLE, CA, Pega Systems)
Q18. Your project is beginning to exceed budget and to fall behind schedule due to almost daily user change
orders and increasing conflicts in user requirements. As a senior developer, how will you address the user
issues?(United Health Group)
Q19. You’ve encountered a delay on an early phase of your project. What actions can you take to counter the
delay?(Wipro, Accenture)
Q20. You have been assigned as the Team Lead for a team comprised of new employees just out of college and
“entry-level” consulting staff. What steps can you take to insure that the project is completed against a very
tight time deadline?(TCS, Infosys, CTS, LogicaCMG)
Q21. How do you handle non-productive team members?(Accenture, CISCO, GE)
Q22. How do you handle team members who come to you with their personal problems?(TCS, GE, CapGemini)
Q23. What are the different phases in delivering the project during development and during maintenance?
(CTS, Patni, Galaxe Systems, General Motors)
Q24. Do you have experience in Production Support and what is the hierarchy in Production Support?(HCL,
RBS, Amdocs(Gurgaon), HSBC)
Q25. How do you write Unit Test Cases?(Microsoft, Google, Tanla, Adobe, Bharti Telecom)
Q26. What is STQC testing?(For all Govt. projects)
Q27. How do you perform impact analysis for your code?(Microsoft, EmcSquare, Honeywell, INTEL, Symphony,
TCS, CTS,Amazon.com, NOKIA)
Q28. Why Analysis & Testing phases are very important?(Infosys, Mphasis)
Q29. What is the document that should be consulted to know about your project, the activities you do, to
know about your project, the activities you do, your schedules and milestones?(Dell, Qualcomm, HCL,
MindTree, PSPL, TechMahindra)
Q30. What is the difference between Architecture and Design?(TCS, Infosys, HCL, Tech Mahindra, Accenture,
HP)
Q31. What is the reporting hierarchy in your project?(all CMM Level 5 companies)
Yes. If I do it, I will use it. Learning design pattern will boost my coding skill.
Q28. Is J2EE a super set of J2SE?
Yes
views do not refer to each other directly.
Q29. What does web module contain?