How to Implement Double Checked Locking Singleton Pattern in Java? Example Tutorial

Double-checked locking pattern is one of the interesting topics in Java Interviews. Earlier, it was asked to see if a Java developer can write code using a synchronized block or not, and now it asks to gauge the candidate's understanding of concurrency, volatile, and synchronization in Java. One of the simplest ways to write thread-safe Singleton was to make the getInstance() method synchronized but prior to JDK 1.6, a simple uncontented synchronization block was expensive, and that lead many developers to write the getInstance() method of the Singleton class using double-checked locking idiom

Java Serialization Example and Tutorial for Beginners [Guide]

Serializing an object in Java is never easy and many Java developers often get confused. There are so many rules, interfaces to implement, and then always a chance of data loss or an error during the Serialization or deserialization process.  In the past, I have posted a detailed guide of Serliazing Object in Java which is very liked by my readers and they asked for more information like what should Java developers remember while using the Serializable and Externalizable interface in Java. 

7 Difference between extends Thread vs implements Runnable in Java [Answer]

Hello guys, the difference between Thread vs Runnable in Java is a common Java multithreading interview question that is often asked by junior Java developers with 2 to 4 years of experience. If you are doing Java programming then you may know that Java provides multithreading to parallelize the execution of tasks (code) and you need multiple threads to run multiple things in parallel like downloading a file in the background and showing the progress bar at the front-end. There are two ways to create a Thread in Java, first by extending java.lang.Thread class and second by implementing the java.lang.Runnable interface. 

Difference between View and Materialized View in Database or SQL? [Answer]

The difference between View and Materialized view is one of the popular SQL interview questions, much like truncate vs delete, correlated vs noncorrelated subquery, or primary key vs unique key. This is one of the classic questions which keeps appearing in SQL interviews now and then and you simply can’t afford to learn about them. Doesn’t matter if you are a programmer, developer, or DBA, these SQL questions are common to all. Views are a concept which not every programmer is familiar with, it is simply not in the category of CRUD operation or database transactions or SELECT query, its little advanced concept for the average programmer.

How to find symbolic link or soft link in Linux? ls + find command Example Tutorial

There are two ways you can find a symbolic link or soft link in UNIX based operating systems like Linux, Solaris, BSD, or IBM AIX. The first way is by using the ls command in UNIX which displays files, directories, and links in any directory and the other way is by using UNIX find command which has the ability to search any kind of file e.g. file, directory, or link. In this UNIX command tutorial, we will see examples of both of these UNIX commands for finding a soft link in any directory. If you are new to UNIX operating system and not familiar with the concept of the soft link and hard link, I would recommend getting a good hand on it, as it is one of the most powerful features of UNIX based system.

10 Examples of forEach() method in Java 8

From Java 8 onward, you can iterate over a List or any Collection without using any loop in Java. The new Stream class provides a forEach() method, which can be used to loop over all or selected elements of the list and map. The forEach() method provides several advantages over the traditional for loop e.g. you can execute it in parallel by just using a parallel Stream instead of a regular stream. Since you are operating on stream, it also allows you to filter and map elements. Once you are done with filtering and mapping, you can use forEach() to operate over them. You can even use the method reference and lambda expression inside the forEach() method, resulting in a more clear and concise code.

How to pause a Thread in Java? Thread.sleep and TimeUnit.sleep Example

There are multiple ways to pause or stop the execution of the currently running thread in Java, but putting the thread into a sleep state using the Thread.sleep() method is the right way to introduce a controlled pause. Some Java programmers would say, why not use the wait and notify? Using those methods just for pausing a thread is not a good coding practice in Java. Those are the tools for a conditional wait and they don't depend on time. A thread blocked using wait() will remain to wait until the condition on which it is waiting is changed. Yes, you can put timeout there but the purpose of the wait() method is different, they are designed for inter-thread communication in Java

10 Examples of ALTER Table Command in SQL

In this SQL tutorial, you will learn how to use ALTER command in the table on the database. ALTER command is mainly used to add, modify and drop columns, indexes, and constraints on the table in relational databases e.g. MySQL, Oracle, Sybase, and SQL Server.  Though ALTER is not part of classical CRUD operation but it’s one of the important DDL commands. One of the most frequent uses of ALTER command in SQL is adding and removing indexes to improve the performance of SQL SELECT queries.

