Thursday, September 30, 2021

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.

Wednesday, September 29, 2021

QuickSort Algorithm Example in Java using Recursion - Tutorial

The Quicksort algorithm is one of the very popular sorting algorithms in programming, often used to sort a large array of numbers. Though there is numerous algorithm available to sort a list of objects, including integer, string, and floating-point number, quicksort is best for general purpose. It's a divide and conquers algorithm, where we divide the given array with respect to a particular element, known as 'pivot' such that the lower partition of the array is less than the pivot and upper partition elements of the array are higher than the pivot.

How to remove a number from an Integer Array in Java? [Example Tutorial]

Hello guys, In the last article, you have learned how to reverse an array in place in Java, and today I have come back with another array-based coding interview question. It's also one of the frequently asked coding questions, not as popular as the previous one but still has been asked a lot of times on various Programming Job interviews, particularly to beginners. In this problem, you are asked to write a program to remove a given number from the given array. It may seem easy, but the trick is that because an array is a fixed data structure and you cannot change the length of the array once created. 

Friday, September 24, 2021

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. 

Thursday, September 23, 2021

5 Free SQL Books For Beginners and Experienced - Download PDF or Read Online

There is no doubt that SQL is one of the most essential skills for Programmers, IT professionals, Software Engineers, Quality Analysts, Project Manager, Data scientists, Database admins, and Business Analysts. I had even mentioned this as one of the top skills in my post about 10 things every programmer should know, if you haven't read that yet, you can read it here, it's completely worth your time. Since many Enterprise applications use the relational database at their backend, like Oracle, Microsoft SQL Server, MySQL, it's crucial to learn SQL to work with those applications and use the data stored on those databases.

How Binary Search Algorithm Works? Java Example without Recursion

The binary search algorithm is one of the fundamental Computer Science Algorithms and is used to search an element in a sorted input set. It's much faster than the linear search which scans each and every element and improves performance from O(n) to O(logN) for searching an element in the array. In order to perform the binary search, you need a sorted array, so you can either ask the user to enter the array in sorted order or you should sort the array before performing the binary search. It's also one of the popular algorithms for Programming Job interviews. The interviewer often asks candidates to implement binary search algorithms by hand in their favorite programming languages like Java, C++, Python. or JavaScript.

Wednesday, September 22, 2021

How to solve java.lang.NoClassDefFoundError: org/springframework/beans/factory/SmartInitializingSingleton in Spring Boot [Solved]

Problem:
I was trying to run a HelloWorld program using Spring Boot when I got this error:

Exception in thread "main" java.lang.IllegalStateException: Could not evaluate condition on org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer due to internal class not found. This can happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:52)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:92)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:174)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:136)

Tuesday, September 21, 2021

10 Examples to DateTimeFormatter in Java 8 to Parse, Format LocalDate and LocalTime

Parsing and formatting dates are other essential topics while working with date and time in Java. Even though the old Date API had the SimpleDateFormat and DateFormat class to support the formatting of date and parsing texts, they were not simple, or should I say there were just simple in writing the wrong code. You might know that SimpleDateFormat was not thread-safe and quite heavy to be used as a local variable. Thankfully, this has been sorted now with a new LocalDateTime class and DateTimeFormatter class, which has several inbuilt formats.

How to declare and Initialize two dimensional Array in Java with Example

An array of more than one dimension is known as a multi-dimensional array. Two of the most common examples of multi-dimensional arrays are two and three-dimensional arrays, known as 2D and 3D arrays, anything above is rare. I have never seen 4-dimensional arrays, even 3D arrays are not that common. Now the question comes when to use a multi-dimensional array? Any real-life example? Well, 2D arrays are very common on platform games like Super Mario Bros to represent screen or terrain; 2D arrays can also be used to represent structures like a spreadsheet, or to draw board games like Chess, which requires an 8x8 board, Checkers and  Tic-Tac-Toe, which requires 3 rows and 3 columns.

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. 

Monday, September 20, 2021

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.  

Sunday, September 19, 2021

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. 

Saturday, September 18, 2021

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. 

Thursday, September 16, 2021

How to create a custom tag in JSP? Steps and Example

You can create a custom tag in JSP either by implementing the SimpleTag interface or extending SimpleTagSupport class. Custom tags are introduced in JSP 2.0 in an effort to minimize Java code from JSP to keep them maintainable and allow page authors to work more in HTML or XML, like environment than writing Java codes. SimpleTag and SimpleTagSupport allow you to create a custom tag in JSP. It's easier to start with SimpleTagSupport class because it implements all methods of the SimpleTagSupport interface and if you are writing a basic tag then you just need to override the doTag() method of this class. 

How to manager HTTP Session in JSP Servlet?

