Java Tutorial : Hands on project for library management application

I am coding Library Management Project in Java and teaching it in simple steps.
If you are interested in doing or learning Java with hands on project then check out this play list from my youtube video 🙂

Git Repo :

Project requirements:
For details visit :

Java : How to setup and run activeMQ for JMS on macos

Setup using command of home brew : 

➜ software brew install apache-activemq
==> Downloading
==> Best Mirror

curl: (28) Resolving timed out after 5539 milliseconds
Trying a mirror…
==> Downloading
######################################################################## 100.0%
🍺 /usr/local/Cellar/activemq/5.13.0: 559 files, 58.9M, built in 2 minutes 41 seconds


Go to default directory of active mq 

When you use brew the default installation directory on mac os is below
➜  software cd /usr/local/Cellar/activemq/

Starting the activemq service 

➜ bin git:(master) activemq start
INFO: Loading ‘/usr/local/Cellar/activemq/5.13.0/libexec//bin/env’
INFO: Using java ‘/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/bin/java’
INFO: Starting – inspect logfiles specified in and to get details
INFO: pidfile created : ‘/usr/local/Cellar/activemq/5.13.0/libexec//data/’ (pid ‘58039’)

Please verifiy the service is running using below command
➜  bin git:(master) ps -eaf | grep activemq

Testing the activemq service on bowser

Open below url and use id as “admin” and password as “admin” to login

Stopping the serving 

➜ bin git:(master) activemq stop
INFO: Loading ‘/usr/local/Cellar/activemq/5.13.0/libexec//bin/env’
INFO: Using java ‘/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/bin/java’
INFO: Waiting at least 30 seconds for regular process termination of pid ‘58039’ :
Java Runtime: Oracle Corporation 1.8.0_60 /Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre
Heap sizes: current=62976k free=61664k max=932352k
JVM args: -Xms64M -Xmx1G -Dactivemq.classpath=/usr/local/Cellar/activemq/5.13.0/libexec//conf:/usr/local/Cellar/activemq/5.13.0/libexec//../lib/ -Dactivemq.home=/usr/local/Cellar/activemq/5.13.0/libexec/ -Dactivemq.base=/usr/local/Cellar/activemq/5.13.0/libexec/ -Dactivemq.conf=/usr/local/Cellar/activemq/5.13.0/libexec//conf
Extensions classpath:
ACTIVEMQ_HOME: /usr/local/Cellar/activemq/5.13.0/libexec
ACTIVEMQ_BASE: /usr/local/Cellar/activemq/5.13.0/libexec
ACTIVEMQ_CONF: /usr/local/Cellar/activemq/5.13.0/libexec/conf
ACTIVEMQ_DATA: /usr/local/Cellar/activemq/5.13.0/libexec/data
Connecting to pid: 58039
INFO: Regular shutdown not successful, sending SIGKILL to process
INFO: sending SIGKILL to pid ‘58039’

Other tasks which can run as
$ activemq <taskname>

browse – Display selected messages in a specified destination.
bstat – Performs a predefined query that displays useful statistics regarding the specified broker
consumer – Receives messages from the broker
create – Creates a runnable broker instance in the specified path.
decrypt – Decrypts given text
dstat – Performs a predefined query that displays useful tabular statistics regarding the specified destination type
encrypt – Encrypts given text
export – Exports a stopped brokers data files to an archive file
list – Lists all available brokers in the specified JMX context
producer – Sends messages to the broker
purge – Delete selected destination’s messages that matches the message selector
query – Display selected broker component’s attributes and statistics.
start – Creates and starts a broker using a configuration file, or a broker URI.
stop – Stops a running broker specified by the broker name.

What is ISO date format

As world is becoming a big family with globalization, we need the standard to followed to avoid confusion especially related to date and time. If every country or person would write dates in different format, it would be confusing to figure out exact date while doing communication across countries, hence ISO has come up with ISO date format to be followed by every one. 

