Function and BiFunction are the functional interfaces introduced from java 8. Simples examples are as below.
Thursday, 22 April 2021
Wednesday, 21 April 2021
Java: forEachRemaining() method
The forEachRemaining() method is introduced in java 8 itself. This method makes iteration on iterator very easy. Basically, this method uses a lambda expression and reduces a lot of unnecessary code. Check below example,
Java: join() method
The join() is used to hold the execution of the main thread for the time our thread on which we are calling join() method is completed. A simple example of this join() method is as below,
Java: clone() method
The clone() method is used to create a copy of any class which implements the Clonable interface. If the class does not implement the Clonable interface and you still call clonable on that then it will throw ClassNotSupportedException. When we call this clone method then the copy of primitive types will be created but object references will be copied as they are. So basically original and cloned object will have the same object references. So modification in the cloned object will be reflected in the original object.
Shallow copy example,
Tuesday, 20 April 2021
Java: yield() method
The yeild() method gives chance to other high-priority threads to execute. This is one of the static native method from the Thread class.
When we call Thread.yield() in any of the running thread then the currently running thread will move to the ready state and other thread with higher priority will get a chance to execute. If another waiting thread doesn't have a higher priority than the current thread then, in that case, the current thread will continue its execution.
The Explanation from Thread class is,
Example of yield method,
Friday, 28 June 2019
Java 8: Stream skip() and limit() method
For the examples below, we can consider data as,
List<String> listOfString = Arrays.asList("A", "B", "C", "D", "E", "F");
1. skip()
List<String> skippedList = listOfString.stream().skip(2).collect(Collectors.toList());
System.out.println("Skipped list: " + skippedList);
2. limit()
List<String> skippedAndLimitedList = listOfString.stream().skip(1).limit(2).collect(Collectors.toList());
System.out.println("Skipped and limi list: " + skippedAndLimitedList);
We can use these methods for implementing pagination on bigger collections.
private static List<String> getPage(final int page, final int size, final List<String> listOfString) {
return listOfString.stream().skip((page - 1) * size).limit(size).collect(Collectors.toList());
}
System.out.println("Page 1 of size 2: " + getPage(1, 2, listOfString));
Output:
Page 1 of size 2: [A, B]
System.out.println("Page 2 of size 2: " + getPage(2, 2, listOfString));
Output:
Page 2 of size 2: [C, D]
System.out.println("Page 1 of size 100: " + getPage(1, 100, listOfString));
Output:
Page 1 of size 100: [A, B, C, D, E, F]
Wednesday, 12 September 2018
Tuesday, 11 September 2018
Java 8: Using optional with nested objects
Consider below the class structure,
Now consider that, you want to extract an email from the Employee object, also you have to avoid null pointer exception. In a traditional way, you have to write a lot of NULL conditions.
Check below code with an Optional class which simplifies your code structure.
I will write a few more posts for using an Optional with collection classes.
Thursday, 26 January 2017
Decimal to binary conversion
Here is simple way to do this.
Suppose you have to convert 35 to binary number then you simple start dividing this with 2.
2/35 - 1(remaining value)
2/17 - 1
2/8 - 0
2/4 - 0
2/2 - 0
2/1 - 1
Now simply collect remaining values in reverse order.
100011 and this is binary number for 35.
to verify you can check like,
(2^5 * 1) + (2^4 *0) + (2^3*0) + (2^2*0) + (2^1*1) + (2^0*1)
↧ ↧ ↧ ↧ ↧ ↧
= 32 + 0 + 0 + 0 + 2 + 1
= 35
And you are done..
Wednesday, 2 October 2013
Tricky Examples 1
public class Test
{
public static void main(String[] args)
{
boolean a = true;
float b = 0.0f;
double c = 0.0;
int d = 0;
if(a = false)
{
System.out.print("\nThis is will not executed");
}//if
else
{
System.out.print("\nThis is false : " + (a = false));
}//else
if(a = true)
{
System.out.print("\nThis is will executed now because (a = true) = " + (a = true));
}//if
else
{
System.out.print("\nThis is will not executed");
}//else
/* In java if(condition) statement will always need boolean value
* so following all code will fail to compile
* if(b = 2.3)
* if(c = 4.3)
* if(d = 3)
* Lets see what will be return value for these
*/
System.out.print("\n(b = 2.3) = " + (b = 2.3f));
System.out.print("\n(c = 4.3) = " + (c = 4.3));
System.out.print("\n(d = 3) = " + (d = 3));
}//PSVM
}//class Test
2. For down cast you will need explicit casting.
public class Test
{
public static void main(String [] args)
{
byte b = 10;
short s = 20;
int i = 30;
float f = 40f;
double d = 50;
// Here are few valid assignments
d = f;
f = i;
i = s;
s = b;
//Here are few invalid assignments
b = s;
s = i;
i = f;
f = d;
//To make this working you have to cast explicitly
b = (byte)s;
s = (short)i;
i = (int)f;
f = (float)d;
}//PSVM
}//class Test
3. Only byte, short, int, char, String and enum is allowed in switch case. Here I am giving example.
public class Test
{
public static void main(String args[])
{
String f ="0";
switch (f)
{
}
int f1 = 0;
switch (f1/2)
{
}
byte f2 = 0;
switch (f2 + 3)
{
}
short f3 = 0;
switch (f3)
{
}
char f4 = '0';
switch (f4)
{
}
/*
It will fail for float, double, long
float f4 = 2.3f;
switch(f4)
{
}
*/
}
}
Sunday, 29 September 2013
Printing triangle pattern in java
import java.io.InputStreamReader;
public class Main
{
public static void main(String args[])
{
int n = 0;
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter the number of rows : ");
n = Integer.parseInt(br.readLine());
for(int i = 0; i < n; i++)
{
for(int j= 0; j < (n-i); j++)
{
System.out.print(" ");
}//for j
for(int j = 0; j <= i; j++)
{
System.out.print("* ");
}//for j
System.out.print("\n");
}//for i
for(int i = 0; i < n; i++)
{
for(int j = 0; j <= i; j++)
{
System.out.print(" ");
}//for j
for(int j= 0; j < (n-i); j++)
{
System.out.print("* ");
}//for j
System.out.print("\n");
}//for i
}//try
catch(Exception e)
{
System.out.print("\nException : " + e);
}//catch
}//PSVM
}//class Main
Printing diamond pattern in java
import java.io.InputStreamReader;
public class Main
{
public static void main(String args[])
{
int n = 0;
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter the number of rows : ");
n = Integer.parseInt(br.readLine());
for(int i = 0; i < n; i++)
{
for(int j= 0; j < (n-i); j++)
{
System.out.print(" ");
}
for(int j = 0; j <= i; j++)
{
System.out.print("* ");
}
System.out.print("\n");
}//for i
for(int i = 0; i < n; i++)
{
for(int j = 0; j <= i; j++)
{
System.out.print(" ");
}
for(int j= 0; j < (n-i); j++)
{
System.out.print("* ");
}
System.out.print("\n");
}//for i
}
catch(Exception e)
{
}
}
}
Output :-
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*
Monday, 15 July 2013
Windows 7 Shortcuts
1. You pin your favorite application to your task-bar say edit-plus (Assume that this is your first application task-bar). Now you can access that application with keyboard shortcut Win + 1. In this way you can access 10 applications with Win + 2, Win + 3,....,Win + 10.
2. You have any one window open now if you want to adjust that window to half left of your computer screen then you can use Win + Left or Right Arrow. If you want to adjust this windows to right half of your screen, you can keep pressing Win + Left or Right Arrow.
3. If you want to restore down your active window then press Win + Down Arrow. If you want to maximize your active window then press Win + Up Arrow key.
4. If you want to browse through your folder hierarchy then use Alt + Arrow keys. This will work with your windows explorer. Here you can use Up, Left or Right arrow keys
5. Win + Alt + N will allow you to access jump list of Nth pinned application on your task-bar. Here N = 1, 2, ...,9 means number keys.
6. You can create shortcut for your favorite application for launching that application. Right click on your favorite application icon => Go to properties => shortcuts. Now click on shortcut field and press shortcut that you want. Ex. Alt + A.
7. Very useful is opening command prompt for particular folder. If you are in some folder say C:\a\b\c\d and now you want to open command prompt at this folder then press "Shift key + Right click" in your folder and you will get "open command window here" option. You click this option and you will get command prompt for that folder.
8. You know that after pressing Shift key five times opens Sticky key dialog box. If you want to avoid that follow the link in the same dialog box and here you can disable this feature.
Tuesday, 21 May 2013
Flyweight Pattern Example - JAVA
Flyweight pattern is mainly used to reuse objects. This one of the structural pattern. We can understand this pattern by following example. Here we are using bikes with different type, color and cc.
1. Create interface as given below.
public interface Bike {
Bike getBike(String type);
void setColor(String color);
void setCc(int cc);
String getDetails();
}//Bike
2. Create class HondaBike as given below.
public class HondaBike implements Bike {
private int cc;
private String color, type;
public HondaBike(String type) {
this.type = type;
}//HondaBike
public Bike getBike(String type) {
return new HondaBike(type);
}//getBike
public void setColor(String color) {
this.color = color;
}//setColor
public void setCc(int cc) {
this.cc = cc;
}//setCc
public String getDetails() {
return "\nColor : " + color + "\tCC : " + cc + "\tType : " + type;
}//getDetails
}//class HondaBike
3. Create BikeGenerator as given below.
import java.util.HashMap;
public class BikeGenerator {
private HashMap<String, Bike> bikeStore = new HashMap<>();
public Bike getBike(String type) {
Bike bike = (Bike) bikeStore.get(type);
if(bike == null) {
bikeStore.put(type, new HondaBike(type));
System.out.print("\nGenerating new bike object with type : " + type);
}//if
else {
System.out.print("\nReturning existing object.");
}//else
return (Bike)bikeStore.get(type);
}//getBike
}//BikeGenerator
4. Now we can create our main class as given below.
public class Main {
public static void main(String args[]) {
BikeGenerator bg = new BikeGenerator();
Bike hondaSimple = bg.getBike("simple");
hondaSimple.setColor("Red");
hondaSimple.setCc(100);
System.out.print("\n" + hondaSimple.getDetails());
Bike hondaDelux = bg.getBike("delux");
hondaDelux.setColor("Red");
hondaDelux.setCc(150);
System.out.print("\n" + hondaDelux.getDetails());
Bike hondaGold = bg.getBike("gold");
hondaGold.setColor("Red");
hondaGold.setCc(350);
System.out.print("\n" + hondaGold.getDetails());
Bike hondaAgainSimple = bg.getBike("simple");
hondaAgainSimple.setColor("Black");
hondaAgainSimple.setCc(350);
System.out.print("\n" + hondaAgainSimple.getDetails());
}//PSVM
}//Main
And now you are ready to run example. Output will explain you waht we have achieved.
Monday, 20 May 2013
Facade Pattern Example
Facade pattern is one of the structural pattern which is used to hide internal complexity. Here I am giving one example of color filling. You can use following steps to get working example of facede pattern.
1. First create Color interface.
public interface Color {
void fillColor();
}//Color
2. Now create class Redcolor
public class RedColor implements Color {
public void fillColor() {
System.out.print("\nFilling red color");
}//fillColor
}//RedColor
3.Now create class BlueColor
public class BlueColor implements Color {
public void fillColor() {
System.out.print("\nFilling blue color");
}//fillColor
}//BlueColor
4. Now create class GreenColor
public class GreenColor implements Color {
public void fillColor() {
System.out.print("\nFilling green color");
}//fillColor
}//GreenColor
5. Here we go for creating ColorFiller class which is going to hide complexity.
public class ColorFiller {
private Color redColor;
private Color blueColor;
private Color greenColor;
public ColorFiller() {
redColor = new RedColor();
blueColor = new BlueColor();
greenColor = new GreenColor();
}//ColorFiller
public void fillRedColor() {
redColor.fillColor();
}//fillRedColor
public void fillBlueColor() {
blueColor.fillColor();
}//fillBlueColor
public void fillGreenColor() {
greenColor.fillColor();
}//fillGreenColor
}//CollerFiller
6. Here Main class where we have to use this pattern.
public class Main {
public static void main(String args[]) {
ColorFiller cf = new ColorFiller();
cf.fillRedColor();
cf.fillBlueColor();
cf.fillGreenColor();
}//PSVM
}//Main
Sunday, 19 May 2013
Composit Pattern Example
1. Create StaffMember class as given below. Here remember that composit pattern class will always have list of objects of its own type.
import java.util.ArrayList;
import java.util.List;
public class StaffMember {
private int ID;
private String name, desg;
public List<StaffMember> subMember;
public StaffMember(int ID, String name, String desg) {
this.ID = ID;
this.name = name;
this.desg = desg;
subMember = new ArrayList<StaffMember>();
}//StaffMember
public void addSubMember(StaffMember staffMember) {
subMember.add(staffMember);
}//addSubMember
public List<StaffMember> getSubMember(StaffMember staffMember) {
return subMember;
}//getSubMember
public String toString() {
return "\nID : " + ID + "\tName : " + name + "\tDesg : " + desg;
}//toString
}//class StaffMember
2. Now create Main class for demo as given below.
import java.util.List;
public class Main {
public static void main(String args[]) {
StaffMember headMaster = new StaffMember(1, "A", "HeadMaster");
StaffMember subHeadMaster = new StaffMember(2, "B", "Sub-HeadMaster");
StaffMember supervisor1 = new StaffMember(3, "C", "Supervisor-1");
StaffMember supervisor2 = new StaffMember(4, "D", "Supervisor-2");
StaffMember teacher1 = new StaffMember(5, "E", "Teacher-1");
StaffMember teacher2 = new StaffMember(6, "F", "Teacher-2");
StaffMember teacher3 = new StaffMember(7, "G", "Teacher-3");
StaffMember teacher4 = new StaffMember(8, "H", "Teacher-4");
headMaster.addSubMember(subHeadMaster);
subHeadMaster.addSubMember(supervisor1);
subHeadMaster.addSubMember(supervisor2);
supervisor1.addSubMember(teacher1);
supervisor1.addSubMember(teacher2);
supervisor2.addSubMember(teacher3);
supervisor2.addSubMember(teacher4);
System.out.print("\nHead master hierarchy : ");
printHierarchy(headMaster);
System.out.print("\n=========================================");
System.out.print("\nSub head master hierarchy : ");
printHierarchy(subHeadMaster);
System.out.print("\n=========================================");
System.out.print("\nSupervisor 1 hierarchy : ");
printHierarchy(supervisor1);
System.out.print("\n=========================================");
System.out.print("\nSupervisor 2 hierarchy : ");
printHierarchy(supervisor2);
}//PSVM
public static void printHierarchy(StaffMember staffMember) {
System.out.print(staffMember.toString());
List<StaffMember> member = staffMember.getSubMember(staffMember);
for(int i = 0; i < member.size(); i++) {
printHierarchy(member.get(i));
}//for i
}//printHierarchy
}//class Main
Now you modify StaffMember class for additional information like you can store parent of that object. You can put some checks when adding member. You can add method for removing member from hierarchy.
Friday, 17 May 2013
Filter Pattern Example - JAVA
Filter pattern is mainly used to filter group of objects based on some criteria We can see one simple example of this filter pattern. Here we are going to filter laptops based on company and OS. Use following steps to build example.
1. Create class Laptops as given below.
public class Laptops {
String company, os;
int bits;
public Laptops(String company, String os, int bits) {
this.company = company;
this.os = os;
this.bits = bits;
}//Laptops
public String getCompany() { return company; }
public String getOs() { return os; }
public int getBits() { return bits; }
}//class Laptops
2. Create interface Filter as given below.
import java.util.List;
public interface Filter {
List<Laptops> filterObjects(List<Laptops> laptops);
}
3. Create class HclFilter as given below.
import java.util.ArrayList;
import java.util.List;
public class HclFilter implements Filter {
public List<Laptops> filterObjects(List<Laptops> laptops) {
List<Laptops> hclLaptops = new ArrayList<>();
for(int i = 0; i < laptops.size(); i++)
if(laptops.get(i).getCompany().equalsIgnoreCase("hcl"))
hclLaptops.add(laptops.get(i));
return hclLaptops;
}//filterObjects
}//HclFilter
4. Create class WindowsOsFilter as given below.
import java.util.ArrayList;
import java.util.List;
public class WindowsOsFilter implements Filter {
public List<Laptops> filterObjects(List<Laptops> laptops) {
List<Laptops> windowsOsLaptops = new ArrayList<>();
for(int i = 0; i < laptops.size(); i++)
if(laptops.get(i).getOs().equalsIgnoreCase("windows"))
windowsOsLaptops.add(laptops.get(i));
return windowsOsLaptops;
}//filterObjects
}//WindowsOsFilter
5. And now our demo class for filter pattern.
import java.util.ArrayList;
import java.util.List;
public class FilterDemo {
public static void main(String args[]) {
List<Laptops> allLaptops = new ArrayList<Laptops>();
allLaptops.add(new Laptops("hcl", "windows", 32)); allLaptops.add(new Laptops("hcl", "linux", 32));
allLaptops.add(new Laptops("hcl", "solaries", 64)); allLaptops.add(new Laptops("dell", "windows", 32));
allLaptops.add(new Laptops("dell", "linux", 32)); allLaptops.add(new Laptops("dell", "solaries", 64));
Filter hclLaptops = new HclFilter();
Filter windowsOsLaptops = new WindowsOsFilter();
List<Laptops> filteredLaptops = hclLaptops.filterObjects(allLaptops);
System.out.print("\nAll HCL laptops : ");
for(int i = 0; i < filteredLaptops.size(); i++)
System.out.print("\nCompany : " + filteredLaptops.get(i).getCompany() + "\tOs : " + filteredLaptops.get(i).getOs());
filteredLaptops = null;
filteredLaptops = windowsOsLaptops.filterObjects(allLaptops);
System.out.print("\nAll windows os laptops : ");
for(int i = 0; i < filteredLaptops.size(); i++)
System.out.print("\nCompany : " + filteredLaptops.get(i).getCompany() + "\tOs : " + filteredLaptops.get(i).getOs());
}//PSVM
}//class FilterDemo
You can add more filters and can add "AND" & "OR" filters as well.
Thursday, 16 May 2013
Adapter pattern example
Adapter pattern is one of the structural pattern which makes two incompatible interfaces to work together. Idea can be more clear with example. For implementing adapter pattern you can follow given steps.
Here example is of ColorProvider class. This ColorProvider class implements interface called BasicColors which can provide only red, green and blue colours. There is another interface called AdvancedColors whic provides yellow, pink, white and black colors. In this case adapter pattern will make BasicColors and AdvancedColors to work together without any changes in interface of ColorProvider class.
1. Create interface BasicColors as given below.
public interface BasicColors {
void getColor(String color);
}
2. Create interface AdvancedColors as given below.
public interface AdvancedColors {
void getColor();
}
3. Now we can create class ColorProvider which will be used by user.
public class ColorProvider implements BasicColors {
ColorAdapter colorAdapter;
public void getColor(String color) {
if(color.equalsIgnoreCase("red") || color.equalsIgnoreCase("green") || color.equalsIgnoreCase("blue")) {
System.out.print("\nBasic colour " + color + " by BasicColor interface.");
}//if
else {
colorAdapter = new ColorAdapter();
colorAdapter.getColor(color);
}//else
}//getColor
}//class ColorProvider
4. Here we go for ColorAdapter as given below.
public class ColorAdapter implements BasicColors {
AdvancedColors advColor;
public void getColor(String color) {
if(color.equalsIgnoreCase("yellow")) {
advColor = new Yellow();
advColor.getColor();
}//if
else if(color.equalsIgnoreCase("pink")) {
advColor = new Pink();
advColor.getColor();
}//else if
else if(color.equalsIgnoreCase("black")) {
advColor = new Black();
advColor.getColor();
}//else if
else if(color.equalsIgnoreCase("white")) {
advColor = new White();
advColor.getColor();
}//else if
}//getColor
}//class ColorAdapter
5. Now we can implement concreet classes of advanced colors as given below.
public class Yellow implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced yellow color.");
}
}
public class Pink implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced pink color.");
}
}
public class Black implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced black color.");
}
}
public class White implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced white color.");
}
}
6. Here we go for demo i.e. for Main class.
public class Main {
public static void main(String args[]) {
ColorProvider cp = new ColorProvider();
cp.getColor("red");
cp.getColor("yellow");
cp.getColor("green");
cp.getColor("pink");
}
}
You can draw UML diagram for better understanding.
Tuesday, 14 May 2013
Factory Design Pattern Example
Factory pattern is creational pattern which hides object creation logic from user. We can see one example of factory patter for clear understanding. To execute your factory pattern use following steps:-
1. Create interface called Car as given below. It will be common reference to all Car objects that we are going to create.
public interface Car {
void myCar();
}
2. Now create one concreet class called Bmw. This class will be implementing interface Car.
public class Bmw implements Car {
public void myCar() {
System.out.print("\nBmw is my car.");
}
}
3. Now create another concreet class called Tata. This class will be implementing interface Car.
public class Tata implements Car {
public void myCar() {
System.out.print("\nTata is my car.");
}
}
4. Now create one more class called Maruti. Thisclass will be implementing interface Car.
public class Maruti implements Car {
public void myCar() {
System.out.print("\nMaruti is my car.");
}
}
5. Now you have to create one more class called CarFactory as given below.
public class CarFactory {
public Car getCar(String carName) {
if(carName.equalsIgnoreCase("Tata"))
return new Tata();
else if(carName.equalsIgnoreCase("Maruti"))
return new Maruti();
else if(carName.equalsIgnoreCase("Bmw"))
return new Bmw();
return null;
}
}
6. Now our pattern is ready. Let's write one class to implement this pattern.
public class CarShop {
public static void main(String args[]) {
CarFactory cf = new CarFactory();
Car c1 = cf.getCar("Tata");
c1.myCar();
c1 = cf.getCar("Maruti");
c1.myCar();
}
}
Here you are ready to execute your application.
Now you can see that if you want to add one more car to shop you just need to add one more class implementing Car interface and you are done. In this was this pattern provides flexibility and hides creational logic from user.
-
Semaphore provides simple and effective way of controlling multiple threads trying to access same resource. This concepts was invented by d...
-
Repository architectural style is data centered style, which allows user interaction for data processing. This style shows two main entitie...
-
Exception handling mechanism in java shows one major base class called Throwable. This Throwable class shows two major branches called Exc...