Since HTTP is a stateless protocol its not possible to identify that two separate HTTP request is coming from same client and HTTP session management handle that issue for us. By maintaining a session for each client at the Server side, we can serve the client better, for example, you can store authentication and authorization information in session to prevent authenticating client for each HTTP request like in an online banking system, a session is created when a user is successful authenticated and session is maintained at server untile clients logout or session times out. If you have to write such online banking system using Java and Java EE technologies like Servlet and JSP then main question arises is how to do session management in JSP?


There are mainly three ways to manage session in JSP applications 1) using hidden html fields 2) using Cookie and 3) using URL rewriting. In Cookie small piece of information is stored in client machine but User can turn off this option and may be there is case of browser not supporting cookies, on all those cases URL rewriting is the best option to manage session in JSP Servlet application. JSTL core tag library provides tag which can encode URL for managing session.

Wednesday, September 15, 2021

How to use lifecycle methods in functional components in React.js? useEffect() hook Example Tutorial

Hello guys, if you have been following my blogs then you know that I have launched a new series - React for Java developers and this is the 4th article on the series. Earlier, we have seen state management in React, Redux, and useState hooks example, and in this article, you will learn about how to use lifecycle methods in functional React components. Lifecycle methods are powerful features provided by React.js in the class-based components. Each of the lifecycle methods executes at a particular time during the lifecycle of a component. 

Tuesday, September 14, 2021

How to compare two Arrays in Java to check if they are equal - [String & Integer Array Example]

Hello guys, one of the common Programming, the day-to-date task is to compare two arrays in Java and see if they are equal to each other or not. Of course, you can't compare a String array to an int array, which means two arrays are said to be equal if they are of the same type, has the same length, contains the same elements, and in the same order. Now, you can write your own method for checking array equality or take advantage of Java's rich Collection API. Similar to what you have seen while printing array values in Java, java.util.Arrays class provides convenient methods for comparing array values.

Monday, September 13, 2021

What is Redux Thunk in React.js? Example tutorial

Hello folks, This is the 3 part of my React for Java developer series and in the past two articles we have been focusing on statement management in React and we have seen that how to use manage state using Redux and useState hooks. And, in this article, we will learn about Redux Thunk, another useful concept when it comes to statement in React.js. State management is one of the most important concepts in react. If you are a react developer, then you must have used state in your project. There is no react project without a state. The state is defined as an instance of a component. It is an object that controls the behavior of a component. 

How to Convert or Print Array to String in Java? Example Tutorial

Array and String are very closely related, not just because String is a character array in most of the programming language but also with popularity - they are two of the most important data structure for programmers. Many times we need to convert an array to String or create an array from String, but unfortunately, there is no direct way of doing this in Java. Though you can convert an array to String by simply calling their toString() method, you will not get any meaningful value.  If you convert an Integer array to a String, you will get something like I@4fee225 due to the default implementation of the toString() method from the java.lang.Object class. Here, I show the type of the array and content after @ is hash code value in hexadecimal.

How to Format Date to String in Java 8 [Example Tutorial]

One of the common programming tasks in Java is to change the date format of a given Date or String. For example, you have something like "2017-01-18 20:10:00" and you want to convert it that date into "2017-01-18", or you want to convert from dd-MM-YY to MM-dd-YY or to any other format of your choice and need, but a valid date format as per Java specification. How will you do that? Well, it's not that difficult. It's just a two-step process. In the first step, you need to parse String to create an equivalent date using the current format, and then once you got the date, you need to again convert it back to String using the new format. The same process is repeated in both Java 8 and before, only corresponding API and class changes.

Sunday, September 12, 2021

How to use JSTL tag libray in JSP pages?

JSTL stands for JavaServer pages Standard tag library, which was created to help JSP developer with common tasks e.g. iterating over Collection in JSP, printing values, encoding URLs etc. In order to use JSTL tags in JSP page you need to do things, first you need to add standard.jar and jstl.jar in your Web application's classpath. This you can do by putting these two jar files into WEB-INF/lib directory. Once you do this you need to import the JSTL tag library in your JSP page to use JSTL tags like out, foreach, or forTokens etc. 

Saturday, September 11, 2021

What is Redux and how to use it? Example Tutorial

Managing state efficiently is very important in a react application. A React application depends on its state. React provides in-built support to manage the state but as the application grows, this in-built support becomes inefficient. So to manage the state of a large and complex react application, we have to use third-party state management libraries. Redux is by far the most popular state management library. It is heavily used with react and if you are planning to work in a real-time react project, you will encounter redux.

Friday, September 10, 2021

Can you Overload or Override main method in Java? Example

One of the common doubts among Java beginners while learning the overloading and overriding concept is, whether it's possible to overload the main in Java? Can you override the main method in Java? How will JVM find if you change the signature of the main method as part of the method overloading? etc. These are good questions and show the curiosity and application of knowledge of students, so if you are the tutor you must answer these questions. If you don't know the answer to this question, don't worry, just read this article till the end and you will find the answer yourself.  I have tried to explain in simple words but if you still can't get it, feel free to comment and I will try to help you personally. 