International Standard ISO 8601 specifies numeric representations of date and time. This standard notation helps to avoid confusion in international communication caused by the many different national notations and increases the portability of computer user interfaces.



     YYYY = four-digit year

     MM   = two-digit month (01=January, etc.)

     DD   = two-digit day of month (01 through 31)

     hh   = two digits of hour (00 through 23) (am/pm NOT allowed)

     mm   = two digits of minute (00 through 59)

     ss   = two digits of second (00 through 59)

     s    = one or more digits representing a decimal fraction of a second

     TZD  = time zone designator (Z or +hh:mm or -hh:mm)


 1997-07-16T19:20:30.45Z (Z at end indicates time is taken with Zero correction i.e. UTC time)

 1997-07-16T19:20:30.45+01:00 (+1:00 at end indicates time is taken at time zone which is 1:00 ahead of UTC time)

Advantages of the ISO 8601 standard date notation compared to other commonly used variants:

  • easily readable and writeable by software (no ‘JAN’, ‘FEB’, … table necessary)
  • easily comparable and sortable with a trivial string comparison
  • language independent
  • can not be confused with other popular date notations
  • consistency with the common 24h time notation system, where the larger units (hours) are also written in front of the smaller ones (minutes and seconds)
  • strings containing a date followed by a time are also easily comparable and sortable (e.g. write “1995-02-04 22:45:00”)
  • the notation is short and has constant length, which makes both keyboard data entry and table layout easier
  • identical to the Chinese date notation, so the largest cultural group (>25%) on this planet is already familiar with it 🙂
  • date notations with the order “year, month, day” are in addition already widely used e.g. in Japan, Korea, Hungary, Sweden, Finland, Denmark, and a few other countries and people in the U.S. are already used to at least the “month, day” order
  • a 4-digit year representation avoids overflow problems after 2099-12-31

Java Program to find out duplicate number in an Array

Problem statement : In an array 1-100, many numbers are duplicates, how do you find it?