5 Difference between Interface and Abstract class in Java? [Answer]

What is abstract class and interface in Java?
The difference between abstract class and interface in Java is one of the tricky Java interview questions and mostly appears in core Java interviews. It has become now even trickier after Java 8 introduced default methods and allowed interfaces to have both default and static methods. Even though both interface and abstract class are a way to achieve abstraction in Java, there are significant differences between them, which you will learn in this article. Some time interviewer also not just focuses on key differences between abstract class and interface in Java but he is also interested in some practical experience e.g. when to use interface in Java and when to use an abstract class in Java.

Top 100 Angular Interview Questions for 1 to 2 Years Experienced Developers

Angular is one of the popular JavaScript frameworks, I think most popular after jQuery, with the core goal of simplification. It allows building dynamic, single-page web apps (SPAs) using JavaScript and supports the Model View Controller (MVC) programming structure. It has been used widely and even big companies like Google, Virgin America, and HBO are using Angular to build their site. The demand for web developers is at an all-time high and there is a huge demand for developers who understand modern JavaScript frameworks like Angular, jQuery, Facebook's React JS, etc. Angular is an Open-source, front-end JavaScript framework which is developed by Google, it mainly competes with Facebook's ReactJS framework

OCMJEA 6 FAQs - Oracle Certified Master - Java EE 6 Enterprise Architect (1Z0-807, 1Z0-865 and 1Z0-866) - Frequently asked Questions

The OCMJEA (Oracle Certified Master Java EE Enterprise Architect) is one of the toughest Java certifications to crack, even for experienced Java developers. It requires architectural decision skills for the given business problem. Step 1 multiple-choice tests your skills by scenario-based business problems to choose the best design solution. The exam not only covers the Java EE platform but also tests your security, hardware architecture, and design pattern skills.

Java 8 Stream + FlatMap Example for Beginners | How to flat a list of list in Java?

In order to understand the flatMap() method, you first need to understand the map() function of Java 8. The map() function is declared in  the java.util.stream.Stream class and uses to transform one Stream into another, for example, it can convert a stream of integer numbers into another stream of ints where each element is the square of the corresponding element in the source stream. In the map() operation, a function is applied to each element of the source Stream and return values are inserted into a new Stream which is returned to the caller. The key point to note here is that the function used by the map() operation returns a single value.

How to get and set Value of a text field using jQuery? Example Tutorial

Hello guys, In the last jQuery tutorial, you learn how to dynamically add a text file into a form, and in this tutorial, I will show you how to get and set the value of the text field using jQuery. This is a common task and there is a good chance that you have already done something similar in your project. Our requirement is simple, the text field initially contains the value "username" and as soon as the user clicks on it to enter a username, it should become clear. After the user has entered the username of the user id, he can click on the submit button, and then your program should print the username and text field again becomes clear.

23 Design Patterns Java Developers Should know

Recently I come across a nice Java design pattern cheatsheet which






1. Abstract Factory Design Pattern
Abstract Factory is a creational Design Pattern, which is used to control the creation of Objects.

2. Adapter design pattern
The Adapter is a structural design pattern; it is used to maintain the structure of classes in object-oriented programs like Java applications.

The adapter pattern converts interface of a class into expected interface, allowing classes with incompatible interfaces to work together.
Adapters are useful for integrating existing components.

Java implementation creates a wrapper class, that is explicitly used in the code:
public interface Log {
    void warning(String message);
    void error(String message);
}
 
public final class Logger {
    void log(Level level, String message) { /* ... */ }
}
 
public class LoggerToLogAdapter implements Log {
    private final Logger logger;
 
    public LoggerToLogAdapter(Logger logger) { this.logger = logger; }
 
    public void warning(String message) {
        logger.log(WARNING, message);
    }
   
    public void error(String message) {
        logger.log(ERROR, message);
    }
}
 
Log log = new LoggerToLogAdapter(new Logger());
In Scala, we have a built-in concept of interface adapters, expressed as implicit classes:


3. Bridge Design Pattern
The bridge is also a structural design pattern

4. Builder Design Pattern
The Builder is another creational design pattern in Java.

5. Chain of Responsibility Pattern
Chain of Responsibility is a behavioral pattern from Gang of Four. It avoids coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. You actually have a chain of receiving objects, starting from lower level to higher level, request move along the chain until an object handles it.

6. Command Design Pattern
The Command Pattern is also a behavioral design pattern and uses to control the behavior of an object or set of objects in a program. The command object is used to encapsulate a request, thus allows you to parameterize clients with different requests, queue, or log requests, and also support undo sort of functionality. As the name suggests, it is used to execute commands e.g., buttons on the remote control.

7. Composite Design Pattern
Composite pattern is another structural design pattern

8. Decorator Design Pattern
Decorator is also a structural pattern

9. Facade Design Pattern
The Facade is another structure design pattern for Java developers.

10. Factory Method Design Pattern
Like Abstract Factory, this is also a creational design pattern, provides a better way to create an instance of objects in Java or any other object-oriented programming language.

The factory method pattern provides an interface for creating an object that encapsulates the actual class instantiation in a method, and lets subclasses decide which class to instantiate.
Factory method allows to:
merge complex object creation code,
select which class to instantiate,
cache objects,
coordinate access to shared resources.
We will consider the static factory method, which is slightly different from the classical version of the pattern “ static factory method avoids sub-classing, so there's no option to override the method.
In Java, we use a new operator to instantiate a class, by invoking its constructor. To implement the pattern, we rely on ordinary methods. Also, because we can̢۪t define static methods in interface, we have to use a separate factory class:
public interface Animal {}
 
private class Dog implements Animal {}
 
private class Cat implements Animal {}
 
public class AnimalFactory {
    public static Animal createAnimal(String kind) {
        if ("cat".equals(kind)) return new Cat();
        if ("dog".equals(kind)) return new Dog();
        throw new IllegalArgumentException();
    }
}
 
AnimalFactory.createAnimal("dog");

11. Flyweight Design Pattern
It's a structural pattern

12. Interpreter Design Pattern

13. Iterator Design Pattern

14. Mediator Design Pattern

15. Memento Design Pattern

16. Prototype Design Pattern

17. Proxy Design Pattern

18. Observer Design Pattern

19. Singleton Design Pattern

20. State Design Pattern

21. Strategy Design Pattern

The Strategy Pattern defines a group of polymorphic (interchangeable) and encapsulated Algorithms in a Context. If the algorithm changes then the client that uses it is not affected. Strategy Pattern can be thought as a very simple form of State Pattern where Algorithms does not access or alter the encapsulated Algorithm of the Context.
 
What Problem strategy pattern solves
 
 
When to use Strategy pattern
The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
 
It is also an alternative of passing behaviors to methods in Java in pre Java 8 world. Now you have a better option in terms of lambda expression for passing a function as parameter. Before that you can use Strategy pattern to pass behavior. It's the nearest substitue for a function of pointer in Java.
 
To add to the already magnificient answers: The strategy pattern has a strong similarity to passing a function (or functions) to another function. In the strategy this is done by wrapping said function in an object followed by passing the object. Some languages can pass functions directly, so they don't need the pattern at all. But other languages can't pass functions, but can pass objects; the pattern then applies.
 
When we have a set of similar algorithms and its need to switch between them in different parts of the application. With Strategy Pattern is possible to avoid ifs and ease maintenance;
When we want to add new methods to superclass that don̢۪t necessarily make sense to every subclass. Instead of using an interface in a traditional way, adding the new method, we use an instance variable that is a subclass of the new Functionality interface. This is known as Composition : Instead of inheriting an ability through inheritance the class is composed with Objects with the right ability;
 
1. Encoding
2. Decoding
3. Compression
4. Splitting
 
 
Advantages
 
 
Drawbacks
 
 
Problem
 Chess is a two-player strategy board game played on a chessboard, a checkered gameboard with 64 squares arranged in an eight-by-eight grid.
Each player begins the game with 16 pieces: one king, one queen, two rooks, two knights, two bishops, and eight pawns. Each of the six piece types moves differently.
Each chess piece has its own style of moving. In the diagrams
 
The king moves one square in any direction. The king has also a special move which is called castling and involves also moving a rook.
The rook can move any number of squares along any rank or file, but may not leap over other pieces. Along with the king, the rook is involved during the king's castling move.
The bishop can move any number of squares diagonally, but may not leap over other pieces.
The queen combines the power of the rook and bishop and can move any number of squares along rank, file, or diagonal, but it may not leap over other pieces.
The knight moves to any of the closest squares that are not on the same rank, file, or diagonal, thus the move forms an "L"-shape: two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The knight is the only piece that can leap over other pieces.
 
Chess is played on a square board of eight rows (called ranks and denoted with numbers 1 to 8) and eight columns (called files and denoted with letters a to h) of squares

 
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
/**
* Problem with switch statement and solution using strategy pattern.
*
* @author
*/
public class Testing {
 
    public static void main(String args[]) {
        ChessPiece night = new ChessPiece("Night", ChessPiece.PieceType.NIGHT);
        ChessPiece rook = new ChessPiece("Rook", ChessPiece.PieceType.ROOK);
        ChessPiece bishop = new ChessPiece("Bishop", ChessPiece.PieceType.BISHOP);
        ChessPiece pawn = new ChessPiece("Pawn", ChessPiece.PieceType.PAWN);
 
        List<ChessPiece> pieces = new ArrayList<>();
        pieces.add(night);
        pieces.add(rook);
        pieces.add(bishop);
        pieces.add(pawn);
 
        for (ChessPiece p : pieces) {
            p.movePiece();
        }
    }
 
}
 
class ChessPiece {
 
    private String name;
 
    public enum PieceType {
 
        PAWN, NIGHT, ROOK, BISHOP, QUEEN, KING;
    }
 
    private PieceType type;
 
    public ChessPiece(String name, PieceType type) {
        this.name = name;
        this.type = type;
    }
 
    public void movePiece() {
        System.out.print(name + ", ");
        switch (type) {
            case ROOK:
                System.out.println("Moving horizontally");
                break;
            case BISHOP:
                System.out.println("Moving diagonally");
                break;
            case NIGHT:
                System.out.println("Moving two and half square");
                break;
            case PAWN:
                System.out.println("Moving vertically");
                break;
        }
 
    }
 
    public String name() {
        return name;
    }
}
 
Output:
Night, Moving two and half square
Rook, Moving horizontally
Bishop, Moving diagonally
Pawn, Moving vertically
 
 
Example
 
 
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
/**
*
*
* @author
*/
public class Testing {
 
    public static void main(String args[]) {
        ChessPiece night = new ChessPiece("Night", new NightMove());
        ChessPiece rook = new ChessPiece("Rook", new RankMove());
        ChessPiece bishop = new ChessPiece("Bishop", new DiagonalMove());
        ChessPiece pawn = new ChessPiece("Pawn", new FileMove());
 
        List<ChessPiece> pieces = new ArrayList<>();
        pieces.add(night);
        pieces.add(rook);
        pieces.add(bishop);
        pieces.add(pawn);
 
        for (ChessPiece p : pieces) {
            p.movePiece();
        }
    }
 
}
 
interface MoveStrategy {
 
    public void move();
}
 
class DiagonalMove implements MoveStrategy {
 
    @Override
    public void move() {
        System.out.println("Moving diagonally");
    }
 
}
 
class FileMove implements MoveStrategy {
 
    @Override
    public void move() {
        System.out.println("Moving horinzontally");
    }
 
}
 
class RankMove implements MoveStrategy {
 
    @Override
    public void move() {
        System.out.println("Moving vertically");
    }
 
}
 
class NightMove implements MoveStrategy {
 
    @Override
    public void move() {
        System.out.println("Moving two and half squares");
    }
 
}
 
class ChessPiece {
 
    private String name;
    private MoveStrategy moveStrategy;
 
    public ChessPiece(String name, MoveStrategy strategy) {
        this.name = name;
        this.moveStrategy = strategy;
    }
 
    public void movePiece() {
        System.out.print(name + ", ");
        moveStrategy.move();
    }
 
    public String name() {
        return name;
    }
}
 
Output :
Night, Moving two and half squares
Rook, Moving vertically
Bishop, Moving diagonally
Pawn, Moving horinzontally
 
 
 
Examples from JDK
Collections.sort() and Comparable method.
 
Important points


22. Template Method Design Pattern

23. Visitor Design Pattern


And here is the big diagram which shows the relationship among different object-oriented design patterns:





That's all on this list of object-oriented design Patterns, Java developers should know. In fact, this list of patterns is equally useful for any object-oriented programmer working on object-oriented languages like C++, Scala, or any other language.

These are also known as Gang Of Four (GOF) design pattern because it was first published in the GOF design pattern book. Just keep one thing in mind, design patterns are tried and tested solutions to some particular problem, but it doesn't mean you always need them.

In fact, if you are familiar with these patterns and know their intent and when to use them, you will automatically alert by your mind about places where you can use these patterns.

I always keep these patterns back of my mind, and while coding, I somehow know that, Ok, this is the place where I should use this pattern. I never use them pre-planned; in fact, they came at random while doing coding, testing, refactoring, and code review.

3 ways to sort a List in Java 8 and 11 - Example Tutorial

There are multiple ways to sort a list in Java 8, for example, you can get a stream from the List and then use the sorted() method of Stream class to sort a list like ArrayList, LinkedList, or Vector and then convert back it to List. Alternatively, you can use the Collections.sort() method to sort the list. There is also a sort() method added to the List class itself. The Collections.sort() method is an older one and it's available from JDK 1.0 itself but List.sort() is a new method added in Java 8. This method accepts a Comparator if you want to sort a List in a custom order, otherwise, you can pass null if you want to sort a List on the natural order of their elements. 

How to use Spread operator and Rest parameter in JavaScript? Example Tutorial

Hello guys, if you are wondering what is Spread and Rest operator is in JavaScript are and how to use them in code then you have come to the right place. Earlier, I have shared some fundamental JavaScript concept tutorials like == vs === operator, hoisting, and destructuring, and in this JavaScirpt article, I am going to talk about Spread and Rest operators. JavaScript came out twenty-five years ago. Since then, it has changed a lot. First, it became the top programming language for client-side web development, and then with the emergence of Node.js, it also became the top player in server-side development. 

What is Variable and Function Hoisting in JavaScript? Example Tutorial

Hoisting is a complex concept in JavaScript. Like other major programming languages, variables and functions are an important part of JavaScript. Being a dynamically typed programming language, the variable declaration does not require specifying variable types. JavaScript also supports functions. But there is a catch. When variables and functions are declared in JavaScript, a process called hoisting takes place, and if you don't know this important concept you may struggle reading and understanding code but don't worry. In this article, I will teach you what is hoisting in JavaScript and give you real-world examples of the function and variable hoisting to start with.  

What is Destructuring in JavaScript? Example Tutorial

Arrays and objects play a very important role in programming. Every major programming language supports arrays and objects. Both arrays and objects are used to store data. The concept is simple but very powerful. JavaScript also supports arrays and objects. In fact, they are a very important part of modern JavaScript development. It does not matter if you are working on the frontend or backend, you are going to use arrays and objects. Over time, more and more features were added in JavaScript to make it easy to work with arrays and objects. 

Difference between first level and second level cache in Hibernate

The main difference between the first level and second level cache in Hibernate is that the first level is maintained at the Session level and accessible only to the Session, while the second level cache is maintained at the SessionFactory level and available to all Sessions. This means, you can use the first-level cache to store local data, i.e. the data which is needed by the Session, and you can use the second-level cache to store global data, i.e. something which can be shared across sessions. This is also one of the frequently asked Hibernate Interview questions and accessible in both telephonic rounds as well as on the face-to-face interviews, in both fresher and experienced level interviews.

Difference between IN, OUT, and INOUT parameters in JDBC Stored Procedure? Answer

Hello guys, Java Database Connectivity, the JDBC API supports three types of parameters, I mean, IN, OUT, and INOUT. They are used to bind values into SQL statements. An IN parameter is the one whose value is unknown when the SQL statement is created and you bind values using various setXXX() method depending upon the type of column those IN parameter refers in SQL query. For example in SQL query, SELECT * from EMPLOYEE where EMP_ID=? if the EMP_ID is a VARCHAR column then you must call the setString() method to pass the value to the IN parameter.