Monday, September 6, 2021

10 Advanced Programming and Development Books for Experienced Developers - Best of Lot

Hello guys, if you are looking for some advanced programming and development books to take your coding and software development skill to next level then you have come to the right place. Earlier, I have shared advanced courses in Java, Python, C++, and JavaScript and in this article, I am going to share some good books for the experienced programmer which can help them to become an expert. Learning never stops but once you become a professional programmer and spent a couple of years doing professional programming, you need to make some effort to reach the next level i.e. to become an expert programmer. Continuously doing the same stuff and not analyzing will not make you better. This is where these books can help you.

Sunday, September 5, 2021

4 Examples of Stream.collect() method in Java 8

Hello guys, you may know that Java 8 brought Stream API which supports a lot of functional programming operations like filtermapflatMap, reduce, and collect. In this article, you will learn about the collect() method. The collect() method of Stream class can be used to accumulate elements of any Stream into a Collection. In Java 8, you will often write code that converts a Collection like a List or Set to Stream and then applies some logic using functional programming methods like the filter, map, flatMap and then converts the result back to the Collection like a ListSetMap, or ConcurrentMap in Java.

Difference between List and ArrayList Reference Variables in Java? Example Tutorial

Someone who is just starting with Java programming language often has doubts about how we are storing an ArrayList object in List variable, what is the difference between List and ArrayList? Or why not just save the ArrayList object in the ArrayList variable just like we do for String, int, and other data types. Well, the main difference between List and ArrayList is that List is an interface while ArrayList is a class. Most importantly, it implements the List interface, which also means that ArrayList is a subtype of the List interface. In Java or any object-oriented language, the supertype of a variable can store an object of subtype.

How to Increasing Heap Size of Java application in JVM? Example Tutorial

Hello guys, if you are wondering how to change the heap size of the heap space of your Java application then you have come to the right place. In this article, I am going to tell you how to increase Java heap space so that your JVM will not crash using OutOfmemoryError. We have already seen how to increase heap memory in Maven and ANT and now we will learn how to increase heap size in Java, Eclipse, Tomcat, and WebSphere Server in a series of articles. Since all these are Java applications, once you know how to change heap space in Java, you can do that in any Java application, provided you know the right place, which is what we will see in this article.

Saturday, September 4, 2021

How to access JSTL variable in Scriptlet?

You can access the JSTL variable inside the scriptlet by calling the getAttribute() method on pageContext, request, response, or session objects, depending upon which scope your JSTL variable was created. For example, if your JSTL variable is created on request scope, you can call request.getAttribute("count") to get value of a variable named count. A JSTL variable is a variable that is created using a set tag and belongs to a particular scope, by default they are created in page scope. 

Friday, September 3, 2021

The Ultimate Guide of Remote Debugging in Java using Eclipse IDE? Example Tutorial

The remote debugging of the Java program is an ultimate tool in the arsenal of a Java developer, which is often becoming the last and only tool to investigate a bug on a Java application running on the remote host like on a Linux server or Windows server. Almost all major Java IDE provides remote debugging like NetBeans, Eclipse, and IntelliJ IDEA, but I mostly use Eclipse for Java coding and so it's my preferred tool to remote debug a Java program. In order to set up remote debugging in Eclipse, you need to do a couple of tasks like you need to start your JVM with debugging parameters or arguments and then you need to create a "remote debug configuration" in Eclipse IDE itself.

How to Convert java.util.Date to LocalDate in Java 8 - Example Tutorial

Hello guys, once you move to Java 8, you will often find yourself working between old and new Date and Time API, as not all the libraries and systems you interact with will be using Java 8. One of the common tasks which arise from this situation is converting old Date to new LocalDate and that's what you will learn in this tutorial. There seems to be a couple of ways to convert a java.util.Date to java.time.LocalDate in Java 8, but which one is the best way? We'll figure it out in this article, but first, let's explore these different ways to convert a java.util.Date object to LocalDate in Java 8 code.

Thursday, September 2, 2021

How to parse String to LocalDate in Java 8 - DateTimeFormatter Example

From Java 8 onward, you are no longer dependent on the buggy and bulky SimpleDateFormat class to parse and format date Strings into real Date objects in Java e.g. java.util.Date. You can use the DateTimeFormatter class from java.time package for all your formatting and parsing need. You are also no longer required to use another buggy class java.util.Date if you are doing fresh development, but if you have to support legacy code then you can also easily convert LocalDate and LocalTime to java.util.Date or java.sql.Date. In this tutorial, we will learn about both parsing String to date in Java and formatting Date into String.