we can loop over array and put the values in a map to find out duplicate numbers with the number of time they repeat them selves.

            int[] numbers = new int [100];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0;i<100;i++){
            int temp = numbers[i];
            Integer count = map.get(temp);
            map.put(temp, (count == null) ? 1 : count + 1);
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println(“Key : ” + entry.getKey() + ” Value repetition time: “
                + entry.getValue());

The solution I proposed gives you the freedom of printing you data in several way or store the data in a manner which is most easy to retrieve. ie create a map for each number and save them against the key.

What is Code Refactoring ?

Refactoring : A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.

Code refactoring is the process of restructuring existing computer code – changing the factoring – without changing its external behavior. Refactoring improves nonfunctional attributes of the software. Advantages include improved code readability and reduced complexity to improve source code maintainability, and create a more expressive internal architecture or object model to improve extensibility. Typically, refactoring applies a series of standardised basic micro-refactorings, each of which is (usually) a tiny change in a computer program’s source code that either preserves the behaviour of the software, or at least does not modify its conformance to functional requirements.

I’ve been asked, “Is refactoring just cleaning up code?” In a way the answer is yes, but I think refactoring goes further because it provides a technique for cleaning up code in a more efficient and controlled manner. Since I’ve been using refactoring, I’ve noticed that I clean code far more effectively than I did before. This is because I know which refactorings to use, I know how to use them in a manner that minimizes bugs, and I test at every possible opportunity.

Like refactoring, performance optimization does not usually change the behavior of a component (other than its speed); it only alters the internal structure. However, the purpose is different. Performance optimization often makes code harder to understand, but you need to do it to get the performance you need. Most of the the time refactoring improves performance in terms of speed as well, however at times its inverse could happen ie by extracting too many classes and introducing too many variable could have an impact of performance as well.

I want to reiterate that refactoring does not change the observable behavior of the software. The software still carries out the same function that it did before.

One thing at a time with TWO HATS ( Refactoring Vs Adding feature )

When you add function, you shouldn’t be changing existing code; you are just adding new capabilities. You can measure your progress by adding tests and getting the tests to work. When you refactor, you make a point of not adding function; you only restructure the code. You don’t add any tests (unless you find a case you missed earlier); you only restructure the code. You don’t add any tests (unless you find a case you missed earlier); you only change tests when you absolutely need to in order to cope with a change in an interface.

As you develop software, you probably find yourself swapping hats frequently. You start by trying to add a new function, and you realize this would be much easier if the code were structured differently. So you swap hats and refactor for a while. Once the code is better structured, you swap hats and add the new function. Once you get the new function working, you realize you coded it in a way that’s awkward to understand, so you swap hats again and refactor. All this might take only ten minutes, but during this time you should always be aware of which hat you’re wearing.


Please note that testing the while refactoring is very import. Always make small changes, test them commit them and make other changes. Do not thing to make all changes in a singe go and later on test entire application at the end. Multiple small cycles of refactor– test – refactor –test and smile Smile  is better then big refactoring – final testing – crying Sad smile

Interpreter Design Pattern

Download the working example demo code in java from my GIT repository –

Example Code Description :
1. Date interpreter example : The main cause of Y2K virus was interpretaiton of date format, in this example code I tried to address the same so that system can intrepret any date given in any formats. we have a interpreter for DD, MM and YYYY (rule to pick the date from context) so you provide the format and system gives you the conversion. Straight forward. 
2. And Or Expression : This example taks a string where in it should match the expression based on rule which accomplies And / Or expression. Code is simple and small but a bit triky to get hold of. Feel free to downlaod and play with it.

Direct link :

  • Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
  • Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design.


Problem Area

This interpreter design pattern does not give solution for building a whole large interpreter for a language. It can be applicable for smaller chunks where grammar and interpretation is applicable. We can consider scenarios like regular expressions and interpreting mathematical expression.


The Interpreter pattern discusses: defining a domain language (i.e. problem characterization) as a simple language grammar, representing domain rules as language sentences, and interpreting these sentences to solve the problem. The pattern uses a class to represent each grammar rule. And since grammars are usually hierarchical in structure, an inheritance hierarchy of rule classes maps nicely.


An abstract base class specifies the method interpret(). Each concrete subclass implements interpret() by accepting (as an argument) the current state of the language stream, and adding its contribution to the problem solving process.


The Intepreter pattern defines a grammatical representation for a language and an interpreter to interpret the grammar. Musicians are examples of Interpreters. The pitch of a sound and its duration can be represented in musical notation on a staff. This notation provides the language of music. Musicians playing the music from the score are able to reproduce the original pitch and duration of each sound represented.

Example of Interpreter

Check list
  1. Decide if a “little language” offers a justifiable return on investment.
  2. Define a grammar for the language.
  3. Map each production in the grammar to a class.
  4. Organize the suite of classes into the structure of the Composite pattern.
  5. Define an interpret(Context) method in the Composite hierarchy.
  6. The Context object encapsulates the current state of the input and output as the former is parsed and the latter is accumulated. It is manipulated by each grammar class as the “interpreting” process transforms the input into the output.

Memento Design Pattern

Download the working example demo code in java from my GIT repository –

Example Code Description :
1. Video Game Example : You can pick your player name, its mask and other details. You earn few more points and get the option to save the games state. Later you can restore your games state as well. The memento is used basically which clones your domain object and keeps it with itself. Care taker is the class which interects with client and talks to Originator. Originator component detals with domain object to save and restore the momento. Download, run and enjoy the game 🙂

Direct link :

  • Without violating encapsulation, capture and externalize an object’s internal state so that the object can be returned to this state later.
  • A magic cookie that encapsulates a “check point” capability.
  • Promote undo or rollback to full object status.

Need to restore an object back to its previous state (e.g. “undo” or “rollback” operations).



The client requests a Memento from the source object when it needs to checkpoint the source object’s state. The source object initializes the Memento with a characterization of its state. The client is the “care-taker” of the Memento, but only the source object can store and retrieve information from the Memento (the Memento is “opaque” to the client and all other objects). If the client subsequently needs to “rollback” the source object’s state, it hands the Memento back to the source object for reinstatement.

An unlimited “undo” and “redo” capability can be readily implemented with a stack of Command objects and a stack of Memento objects.


The Memento design pattern defines three distinct roles:

  1. Originator – the object that knows how to save itself.
  2. Caretaker – the object that knows why and when the Originator needs to save and restore itself.
  3. Memento – the lock box that is written and read by the Originator, and shepherded by the Caretaker.


Check list

  1. Identify the roles of “caretaker” and “originator”.
  2. Create a Memento class and declare the originator a friend.
  3. Caretaker knows when to “check point” the originator.
  4. Originator creates a Memento and copies its state to that Memento.
  5. Caretaker holds on to (but cannot peek into) the Memento.
  6. Caretaker knows when to “roll back” the originator.
  7. Originator reinstates itself using the saved state in the Memento.
Rules of thumb
  • Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
  • Command can use Memento to maintain the state required for an undo operation.
  • Memento is often used in conjunction with Iterator. An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally.