Home » Core Java

Category Archives: Core Java

Java 8 Date Time API

Java 8 Date Time API is one of the best features in Java8.

Why Java 8 Date Time API needed ?
1. Prior to Java8 we have SimpleDateFormatter and java.util.Date and both are not Thread safe.Every application now a days requires concurrency and multithreading support.So slowly application developers started preferring 3rd party library JodaTime over java.util.Date package.This was a concern for Java Team and they come up with Java Date Time API which is thread safe.
2. Prior to Java 8 some of the date and time classes has poor API design in terms of date range.For example,default years in java.util.Date start at 1900,default months start at 1, and default days start at 0, so not very good.
3. Also Developers need to code a lot to handle TimeZone due to poor API design.

Program :::

Output ::

Sort Map by Key and by Value using Java8

Question : Write a program using java 8
1. sort a map by key in natural order
2. sort a map by key in reverse order
3. sort a map by value in natural order
4. sort a map by value in reverse order

Solution ::
The below program takes a hashmap as input and sorts the map by key and by value.

Java Enum

Java Enum Overview ::

1. In java an enum type is a special data type which enables a variable to hold a set of predefined constants.It means basically enum  is a datatype which can hold a set of constants.
2. Directions(EAST,WEST,NORTH,SOUTH) is an example of enum or DAY(SUN,MON,TUE,WED,THU,FRI,SAT) is  an example of enum.
3. enum can be traversed using values() method.
4. enum can have constructor,fields and also user defined methods.
5. enum internally extends enum class ,so it can not extend any other class .enum can implement multiple interfaces.

6. enum can be used in switch statements,enum is final so we can use for Singleton,enum ensures type safety as well.These are some of the reasons why we use enum.

7. You can use valueOf(String arg) to get a particular enum and you can use valueOf(Class<T>  arg, String arg1) to get a particular enum of a class Type.
8. enum was introduced in Java 5 version jdk 1.5

You can directly create enum java file by following the below image.

Let us create an enum called Apartment.

Output ::

Java Regular Expressions

Java Regular Expressions ::

1. java.util.regex API is used for pattern matching using regular expressions
2. java.util.regex.Pattern and java.util.regex.Matcher are the two main classed in java.util.regex API.
3. class java.util.regex.Pattern extends Object class and implements Serializable class.
4. A regular expression, specified as a string, must first be compiled into an instance of Pattern class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.

Validate Email address with regular expression

Write a Program to validate Email address with regular expression ?

ValidEmailMain.java

Output ::

Validate IP address with regular expression

Write a Program to validate IP address with regular expression ?

ValidIPMain.java

Output ::

Java8-ForEach

In this post we are going to code forEach() and forEachOrdered() examples. forEach() method is used to iterate over a collection like List,Set,Map etc or a stream.forEachOrdered() method process the elements in the order the elements are added to collection.

Syntax ::

Program ::
In the below Program I have used three methods to use forEach() over List,Set and Map.I have used the same method to show forEachOrdered() on List and Set using stream.

Output ::

Abstract Factory Design Pattern

Abstract Factory Design Pattern ::Abstract Factory design pattern is also called as factory of factories. This type of design pattern comes under creational design pattern as this pattern provides way to select a factory and then create an instance of related classes of that factory.
 
Real Time Example :: I am going to have two factories where one factory will have VideoPlayer and its implementation classes and another factory will have AudioPlayer and and its implementation classes.Based on user input a factory will be selected and then an instance will be created of related classed of that factory.

 

UML Diagram ::

 

 

Step 1 :
Create an Interface VideoPlayer .java and declare method playVideo()

Step 2 :
Create a class VlcMediaPlayer.java which implements interface VideoPlayer.java and has its own implementation for method playVideo()

Step 3 :
Create a class WindowsMediaPlayer.java which implements interface VideoPlayer.java and has its own implementation for method playVideo()

Step 4 :
Create a class AdobeFlashPlayer.java which implements interface VideoPlayer.java and has its own implementation for method playVideo()

Step 5 :
Create an Interface AudioPlayer.java and declare method playSong()

Step 6 :
Create a class WinAmpPlayer .java which implements interface AudioPlayer.java and has its own implementation for method playSong()

Step 7 :
Create a class MP3Player.java which implements interface AudioPlayer.java and has its own implementation for method playSong()

Step 8 :
Create a class JetAudioHDPlayer.java which implements interface AudioPlayer.java and has its own implementation for method playSong()

Step 9:
Create an abstract class AbstractFactory.java which has two abstract methods getVideoPlayer() and getAudioPlayer() which returns VideoPlayer and AudioPlayer type instances respectively.

Step 10 :
Create a class VideoPlayerFactory .java which extends AbstractFactory class and returns corresponding VideoPlayer type instance based on user input.

Step 12 :
create a class AudioPlayerFactory.java which extends AbstractFactory class and returns corresponding AudioPlayer type instance based on user input.

Step 13 :
Create class SelectFactory.java which has public method getFactory() that returns corresponding VideoPlayerFactory or AudioPlayerFactory type instance based on user input.

Step 14 :
Create class AbstractFactoryDesignPatternDemo.java and select factory and then corresponding class object of that factory.

Output ::
Playing your favourite video using VLC MediaPlayer
Playing your favourite video using Windows MediaPlayer
Playing your favourite video using Adobe Flash Player

Playing your favourite song using WinAmp Player
Playing your favourite song using MP3 Player
Playing your favourite song using JetAudioHD Player

Observer Design Pattern

Observer Design Pattern :: Observer Design Pattern comes under behvioral design pattern.In this design pattern an observer is notified if any changes occur to an object which the observer is subscribed to.

Real Time Example :: Suppose there are serveral readers.One category of readers like to read Java Topics and other set of readers like to read Spring Topics .So these readers(Observers) first subscribes to corresponding SubjectTopic(Subjects).Once any changes to Subject, new articles added to topic and any subscriber is added/removed then if reader/subscriber opts for notification he/she can get the notification about the same.

 

UML Diagram ::

 

Step 1 :
Create an Interface Subject.java and declare methods subscribeObsever(Observer observer),unSubscribeObsever(Observer observer) and notifyAllObsevers() .
subscribeObsever() method adds an Observer/Subscriber.
unSubscribeObsever method removes an Observer/Subscriber.
notifyAllObsevers() method notify all Observers/Subscribers currently subscribed for the Subject.

Step 2 :
Create an Interface Observer.java and declare methods updateObserver() .
updateObserver() method updates an Observer/Subscriber if any changes happen to Subject.
I have also optionally added getName() method to get details about Observer/Subscriber.

Step 3 :
Create a class TopicEnrollment.java which implements interface Subject.java and has its own implementation for methods subscribeObsever(Observer observer),unSubscribeObsever(Observer observer) and notifyAllObsevers() .

Step 4 :
Create a class Subsrciber.java which implements interface Observer.java and has its own implementation for methods updateObserver()nd getName()
I also have an instance of Subject here ,so that a Subscriber can subscribe to corresponding Subject.I am doing the same in the constructor.

Step 5 :
Create main class ObserverDesignPatternDemo.java.I have created two topics “java-8” and “Spring-5” to demo Observer design pattern.

<


Output ::

Factory Design Pattern

Factory Design Pattern :: Factory Design Pattern comes under creation design pattern.As the name suggests,basically using these design pattern you can create an instance of class from a factory of related classes.

Real Time Example :: I am going to have a factory of MediaPlayer classes and each class has the functionality to play song.Based on user input ,user will select a particular type media player and will play song using that media player only.

 

UML Diagram ::

 

 

Step 1 :
Create an Interface MediaPlayer.java and declare method playSong()

Step 2 :
Create a class VlcMediaPlayer.java which implements interface MediaPlayer.java and has its own implementation for method playSong()

Step 3 :
Create a class WindowsMediaPlayer.java which implements interface MediaPlayer.java and has its own implementation for method playSong()

Step 4 :
Create a class AdobeFlashPlayer.java which implements interface MediaPlayer.java and has its own implementation for method playSong()

Step 5 :
Create a class MediaPlayerFactory.java and expose a public method which accepts an input and create instance of the corresponding class based on input.

Step 6 :
Create Main class FactoryDesignPatternDemo.java and create MediaPlayerFactory instance. Pass input tho the public method of MediaPlayerFactory class and get corresponding instance.


Output ::