Showing posts with label design pattern. Show all posts
Showing posts with label design pattern. Show all posts

Spring Framework Sharing and reusing objects with the flyweight design pattern in Java

The Builder pattern is used to create many objects, whereby the Flyweight pattern is about sharing such a collection of objects. The flyweight design pattern is a structural pattern used to improve memory usage and performance (i.e. due to shorter and less frequent garbage collections). Here, instead of creating a large number of objects, we reuse the objects that are already created. With fewer objects, your application could fly.

Q. Can you give some examples of the usage of the flyweight design pattern in Java?
A.

Example 1: In Java, String objects are managed as flyweight. Java puts all fixed String literals into a literal pool. For redundant literals, Java keeps only one copy in the pool.


 
String author = "Little brown fox";
String authorCopy = "Little brown fox";

if(author == authorCopy) {
System.out.println("referencing the same object");
}

The above code snippet will print "referencing the same object". Even though the two String objects are created separately, under the covers Java is storing them in the same location, to save space by applying the flyweight design pattern.


Example 2: The Wrapper classes like Integer, Float, Decimal, Boolean, and many other classes having the valueOf static factory method applies the flyweight design pattern to conserve memory by reusing the objects.

 public class FlyWeightWrapper {

public static void main(String[] args) {
Integer value1 = Integer.valueOf(5);
Integer value2 = Integer.valueOf(5);

if (value1 == value2) {
System.out.println("referencing the same object");
}

}

}

The above code snippet will print "referencing the same object".

Q. How will you apply this pattern in the following scenario?

You have a scheduling application where a number of different time slots are used in 15 minute intervals in various online reporting. It contains hour and minute slots as in  10:15, 10:30, etc. The objects need to be immutable and reusable.

A. Here is the sample code that makes use of the getInstance(...)  static factory method to create objects.

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


//no setters, immutable object
//final class -- don't let outsiders extend
public final class Schedule {

private byte hour;
private byte minute;

private static Map<String,Schedule> schedules = new ConcurrentHashMap<String,Schedule>();

// Don't let outsiders create new factories directly
// can be invoked only via getInstance (byte hour, byte minute) method
private Schedule(byte hour, byte minute) {
this.hour = hour;
this.minute = minute;
}

public byte getHour() {
return hour;
}

public byte getMinute() {
return minute;
}

public static Schedule getInstance(byte hour, byte minute) {
String key = hour + ":" + minute;
//check the object pool first
Schedule schedule = schedules.get(key);
//if not found in the pool, create a new instance
if (schedule == null) {
schedule = new Schedule(hour, minute);
// add it to the pool, for later reuse
schedules.put(key, schedule);
}
return schedule;
}

}




Q. Are there any alternatives to using an object or resource pool to conserve memory in Java?
A. Yes, you can use a ThreadLocal object to create an object per thread. This approach is useful when creation of a particular object is not trivial and the objects cannot be shared between threads. For example, java.util.Calendar and java.text.SimpleDateFormat. Because these are heavy objects that often need to be set up with a format or locale, it’s very tempting to create it with a static initializer and stick the instance in a static field. Both of these classes use internal mutable state when doing date calculations or formatting/parsing dates. If they are called from multiple threads at the same time, the internal mutable state will most likely do unexpected things and  give you wrong answers. In simple terms, this will cause thread-safety issues that can be very hard to debug.

Here is an example with the ThreadLocal class to create per thread heavy object applying the abstract factory and singleton design patterns.

//final class -- don't let outsiders extend
public final class CalendarFactory {
private ThreadLocal<calendar> calendarRef = new ThreadLocal<calendar>() {
protected Calendar initialValue() {
return new GregorianCalendar();
}
};

private static CalendarFactory instance = new CalendarFactory();

public static CalendarFactory getFactory() {
return instance;
}

public Calendar getCalendar() {
return calendarRef.get();
}

// Don't let outsiders create new factories directly
private CalendarFactory() {}
}


Another alternative is to create immutable objects as they are inherently thread-safe, and can be shared with multiple threads.







Java J2EE Spring Chapter 57: Front Controller Pattern

This chapter is going to deal with the last pattern on the SCWCD exam – The Front Controller Pattern.

What is Front Controller Pattern?

The Front Controller pattern presents one entry point to a Web site or service. It provides a centralized entry point that controls and manages Web request handling. It eliminates the dependency of the user on a direct resource. Suppose you wanted to get the

Java J2EE Spring Chapter 55: Business Delegate Pattern

In this chapter, we are going to take a detailed look at the Business Delegate Pattern.

What is Business Delegate Pattern?

The Business Delegate pattern reduces the dependency between tiers. It is an attempt to make tiers interchangeable so one can access or utilize the services of any other.

Is

This pattern is a proxy that hides the complexity of remote service lookup and error recovery.

Java J2EE Spring Chapter 54: Data Access Object Pattern

In this chapter, we are going to take a detailed look at the DAO or Data Access Object Design Pattern.

What is Data Access Object Pattern?

The DAO pattern provides the connection between the business logic tier and the resource (usually a database) tier. The Data Access Object represents a general interface to the resources layer: It handles all calls to it. JDBC is the most commonly used

Java J2EE Spring Chapter 53: Value Object Pattern

Value Object
In this chapter, we are going to take a detailed look at the Value Object Pattern.

What is Value Object Pattern?

The Value Object pattern provides the best way to exchange data across tiers or system boundaries, especially when there is network communication involved. This is a pattern that solves performance issues around network latency. Do I have to tell you that, this is a

Java J2EE Spring Chapter 52: Design Pattern Elements

Before we dig into the specifics of the Design Patterns that are part of the SCWCD Exam, we need to know one important thing. “The Elements of a Design Pattern”. This is what you are going to learn in this chapter.

So, lets get started!!!

Elements of a Design Pattern:

There are many ways to define a pattern, but the classical way is to describe its elements, or the aspects of a pattern.

Java J2EE Spring Chapter 51: Introduction to Design Patterns

Design Patterns are a very important topic from the SCWCD Exam perspective as well as from being a J2EE Programmer perspective. Any experienced J2EE programmer is expected to know about a few of the J2EE Design Patterns. These patterns are used extensively and are very useful to create enterprise class J2EE Web Applications. In this next few chapters, we are going to look in detail, some of the

Spring Framework Proxy design pattern implementing thread safe wrappers


Q. What are the different ways you can make an object thread-safe?
A
  • Synchronize critical sections:  An object's critical sections are those methods or blocks of code within methods that must be executed by only one thread at a time. By using Java's synchronized keyword, you can guarantee that only one thread at a time will ever execute the object's critical sections.
  • Make the object immutable. Immutable objects are, by their very nature, thread-safe simply because threads have to be able to write to an object's instance variables to experience a read/write or write/write conflict. 
  • Use a thread-safe wrapper: by applying the proxy design pattern. let's have a look at an example.


Step 1: Here are the sample third party interface and implementation classes.

Here is the Interface

package com.arul;

public interface ThirdPartyInterface
{
abstract void someMethod();
}


Here is the implementation

package com.arul;

public class ThirdPartyImpl implements ThirdPartyInterface
{

private int someVar = 0;

@Override
public void someMethod()
{
//some not thread safe functionality
System.out.println("Printing .........." + ++someVar);
}

}

Step 2: Here is the testing of original third-party library to prove that it is not thread-safe.

package com.arul;

public class TestThreadSafeThirdParty implements Runnable
{

private ThirdPartyInterface tstp = null;

public TestThreadSafeThirdParty(ThirdPartyInterface tstp)
{
this.tstp = tstp;
}

public static void main(String[] args)
{
ThirdPartyImpl localTp = new ThirdPartyImpl();

TestThreadSafeThirdParty test = new TestThreadSafeThirdParty(localTp);

//create 2 threads
Thread thread1 = new Thread(test);
Thread thread2 = new Thread(test);
thread1.start();
thread2.start();

}

@Override
public void run()
{
for (int i = 0; i < 5; i++)
{
tstp.someMethod();
}

}
}


The output of the above run is not thread-safe as shown below

Printing ..........1
Printing ..........3
Printing ..........2
Printing ..........4
Printing ..........5
Printing ..........6
Printing ..........7
Printing ..........9
Printing ..........8
Printing ..........10


Step 3: Here is the thread safe implementation that acts as a proxy to the subject, and its responsibility is to add thread-safety.

package com.arul;

/**
* proxy class that applies thread safety to
*/
public class ThreadSafeThirdPartyImpl implements ThirdPartyInterface
{

private final Object lock = new Object();
private final ThirdPartyInterface subject;

public ThreadSafeThirdPartyImpl(ThirdPartyInterface subject)
{
this.subject = subject;
}

@Override
public void someMethod()
{
//lock to provide thread safety via this proxy class
synchronized (lock)
{
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}

subject.someMethod(); //access the unsafe method
}
}
}

Step 4: Here is the testing of proxied third-party library to prove that it is now thread-safe.

package com.arul;

public class TestThreadSafeThirdParty implements Runnable
{

private ThirdPartyInterface tstp = null;

public TestThreadSafeThirdParty(ThirdPartyInterface tstp)
{
this.tstp = tstp;
}

public static void main(String[] args)
{
ThirdPartyImpl localTp = new ThirdPartyImpl();
ThreadSafeThirdPartyImpl localTsTp = new ThreadSafeThirdPartyImpl(localTp);

TestThreadSafeThirdParty test = new TestThreadSafeThirdParty(localTsTp);

//create 2 threads
Thread thread1 = new Thread(test);
Thread thread2 = new Thread(test);
thread1.start();
thread2.start();

}

@Override
public void run()
{
for (int i = 0; i < 5; i++)
{
tstp.someMethod();
}

}
}

The output of the above run is now thread-safe as shown below. Thanks to the proxy class that applies the lock.

Printing ..........1
Printing ..........2
Printing ..........3
Printing ..........4
Printing ..........5
Printing ..........6
Printing ..........7
Printing ..........8
Printing ..........9
Printing ..........10


Spring Framework Java design pattern interview questions and answers: strategy and factory pattern

Design pattern questions are very popular with the job interviewers, and this post covers Java strategy and factory design pattern in a tutorial style. This blog takes you through a scenario where you will be learning 4 key things.

1. Factory design pattern
2. Strategy design pattern
3. Applying logic to calculate variance
4. Making use of the BigDecimal class for the financial calculations. The floating point variables must not be used as they can cause rounding issues.
Q. The scenario is narrated with the diagram below. It is financial application where an investor builds portfolio by buying and selling managed funds and listed securities.



The additional business rules are:

1. The managed funds that are not of type daily, must be funded from the available cash. Which means, you cannot use the proceeds you receive from selling managed funds or listed securities.

2. The daily managed funds and listed securities can be switched. This means you sell some daily managed funds to buy some listed securities.

3. The variance is calculated as total sell amount - total buy amount. The funded from cash amount also needs to be calculated to show the investor.

Let's look at the code samples:


Step 1: Define the InvestmentDetail value object (i.e. a POJO) that defines each investment  detail as shown above.

import java.math.BigDecimal;

public class InvestmentDetail {

enum TRADE_TYPE {BUY, SELL};
enum FUND_TYPE {MONTHLY, DAILY, NOT_APPLICABLE}

private String investmentCode;
private String investmentName;
private TRADE_TYPE tradeType;
private FUND_TYPE fundType;
private BigDecimal orderAmount;

public InvestmentDetail(String investmentCode, String investmentName,
TRADE_TYPE tradeType, FUND_TYPE fundType, BigDecimal orderAmount) {
this.investmentCode = investmentCode;
this.investmentName = investmentName;
this.tradeType = tradeType;
this.fundType = fundType;
this.orderAmount = orderAmount;
}

public boolean isDailyManagedFund() {
return fundType != null && fundType == FUND_TYPE.DAILY;
}

public boolean isMonthlyManagedFund() {
if(fundType == null ) {
throw new IllegalArgumentException("fundType cannot be null");
}
return fundType == FUND_TYPE.MONTHLY;
}

public boolean isListedSecurity() {
return fundType != null && fundType == FUND_TYPE.NOT_APPLICABLE;
}

public boolean isBuy() {
if(tradeType == null ) {
throw new IllegalArgumentException("tradeType cannot be null");
}
return tradeType == TRADE_TYPE.BUY;
}

public boolean isSell() {
if(tradeType == null ) {
throw new IllegalArgumentException("tradeType cannot be null");
}
return tradeType == TRADE_TYPE.SELL;
}

public BigDecimal getOrderAmount() {
return orderAmount;
}

//setters, getters, equals(), hashCode(), and toString() omitted for brevity
}

Step 2: The CashVariance value object (i.e. a POJO) for storing the calculated values like funded from cash and proceed to cash amounts and the variance is derived from these two amounts.

import java.math.BigDecimal;


public class CashVariance {

BigDecimal fundedFromCash;
BigDecimal proceedsToCash;

public CashVariance(BigDecimal fundedFromCash, BigDecimal proceedsToCash) {
super();
this.fundedFromCash = fundedFromCash;
this.proceedsToCash = proceedsToCash;
}

public BigDecimal getVariance() {
return this.proceedsToCash.subtract(this.fundedFromCash);
}

public void setFundedFromCash(BigDecimal fundedFromCash) {
this.fundedFromCash = fundedFromCash;
}

public void setProceedsToCash(BigDecimal proceedsToCash) {
this.proceedsToCash = proceedsToCash;
}

public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("fromCash:").append(this.fundedFromCash);
buffer.append("|toCash:").append(this.proceedsToCash);
buffer.append("|variance:").append(getVariance());
return buffer.toString();
}

//getters, equals(), and hashCode()omitted for brevity
}


Step 3: Define a factory class that decides which cash variance calculation strategy to use depending on the product type.

//cannot be extended as it is final
public final class VarianceCalculationFactory {

//can't instantiate from outside
private VarianceCalculationFactory(){}

//factory that creates and return a relevant strategy
public static CashVarianceCalculationStrategy getCashVarianceStrategy(String productType) {
if(productType != null ) {
return new SpecificCashVarianceCalculationStrategy();
}
else {
return new DefaultCashVarianceCalculationStrategy();
}
}

}


Q. Why use a factory design pattern?
A.
Factory pattern returns an instance of several subclasses (like DefaultCashVarianceCalculationStrategy, ManagedInvestmentsCashVarianceCalculationStrategy, etc), but the calling code is unaware of the actual implementation class. The calling code invokes the method on the interface for example CashVarianceCalculationStrategy and using polymorphism the relevant class and correct method gets invoked. So, as you can see, the factory pattern reduces the coupling or the dependencies between the calling code and called objects like DefaultCashVarianceCalculationStrategy, ManagedInvestmentsCashVarianceCalculationStrategy, etc. This is a very powerful and common feature in many frameworks.  You do not have to create a new DefaultCashVarianceCalculationStrategy or a new ManagedInvestmentsCashVarianceCalculationStrategy on each invocation. In future, to conserve memory, you can decide to cache objects or reuse objects in your factory with no changes required to your calling code. You can also load objects in your factory based on attribute(s) read from an external properties file or some other condition. Another benefit going for the factory is that unlike calling constructors directly, factory patterns have more meaningful names like getShape(…), getInstance(…), getStrategy(…) etc, which may make calling code much clear. 



Step 4: Define an interface each strategy class will be implementing.

import java.util.List;

//strategy pattern interface
public interface CashVarianceCalculationStrategy {
CashVariance calculate (List<InvestmentDetail> investments);
}


Step 5: This is the default implementation of the above interface, and the class that is responsible for calculating the funded from cash and proceed to cash values.




import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;

public class DefaultCashVarianceCalculationStrategy implements CashVarianceCalculationStrategy {

@Override
public CashVariance calculate(List<InvestmentDetail> investments) {
//input validation
if(investments == null){
throw new IllegalArgumentException("No investments founds!!!");
}

List<BigDecimal> buys = new LinkedList<BigDecimal>();
List<BigDecimal> sells = new LinkedList<BigDecimal>();
List<BigDecimal> switchables = new LinkedList<BigDecimal>(); //pay for buys from the sells

for (InvestmentDetail detail : investments) {
if(detail.isBuy()){
processBuy(detail, buys, switchables);
}
else if(detail.isSell()){
processSell(detail, sells, switchables);
}
}

CashVariance variance = calculateVariance(buys, sells, switchables);

return variance;
}

private void processSell(InvestmentDetail detail, List<BigDecimal> sells, List<BigDecimal> switchables) {
if(isSwitch(detail)){
switchables.add(detail.getOrderAmount()); //+ve amount
}
else{
sells.add(detail.getOrderAmount());
}

}

private void processBuy(InvestmentDetail detail, List<BigDecimal> buys, List<BigDecimal> switchables) {
if(isSwitch(detail)){
switchables.add(detail.getOrderAmount().negate()); //-ve amount
}
else{
buys.add(detail.getOrderAmount());
}

}

//protected so that it can be overridden by another strategy
protected boolean isSwitch(InvestmentDetail detail){
return detail != null && (detail.isDailyManagedFund() || detail.isListedSecurity()); //return false if it is a monthly managed fund
//This has to be funded from cash.
}

protected CashVariance calculateVariance(List<BigDecimal> buys, List<BigDecimal> sells, List<BigDecimal> switchables) {
BigDecimal switchedSum = sumAll(switchables);
BigDecimal fundedFromCash = calculateFundedFromCash(buys, switchedSum);
BigDecimal proceedsToCash = calculateProceedsToCash(sells, switchedSum);

return new CashVariance(fundedFromCash, proceedsToCash);
}

private BigDecimal calculateFundedFromCash(List<BigDecimal> buys, BigDecimal switchedSum) {
BigDecimal buysSum = sumAll(buys);
//if switchedSum has more buy amount (i.e negative) add the switchedSum to buy
return buysSum.add((switchedSum.signum() == -1) ? switchedSum.abs() : BigDecimal.ZERO);
}

private BigDecimal calculateProceedsToCash(List<BigDecimal> sells, BigDecimal switchedSum) {
BigDecimal sellsSum = sumAll(sells);
//if switchedSum has more sell amount (i.e positive) add the switchedSum to sell
return sellsSum.add((switchedSum.signum() == 1) ? switchedSum : BigDecimal.ZERO);
}


private BigDecimal sumAll(List<BigDecimal> values) {
BigDecimal total = BigDecimal.ZERO;
for (BigDecimal val : values) {
total = total.add(val);
}
return total;
}

}

Q. Why use a strategy design pattern?
A.  A strategy design pattern allows you to choose different algorithms at run time depending certain run time conditions like product type. Different algorithms can be isolated in different implementation classes that implement the same interface. Different client classes or invokees can execute different strategies (i.e. algorithms).

Step 6: Finally, the tester class that demonstrates the  above scenario by constructing investment details and calculating the variance as shown below.


import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;

public class VarianceCalcTester {

public static void main(String[] args) {
InvestmentDetail ab0001 = new InvestmentDetail("AB0001", "AB Manged Fund",
InvestmentDetail.TRADE_TYPE.BUY, InvestmentDetail.FUND_TYPE.MONTHLY,
new BigDecimal("2500.00"));

InvestmentDetail cx0002 = new InvestmentDetail("CX0002", "CX Managed Fund",
InvestmentDetail.TRADE_TYPE.BUY, InvestmentDetail.FUND_TYPE.DAILY,
new BigDecimal("4500.00"));

InvestmentDetail by007 = new InvestmentDetail("BY007", "BY Managed Fund",
InvestmentDetail.TRADE_TYPE.BUY, InvestmentDetail.FUND_TYPE.DAILY,
new BigDecimal("2000.00"));


InvestmentDetail sh0008 = new InvestmentDetail("SH0008", "BY Managed Fund",
InvestmentDetail.TRADE_TYPE.SELL, InvestmentDetail.FUND_TYPE.NOT_APPLICABLE,
new BigDecimal("8000.00"));

List<InvestmentDetail> investments = new LinkedList<InvestmentDetail>();

investments.add(ab0001);
investments.add(cx0002);
investments.add(by007);
investments.add(sh0008);


//get the variance calculation strategy from the factory

CashVarianceCalculationStrategy cvCalcStaregy = VarianceCalculationFactory.getCashVarianceStrategy(null); // return the default strategy

CashVariance cv = cvCalcStaregy.calculate(investments);


System.out.println(cv); // -ve variance Debit and +ve variance Credit
}
}


Spring Framework Java I/O and the Decorator and proxy design pattern interview questions and answers



Q. Can you explain the decorator design pattern?
A. By implementing the decorator pattern you construct a wrapper around an object by extending its behavior. The wrapper will do its job before or after and delegate the call to the wrapped instance. The decoration happens at run-time. In Java, the wrapper classes like Integer, Double, etc are typical example of a decorator pattern. Another good example is the Java I/O classes as shown below. Each reader or writer will decorate the other to extend or modify the behavior.

String inputText = "Some text to read";
ByteArrayInputStream bais = new ByteArrayInputStream(inputText.getBytes());
Reader isr = new InputStreamReader(bais);
BufferedReader br = new BufferedReader(isr);
br.readLine();


As you can see, each reader extends the behavior at run-time. This is the power of object composition as opposed to inheritance. By composing a fewer classes at run-time, desired behavior can be created. Here is another example demonstrating an interleaved reading using a class from the Apache library.

import java.io.*;
import org.apache.commons.io.input.TeeInputStream;

class InterleavedReadingFromFile {
public static void main(String[] args) throws IOException {

// Create the source input stream.
InputStream is = new FileInputStream("c:\temp\persons.txt");

// Create a piped input stream for one of the readers.
PipedInputStream in = new PipedInputStream();

// Create a tee-splitter for the other reader. This is from the Apache library
TeeInputStream tee = new TeeInputStream(is, new PipedOutputStream(in));

// Create the two buffered readers.
BufferedReader br1 = new BufferedReader(new InputStreamReader(tee));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in));

// You can now do interleaved reads
System.out.println("1 line from br1");
System.out.println(br1.readLine());


System.out.println("2 lines from br2:");
System.out.println(br2.readLine());
System.out.println(br2.readLine());
System.out.println();

System.out.println("1 line again from br1:");
System.out.println(br1.readLine());
System.out.println();

}
}


Q. Can you write a class using the decorator design pattern to print numbers from 1-10, and then decorators that optionally print only even or odd numbers?
A. Java decorator pattern


Q. How does a decorator design pattern differ from a proxy design pattern?
A. In Proxy pattern, you have a proxy and a real subject. The relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively constructed at run time. The Decorator Pattern is also known as the Wrapper pattern. The Proxy Pattern is also known as the Surrogate pattern. The purpose of decorator pattern is to add additional responsibilities to an object. These responsibilities can of course be added through inheritance, but composition provides better flexibility as explained above via the Java I/O classes. The purpose of the proxy pattern is to add an intermediate between the client and the target object. This intermediate shares the same interface as the target object. Here are some scenarios in which a proxy pattern can be applied.

  • A remote proxy provides a local representative for an object in a different address space.Providing interface for remote resources such as web service or REST resources or EJB using RMI.
  • A virtual proxy creates expensive object on demand.
  • A protection proxy controls access to the original object.Protection proxies are useful when objects should have different access rights.
  • A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed.
  • Adding a thread-safe feature to an existing class without changing the existing class's code. This is useful when you do not have the freedom to fix thread-safety issues in a third-party library.
The proxy design pattern is explained with a dynamic proxy class to gather performance results in the blog entitled  Java Interview Questions and Answers - performance testing your Java application.



Q. Can you list some of the best practices relating to Java I/O
A.
  1. As demonstrated in Java I/O interview Questions, it is a good practice to close all instances of java.io.Closeable in a finally block.
  2. Use BufferedReader and BufferedWriter to increase efficiency because IO performance depends a lot from the buffering strategy. 
  3. Favor NIO over old IO because the old I/O is stream oriented and uses a blocking IO, whereas the NIO (aka New IO) is Buffer oriented, uses Non blocking I/O and has selectors. 
  4. To avoid issues like "the file reading works in Windows but not in Unix", use java.io.File constructors instead of working with file names as String. The FilenameUtils class in Apache. commons IO handles issues relating to operating systems. 
  5. Apache FileUtils class is  very handy for touching, copying, moving, deleting, calculating the checksum, calculating last modified date, listing and filtering directories, comparing file content, etc.

Spring Framework Java Coding Interview Questions on decorator design pattern and composition


Q. When would you use a decorator design pattern?
A. The Decorator pattern should be used when:
  •     Object responsibilities and behaviors should be dynamically modifiable
  •     Concrete implementations should be decoupled from responsibilities and behaviors

Q. Can you write a class using the decorator design pattern to print numbers from 1-10, and then decorators that optionally print only even or odd numbers?
A. This can be done by sub classing or via inheritance. But too much sub classing is definitely a bad thing. Composition is more powerful than sub classing as you can get different behaviors via decorating at run time. Here is the code, you will realize the power of object composition and why GoF design patterns favors composition to inheritance.


Step 1: Define the interface class.

package com.arul;

public interface NextNumber
{
abstract int getNextNumber();
}


Step 2: Define the implementation classes. The class that gets the numbers.

package com.arul;

public class PrintNumbers implements NextNumber
{
protected int num;

public PrintNumbers(int num)
{
this.num = num;
}

@Override
public int getNextNumber()
{
return ++num; // incremented, assigned, and then returned
}

}

Step 3: The class that gets the odd numbers.

package com.arul;

public class PrintOddNumbers implements NextNumber
{

protected final NextNumber next;

public PrintOddNumbers(NextNumber next)
{
if (next instanceof PrintEvenNumbers)
{
throw new IllegalArgumentException("Cannot be decorated with " + PrintEvenNumbers.class);
}
this.next = next;

}

@Override
public int getNextNumber()
{
int num = -1;

if (next != null)
{

num = next.getNextNumber();
//keep getting the next number until it is odd
while (num % 2 == 0)
{
num = next.getNextNumber();
}
}

return num;
}

}


Step 4: The class that gets the even numbers

package com.arul;

public class PrintOddNumbers implements NextNumber
{

protected final NextNumber next;

public PrintOddNumbers(NextNumber next)
{
if (next instanceof PrintEvenNumbers)
{
throw new IllegalArgumentException("Cannot be decorated with " + PrintEvenNumbers.class);
}
this.next = next;

}

@Override
public int getNextNumber()
{
int num = -1;

if (next != null)
{

num = next.getNextNumber();
//keep getting the next number until it is odd
while (num % 2 == 0)
{
num = next.getNextNumber();
}
}

return num;
}

}

Step 5: The class that gets the multiples of 3s

package com.arul;

public class PrintMultipleOfThreeNumbers implements NextNumber
{

protected final NextNumber next;

public PrintMultipleOfThreeNumbers(NextNumber next)
{
this.next = next;
}

@Override
public int getNextNumber()
{
int num = -1;

if (next != null)
{

num = next.getNextNumber();
//keep getting the next number until it is odd
while (num % 3 != 0)
{
num = next.getNextNumber();
}
}

return num;
}

}






Step 6:  Finally, a  sample file that shows how the above classes can be decorated at run time using object composition to get different outcomes. Additional  implementations of NextNumber  like PrintPrimeNumbers, PrintMultiplesOfSevenPrintFibonacciNumber, etc can be added using the Open-Closed design principle.

package com.arul;

public class TestNumbersWithDecorators
{
public static void main(String[] args)
{

//without decorators
PrintNumbers pn = new PrintNumbers(0);
for (int i = 0; i < 10; i++)
{
System.out.print(pn.getNextNumber() + " "); // print next 10 numbers
}

System.out.println();

PrintNumbers pn2 = new PrintNumbers(0);
//print odd numbers with decorators
PrintOddNumbers pOdd = new PrintOddNumbers(pn2); // decorates pn2
for (int i = 0; i < 10; i++)
{
System.out.print(pOdd.getNextNumber() + " "); //print next 10 odd numbers
}

System.out.println();

PrintNumbers pn3 = new PrintNumbers(0);
//print even numbers with decorators
PrintEvenNumbers pEven = new PrintEvenNumbers(pn3); // decorates pn3
for (int i = 0; i < 10; i++)
{
System.out.print(pEven.getNextNumber() + " "); //print next 10 even numbers
}

System.out.println("");

PrintNumbers pn4 = new PrintNumbers(0);
//print odd numbers with decorators
PrintOddNumbers pOdd2 = new PrintOddNumbers(pn4); // decorates pn4
//print multiples of 3 with decorators
PrintMultipleOfThreeNumbers threes = new PrintMultipleOfThreeNumbers(pOdd2); // decorates pOdd2
for (int i = 0; i < 10; i++)
{
System.out.print(threes.getNextNumber() + " "); // print next 10 odd numbers
// that are multiple of threes
}

System.out.println("");

PrintNumbers pn5 = new PrintNumbers(0);
//print even numbers with decorators
PrintEvenNumbers pEven2 = new PrintEvenNumbers(pn5); // decorates pn5
//print multiples of 3 with decorators
PrintMultipleOfThreeNumbers threes2 = new PrintMultipleOfThreeNumbers(pEven2); // decorates pEven2

for (int i = 0; i < 10; i++)
{
System.out.print(threes2.getNextNumber() + " "); // print next 10 even numbers
// that are multiple of threes
}

System.out.println("");

PrintNumbers pn6 = new PrintNumbers(0);
//print multiples of 3 with decorators
PrintMultipleOfThreeNumbers threes3 = new PrintMultipleOfThreeNumbers(pn6); // decorates pn6
//print even numbers with decorators
PrintEvenNumbers pEven3 = new PrintEvenNumbers(threes3); // decorates threes3

for (int i = 0; i < 10; i++)
{
System.out.print(pEven3.getNextNumber() + " "); // print next 10 multiple of threes
// that are even numbers
}

}
}

The output of running the above class is

1 2 3 4 5 6 7 8 9 10 
1 3 5 7 9 11 13 15 17 19
2 4 6 8 10 12 14 16 18 20
3 9 15 21 27 33 39 45 51 57
6 12 18 24 30 36 42 48 54 60
6 12 18 24 30 36 42 48 54 60


Spring Hibernate Article: Using Builders instead of Constructors to create Immutable objects

This article explains how you can create immutable objects in Java by using the builder design pattern as opposed to constructors. This will make your code more readable. Firstly, let's see what is not so elegant about using a constructor as shown below with a CashBalance object that takes 3 BigDecimal arguments. Then we will see how a builder class will make your code more intuitive.

Next time you are asked to explain a design pattern in an interview, you could pick this as opposed to the very common factory and singleton design patterns. This article also touch on other two important concepts like immutability and thread-safety.

import java.math.BigDecimal;

/**
* Immutable, hence thread safe CashBalance object
*/
public final class CashBalance {

private BigDecimal initialBalance;
private BigDecimal totCredits;
private BigDecimal totDebits;

//construct
public CashBalance(BigDecimal initialBalance, BigDecimal totCredits, BigDecimal totDebits) {
this.initialBalance = initialBalance;
this.totCredits = totCredits;
this.totDebits = totDebits;
}

//only getter methods and not setter methods as it is an immutable object

}


So, why wasn't it elegant? The constructor takes 3 BigDecimal arguments, and for the user of the class it is not intuitive enough as to which is initialBalance, which is totCredits, etc. It would have been nicer if you could invoke the constructor something like


CashBalance bal = new CashBalance(initialBalance:BigDecimal.valueOf(250.00), 
totCredits:BigDecimal.valueOf(250.00),
totDebits:BigDecimal.valueOf(250.00));

Unfortunately, you can't use above syntax. You need to invoke it as shown below.

CashBalance bal = new CashBalance(BigDecimal.valueOf(250.00), 
BigDecimal.valueOf(250.00),
BigDecimal.valueOf(250.00));




Constructing the object with an empty constructor and 3 setter methods are more elegant, but that will make your object mutable. Here is the builder design pattern to the rescue. Here is the builder defined as an inner class to construct the CashBalance object.
import java.math.BigDecimal;

/**
* Immutable, hence thread safe CashBalance object
*/
public final class CashBalance {

private BigDecimal initialBalance, totCredits, totDebits;

//construct
public CashBalance(CashBalanceBuilder builder) {
this.initialBalance = builder.initialBalance;
this.totCredits = builder.totCredits;
this.totDebits = builder.totDebits;
}

//builder design pattern
public static class CashBalanceBuilder {

//has same fields as the object it is going to build
protected BigDecimal initialBalance, totCredits, totDebits;

//define the setters with package private access
void setInitialBalance(BigDecimal initialBalance) {
this.initialBalance = initialBalance;
}

void setTotCredits(BigDecimal totCredits) {
this.totCredits = totCredits;
}

void setTotDebits(BigDecimal totDebits) {
this.totDebits = totDebits;
}
}

//only getter methods and not setter methods as it is an immutable object

}
Now, you can construct the CashBalance object from outside the class as shown below.  

public static void main(String[] args) {
CashBalance.CashBalanceBuilder builder = new CashBalance.CashBalanceBuilder();
builder.setInitialBalance(BigDecimal.valueOf(250.00));
builder.setTotCredits(BigDecimal.valueOf(250.00));
builder.setTotDebits(BigDecimal.valueOf(250.00));
CashBalance bal = new CashBalance(builder);
}

The above code does the job, but if you have many number of fields, the construction code will be very verbose. This can be further improved as shown below.

The following improved method changes the void setter methods to return the builder itself after setting the value.

import java.math.BigDecimal;

/**
* Immutable, hence thread safe CashBalance object
*/
public final class CashBalance {

private BigDecimal initialBalance, totCredits, totDebits;

//construct
public CashBalance(CashBalanceBuilder builder) {
this.initialBalance = builder.initialBalance;
this.totCredits = builder.totCredits;
this.totDebits = builder.totDebits;
}


public static class CashBalanceBuilder {

//has same fields as the object it is going to build
protected BigDecimal initialBalance, totCredits, totDebits;

//define the setters that return itself
CashBalanceBuilder setInitialBalance(BigDecimal initialBalance) {
this.initialBalance = initialBalance;
return this;
}

CashBalanceBuilder setTotCredits(BigDecimal totCredits) {
this.totCredits = totCredits;
return this;
}

CashBalanceBuilder setTotDebits(BigDecimal totDebits) {
this.totDebits = totDebits;
return this;
}
}

//only getter methods and no setter methods as it is an immutable object

}

The beauty of the change is that now the oCashBalance construction code becomes:

public static void main(String[] args) {
CashBalance.CashBalanceBuilder builder = new CashBalance.CashBalanceBuilder()
.setInitialBalance(BigDecimal.valueOf(250.00))
.setTotCredits(BigDecimal.valueOf(250.00))
.setTotDebits(BigDecimal.valueOf(250.00));
CashBalance bal = new CashBalance(builder);
}


So, these kinds of "know hows" will be noticed in peer code reviews and will help you earn a reputation as a go to person.


Similar post:

Spring MVC Framework Singleton Design Pattern Questions

Singleton Design Pattern is the basic design pattern that most of the developers seems to learn at the very early stages of their career (including me). So it is natural that there are lot questions that interviewers asked in order to see whether the person has just crammed up the definition or actually knows how to write it as well. Also, the implementation of this pattern has also changed a lot over time and a thorough knowledge of the same would mean that the person is also up to date with the new techniques.
Question 1: Explain Singleton Design Pattern?
Singleton Design Pattern means there is only one instance of an object in the Application / per classloader.

Question 2: What are the things required to implement a Singleton class?
Singleton class should have a private constructor and there is only way to create singleton instance.

Question 3: How do you implement Singleton?
In order to create a Singleton please see below:

     public class SingleTon {
private static SingleTon INSTANCE;

private SingleTon() {
}

public static SingleTon getInstance() {
if (INSTANCE == null) {
INSTANCE = new SingleTon();
}

return INSTANCE;
}
}
Question 4: Is the above class thread-safe?
The problem with the above class is that if two methods execute the getInstance() method, both of them might be able to create an instance and hence violating the Singleton condition. In order to achieve thread-safety, we can make the getInstance() method synchronized. as below:

     public class SingleTon {
private static SingleTon INSTANCE;

private SingleTon() {
}

public synchronized static SingleTon getInstance() {
if (INSTANCE == null) {
INSTANCE = new SingleTon();
}

return INSTANCE;
}
}
Question 5: In the above solution synchronizing the static method will give you a class level lock and hence have performance impact? How can you remove that?
In order to remove the synchronizing we can have a static field instantiating the Singleton as below:

     public class SingleTon {
private static final SingleTon INSTANCE = new SingleTon();

private SingleTon() {
}

public static SingleTon getInstance() {
return INSTANCE;
}
}
The problem with the above class is that if your Singleton class have lot of constructs you might end up creating them even though you may not need them. So above should only be used if the Singleton is not very heavily loaded.This type of initialization is also known as Eagerly Initialization whereas the above initialization is known as Lazy Initialization.

Question 6: How to improve the above solution incase the class is heavily loaded?
In that case we would like to delay the instantiation process as below, by using an inner static class:
public final class SingleTon {
private static class SingleTonHolder {
private static SingleTon INSTANCE = new SingleTon();
}

private SingleTon() {}

public static SingleTon getInstance() {
return SingleTonHolder.INSTANCE;
}
}
Question 7: How do you prevent the Singleton class creation using reflection?
One way to do that is to throw an exception from the Constructor as follows:
public final class SingleTon {
private static class SingleTonHolder {
private static SingleTon INSTANCE = new SingleTon();
}

private SingleTon() {
if(SingleTonHolder.INSTANCE != null) {
throw new IllegalStateException("Already Instantiated");
}
}

public static SingleTon getInstance() {
return SingleTonHolder.INSTANCE;
}
}
Question 8: Is there any other method that can be used to create a Singleton class?
Other method that can be used to create a Singleton class is the enum method, this solution is only applicable post Java 1.5. This is possible using Enum as:
public enum SingleTon3 {
INSTANCE;
// Other instance methods.
}
The advantage of using this is that, Java Memory Model guarantees that there will a single instance of the Enum and Enums are thread-safe as well.

Question 9: What do you understand by the double checked locking in Singleton pattern?
Double checked locking means that the INSTANCE is checked for NULL twice, before and after acquiring lock. Remember that it is only possible after Java 5, with the better handling of volatile fields. This may not work before Java 5.
     public final class SingleTon {
private SingleTon INSTANCE;

private SingleTon() {
if(INSTANCE != null) {
throw new IllegalStateException("Already Instantiated");
}
}

public static SingleTon getInstance() {
if(INSTANCE == null) {
synchronized(this) {
if(INSTANCE==null) {
INSTANCE = new SingleTon();
}
}
}

return INSTANCE;
}
}
Question 10: How do you avoid a Singleton being created by serialization?
This problem occurs when your Singleton implements Serializable. The readResolve() method will always return a new instance of the class, just like Constructor. In order to avoid this you can override the readResolve() method to return your INSTANCE as:
     public final class SingleTon {
private volatile SingleTon INSTANCE;

private SingleTon() {
if(INSTANCE != null) {
throw new IllegalStateException("Already Instantiated");
}
}

public static SingleTon getInstance() {
if(INSTANCE == null) {
synchronized(this) {
if(INSTANCE==null) {
INSTANCE = new SingleTon();
}
}
}

return INSTANCE;
}

private Object readResolve(){
return INSTANCE;
}
}
This can even become more complex if your Singleton starts to manage states, as then the states have to be transient. This problem can also be handled by Enums, as the serialization is handled by the JVM.
Question 10: Why should you avoid Singleton anti-pattern or why is Singleton is an anti-pattern?
  1. In order to use Singleton we need to call getInstance(), which makes them tightly coupled to the calling object and hence makes them hard to mock while testing.
  2. They maintain their state during the lifetime of the application and hence makes unit testing difficult as you may need to execute your Junit in an order. This voids the basic principle of Unit testing that the tests should be independent of each other.
  3. They violate the Single Responsibility Priniciple, as they manage the creation and lifecycle themselves.
  4. They are generally used as a global variable and creating global variable just to avoid passing them around is a code smell. 

Java J2EE Spring Design patterns interview Questions and answers: observer pattern

The design patterns are very popular with the interviewers and Java/J2EE Job Interview Companion covers GoF design patterns, J2EEE design patterns, and EJB design patterns. This blog entry covers the observer design pattern.

Q. What is an observer design pattern?
A. The Observer pattern is a behavioral design pattern that  allows an object (an Observer) to watch another object (a Subject). The subject and observer to have a publish/subscribe relationship. Observers can register to receive events from the Subject.

Some of the practical uses of observer pattern are:

  • When a change to one object requires changing of others, and you don't know how many objects need to be changed.
  • When an object should be able to notify other objects without making assumptions about who these objects are and not tightly coupling them.
  • When a report is received or an event occurs, a message needs to be sent to the subscribed handlers.

Examples:

  • Programming Swing based GUI applications where the listeners register them with events like button click, property change, etc.
  • Programming a stock market application to know when the price of a stock changes.
  • Programming a order placement or trading application to know the status changes like pending, filled, shipped, rejected, etc.

So, whenever you want to have the state change or other information, instead of polling every few second, register the observers with a subject. 






Here is some pseudo code of this third scenario

STEP 1: Define the Subject and Observer interfaces

This is the subject interface


package com;

public interface ReportExecutor {
public void addHandler(ReportHandler rh);
public void removeHandler(ReportHandler rh);
public void processReport(String message);
}


This is the observer interface

package com;

public interface ReportHandler {
//handles report
public void handleMessage(String message);
}


STEP 2: Define the concrete subject and observers.


The concrete subject

package com;

import java.util.ArrayList;
import java.util.List;

public class SalesReportExecutor implements ReportExecutor {

//list of observers that register their interest in SalesReport
private List<reporthandler> reportHandlers = new ArrayList<reporthandler>();

@Override
public void addHandler(ReportHandler rh) {
reportHandlers.add(rh);
}

@Override
public void processReport(String message) {
for (ReportHandler reportHandler : reportHandlers) {
reportHandler.handleMessage(message);
}
}

@Override
public void removeHandler(ReportHandler rh) {
reportHandlers.remove(rh);

}

}

The concrete observers

package com;

public class LoggingReportHandler implements ReportHandler {

@Override
public void handleMessage(String message) {
//handles report by formatting and printing
System.out.println("Logging report " + message);
}
}


package com;

public class EmailReportHandler implements ReportHandler {

@Override
public void handleMessage(String message) {
//handles the report by formatting it differently and emailing.
System.out.println("Emailing report " + message);
//logic to email report.
}
}


STEP 3: Finally, the JMS listener class that uses the subject. The JMS Listener class listens on a queue for presence of a report.

package com.mgl.mts.fix;

import javax.jms.Message;
import javax.jms.TextMessage;

public class MyAppListener {

public void onMessage(Message message) {
if (message instanceof TextMessage) {

ReportExecutor executor = new SalesReportExecutor();
executor.addHandler(new LoggingReportHandler());
executor.addHandler(new EmailReportHandler());
executor.processReport(message.toString());

} else {
throw new IllegalArgumentException("Message must be of type TextMessage");
}
}
}

Q. Can you list some Java interfaces that use the observer design pattern?
A.

  • The Java Message Service (JMS) models the observer pattern, with its guaranteed delivery, non-local distribution, and persistence, to name a few of its benefits. The JMS publish-subscribe messaging model allows any number of subscribers to listen to topics of interest. When a message for the published topic is produced, all the associated subscribers are notified.
  • The Java Foundation Classes (JFC) like JList, JTree and the JTable components manipulate data through their respective data models. The components act as observers of their data models.
  • In the java.util package, we have the Observer interface and the Observable class.
  • In an MVC (Model-View-Controller) architecture, the view gets its own data from the model or in some cases the controller may issue a general instruction to the view to render itself. In others, the view acts as an observer  and is automatically notified by the model of changes in state that require a screen update.


Q. What are the pros and cons of an Observer design pattern?
A.

PROS:

  • Loose coupling between Subject and Observer: The subject knows only a list of observers, that implement the Observer interface, it does no know the concrete implementation of the Observer.
  • Broadcast communication: An event notification is broadcast to observers irrespective of the number of Observers

CONS:

  • If not used carefully the observer pattern can add unnecessary complexity.
  • The order of Observer notifications is undependable. Simply registering the observers in a particular order will not enforce their order of notification. You don't necessarily know if the first registered listener is notified first or last. If you need to have cascading notifications, where object X must be notified first, followed by object Y, you must introduce an intermediary object to enforce the ordering. 
  • The possibility of a memory leak. A reference to the Observer is maintained by the Subject. Until the Subject releases the reference, the Observer cannot be removed by the garbage collector.

Relevant other design patterns:

Labels

.equals = operator abstract class abstract method abstract window toolkit Access Modifiers accessing java beans accessing javabeans action events actionperformed active addition Advanced Advanced Overloading AdvJavaBooks Agile development ajax alive AMQP and Android anonymous class anonymous inner class Ant ant tutorials anti patterns antipatterns Apache Camel api for jsp api for servlet api for servlets api jsp application context application scope application session Apps Architecture are you eligible for the ocmjd certificaiton are you eligible for the scjd certification arithmetic operator arpanet array construction array declaration array initialization array list array to list conversion arraylist arraylist of strings arraylist of types arraylist questions arraylists Arrays arrays in java ask for help assert assert in java assertions assertions in java assignment assignment operator Atlassian attribute visibility authentication authorization autoboxing autounboxing awt AWT Event Handling awt interview questions AWT Layouts awt questions awt questions and answers backed collection backed collections Basic Basics of event handling bean attributes bean properties bean scope Beginner best practices BigData blocked books boxing buffer size bufferedreader bufferedwriter business delegate business delegate pattern calendar case statement casting in java casting interview questions chapter review choosing a java locking mechanism choosing a locking mechanism choosing a thread locking mechanism class inside a method class questions class with no name class without a name classes interview questions Clipboard closing jsp tags code snap coding cohesion collection generics collection interview questions collection methods collection of types collection questions collection searching collection types Collections Collections Framework collections interview questions collections sorting colors in java swings colors in swing command line arguments communication between threads comparable comparator comparison operators compiling java classes computers concurrency example and tutorial config Configuration ConnectionPooling constructor creation constructor interview questions constructor overloading constructors in java containers contents of deployment descriptor contents of web.xml context context scope converting array to list converting list to array core java core java interview core java interview question core java interview questions core java questions core java; core java; object oriented programming CoreJava CoreJavaBooks CORS coupling create threads creating 2 dimensional shapes creating 2D shapes creating a frame creating a jframe creating a thread creating an arraylist creating an inner class creating an interface creating java beans creating java threads creating javabeans creating threads creating threads in java CSS cURL currency current thread determination custom tag library custom taglib custom taglibs custom tags CVS dao dao design pattern dao factory pattern dao pattern data access object data access object pattern data structure and algorithm database date and time tutorial date format dateformat dates deadlock deadlocks debugging Declarations decorator pattern decrement default deleting sessions deploy web app deployment deployment descriptor deployment descriptor contents deployment of web application deserialization deserialize design pattern design pattern interview questions design patterns Designpatterns destory method destroy destroying sessions determining current thread determining the current thread Developer Differences different types of collections display stuff in a frame displaying images displaying images in java swings displaying images in swings displaying text in a component division do while loop doget dohead dopost doput DOS Downloads drawing a line drawing an ellipse drawing circles drawing ellipses drawing lines Drools tutorial eBooks Eclipse Eclipse Tutorial Encapsulation encapsulation in java enhanced for loop entity facade pattern enumerations enumerations in java enums equal to equals equals comparison error and exception error codes error handling in servlets error page event handling in swings event listeners exam prep tips example servlet Examples exception exception handling exception handling in servlets exception handling interview questions exception handling questions Exceptions exceptions in java exceptions in web applications explicit locking explicit locking of objects file file navigation filereader filewriter final class final method FireBug first servlet FIX protocol FIX Protocol interview questions FIX protocol tutorial font fonts for each loop for loop form parameters form values formatting forwarding requests frame frame creation frame positioning frame swings front controller front controller design pattern front controller pattern fundamental.Java FXML Games garbage collection garbage collection interview questions garbage collection questions garbage collector gc gc questions general generic Generics generics collections Geo get get set methods getattribute getting bean property getting form values getting form values in servlet getting scwcd certified getting servlet initialization parameters getting sun certified Google Graphics2D gregorian calendar handling strings in java hash hash map hash table hashcode hashmap hashset hashtable head head request HeadFirst heap heaps hibernate hibernate interview questions hibernate interview questions and answers hibernate questions hibernate questions and answers Hibernate Tutorial HibernateBooks homework How To HTML HTML and JavaScript html form http request http request handling http request header http request methods http request servlet http request type http session httprequest httprequest methods httpservlet httpservlet interview questions httpservlet interview questions with answers httpsession httpsession interview questions httpsession questions HttpSessionActivationListener HttpSessionAttributeListener HttpSessionBindingListener if if else if else block if else statement Image IO implementing an interface Implicit objects increment info inheritance inheritance in java init init method Initialization Blocks inner class inner class inside a method inner classes innerclass installation instanceof instanceof operator IntelliJ interaction between threads interface interface interview interface questions interfaces interfaces in java interfaces interview questions internet history interrupting a thread interrupting threads Interview interview questions interview questions on design patterns interview questions on exception handling interview questions on java collections interview questions on serialization introduction to java threads introduction to jsps introduction to threading introduction to threads invalidating session Investment Banking IO Package iscurrentthread iterator J2EE j2ee api j2ee design pattern j2ee design pattern interview questions j2ee design patterns j2ee hibernate interview questions j2ee history j2ee interview j2ee interview questions j2ee mvc j2ee mvc pattern j2ee programmer j2ee questions j2ee servlet api j2ee session j2ee struts interview questions java java 5 tutorial Java 8 java arrays java assertions java assignments java awt questions java bean java bean scope java beans java beginners tutorial Java career java certification Java Class java collection interview questions and answers java collection tutorial java collections java collections interview questions java constructors java currency Java CV java data base connectivity java database connectivity java database connectivity interview questions and answers java dates java design pattern java design patterns java developer certification Java EE java encapsulation java enums java event listeners java exceptions java formatting java garbage collection java garbage collector java gc java heap Java I/O java inheritance java input output Java Interface Java Interview Java Interview Answers Java Interview Questions Java Introduction java io java IO tutorial java iterator java jdbc Java JSON tutorial Java Key Areas java lists java literals java locks nested Java Media Framework java methods java multithreading Java multithreading Tutorials java nested locks java networking tutorial java numbers Java Objects java operators java overloading java parsing Java Programming Tutorials java race conditions java regex java regular expressions Java resume java scjp java searching java serialization java server pages java server pages api java server pages questions java spring interview questions. j2ee spring interview questions java stack java strings java swing java swing event listeners java swing frame java swing images java swings java swings images java thread explicit locking java thread lock scope java thread locking java thread locking mechanism java thread locking objects java threads java threads race condition java tips java tokenizing Java Tools Java Tutorial java ui questions Java Utilities java variables java wrappers Java xml tutorial java.lang java8 javabean javabean accessing javabean scope JavaBeans javac JavaEE JavaFX JavaFX 3D JavaFX 8 JavaOne JavaScript JavaTips JDBC jdbc driver jdbc example jdbc interview questions jdbc interview questions and answers jdbc interview questions with answers jdbc sample code JDBC Tutorial jdbc type 1 driver jdbc type 2 driver jdbc type 3 driver jdbc type 4 driver Jdeveloper JDK JDK8 JEE Tutorial jframe jframe creation jframe position jframe positioning JIRA JMeter JMS JMX join() joining threads JPA JQuery JS JSF JSF Tutorial JSONP JSP jsp and java beans jsp and servlets jsp and xml jsp api jsp code jsp compilation jsp conversion jsp directives jsp error page jsp error page directive jsp implicit objects jsp interview jsp interview questions jsp introduction jsp intvw questions jsp life jsp life cycle jsp life-cycle jsp lifecycle jsp page directive jsp questions jsp sample jsp scripting jsp scriptlets jsp servlets jsp summary jsp synopsis jsp tag libraries jsp tag library jsp taglib jsp tags jsp technology jsp to servlet jsp to servlet conversion jsp translation jsp usage jsp usebean jsp xml tags jsp xml tags usage jsp-servlet jsp:getProperty jsp:setProperty jsp:usebean jsps JSTL JUnit testing keyword synchronized keyword volatile Keywords Lambda Expressions Learning libraries life cycle life cycle of a jsp life cycle of a servlet life cycle of a thread life cycle of jsp life cycle of threads lifecycle of a thread linked list linkedhashmap linkedhashset linkedlist linux List listeners lists Literals locale lock manager pattern lock scope locking objects using threads log Logging logging errors logical and logical operators logical or loops loosely coupled making an arraylist making threads sleep making threads sleep for time MapReduce maps maps usage Maven Maven Tutorial max priority member access method arguments method local inner class method overloading method overriding method return types methods creating classes min priority Miscellaneous mobile mock exam model view controller model view controller design pattern model view controller pattern Multi Threading Multi-threading multiple threads multiplication multithreading multithreading in java multithreading interview questions multithreading questions mvc mvc design pattern mvc pattern MyEclipse mysql nested java lock nested java locks nested java thread locks nested locks nested thread locks NetBeans Networking new news nio NonAccess Modifiers norm priority normal inner class Normalization not equal to Notepad notify notifyall number format numberformat numbers object comparison object notify object orientation object oriented object oriented programming Object Oriented Programming in java objects interview questions ocmjd certification ocmjd certification eligibility OO OO Java oops OpenCSV OpenCV opening jsp tags OpenJDK OpenJFX Operators or Oracle Oracle ADF Mobile Oracle Certified Exams oracle certified master java developer oracle database ORM other topics out overloading overloading constructors overloading in java overriding page page directive page scope parsing passing variables passing variables to methods performance Platform Playing with Numbers points to remember polymorphism positioning a frame post practice exam Primitive Casting primitive variables printwriter priority queue priority queues priorityqueue priorityqueues private processing form values Products programming Projects protected public put questions questions on garbage collection questions on java strings queue quick recap quick review race conditions read objects from stream reading http request header RealTime_Tips redirecting to another servlet redirection reference reference variable casting reference variables Refreshing Java regex Regular Expressions regular inner class relational operators reminder request request dispatcher request forwarding request header request object. httpservletrequest request scope requestdispatcher response RESTClient RESTful retrieving values from session return error codes return types returning values runnable runnable interface running running java programs RUP sample jsp sample questions sample questions scwcd sample servlet scanner Scene Builder scjd certification scjd certification eligibility requirements scjp SCJP Certification scjp exam scjp exam questions scjp exam sample questions scjp questions scjp test scjp test questions scope scope of java locks scope of java thread locks scope of locks scripting in jsp scriptlet tags scriptlets scriptlets in jsp pages scwcd scwcd certification scwcd certification practice exam scwcd exam scwcd exam questions scwcd jsp summary scwcd mock exam scwcd mock exam answers scwcd practice exam scwcd practice test scwcd questions scwcd test SDLC searching searching arrays searching collections searching in java searching treemap searching treesets security self assement self assement scwcd self assessment scjp self test self test scjp self test scwcd send error method senderror method sending error code to browser serialization serialization in java serialization interview questions Serialization on Swing serialization questions service service method servlet servlet and forms servlet and jsp servlet api servlet attributes servlet code servlet container servlet context servlet error handling servlet exception handling servlet handling http request servlet initialization servlet initialization parameters servlet interview servlet interview questions servlet interview questions with answers servlet intvw questions servlet life cycle servlet lifecycle servlet questions servlet questions with answers servlet request servlet request dispatcher servlet request type servlet skeleton servletcontext servletcontextevent servletrequest Servlets servlets and jsps servlets api servlets details servlets request handling session session clean up session event listeners session facade pattern session interview questions session invalidation session listeners session management session questions session scope session timeout session tracking through url rewriting set collections set status method setattribute sets setstatus method setting bean property setting request type short circuit operators Singleton sleep sleeping threads soapUI Software Installation sorting sorting arraylist sorting arrays sorting collections special collections special inner classes split spring spring and hibernate interview questions spring batch Spring Core Spring Framework Spring Integration spring interview questions Spring JDBC Spring MVC Spring security Spring tutorial SQL SQL and database tutorial examples SQL Tutorial SSL stack stacks stacks and heaps static static class static declaration static imports static inner static inner class static method Static variable stopped stopping a thread stopping thread stopping threads Stored Procedure storing values in session Streams strictfp StrictMath string string buffer string builder string class string formatting String Handling string interview questions string manupulation string questions string tokenizer stringbuffer stringbuffer questions stringbuilder Strings strings in java struts Struts 1 Struts 1.2 Struts 2 struts framework interview questions struts interview questions struts interview questions with answers struts mvc interview questions struts questions Struts2 StrutsBooks submitting request subtraction Sun Certification sun certified java developer Sun Certified Java Programmer swing swing action performed swing and colors Swing Components swing event handling swing event listeners swing events Swing Hacks swing images Swing Look And Feels swings swings frame switch block switch case block switch case statement Sybase Sybase and SQL Server synchronization synchronized code synchronized keyword synchronized method System Properties tag lib tag library tag-lib taglibs tags TDD Technical Blogging ternary operator Test Driven Development test scjp Testing the context the session the volatile keyword thread thread class thread deadlocks thread interaction thread interruption thread life cycle thread lifecycle thread lock scope thread locks thread notify thread priorities thread race conditions race conditions in threads thread sleep thread states thread stoppage thread stopping thread synchronization thread syncing thread yield Threads threads in java threads interview questions threads life cycle threads questions tibco tightly coupled tips tips and tricks tips.FXML tokenizing Tomcat Tools toString transitions treemap treeset tricks Tricks Bag try catch try catch finally. finally block Tutorial type casting in java ui programming with java swings UML unboxing unit testing unix url rewriting use bean usebean using a arraylist using collections using colors using colours using command line arguments using different fonts using expressions using font using fonts using fonts in swings using hashmap using http session using httpsession using iterator using java beans in jsp using javabean in jsp using javabeans in jsp using javac using lists using maps using request dispatcher using scriptlets using session persistense using sets using special fonts using system properties using the jsp use bean using treeset using use bean Using Variables using volatile Using Wrappers using xml in jsp Util pack value object value object design pattern value object pattern var-args varargs Variable Arguments Variables vector vector questions vectors visibility vo pattern volatile volatile keyword volatile variables wait method waiting web app exception handling web app interview web application deployment web application exceptions web application scope web application security web component developer web component developer certification web context web context interfaces web context listeners web interview questions web security web server web servers Web services web.xml web.xml deployment webapp log weblogic website hacking website security what are threads what is a java thread what is a thread what is thread while loop windows windows 8 wrapper classes wrappers write objects to stream WSAD xml xml and jsp xml tags xslt yield()