Posts

Showing posts with the label Java Tutorial

Understanding Composite Design Pattern in Java

Image
The Composite Design Pattern is one of the most powerful structural design patterns in Java . It is widely used when you want to represent hierarchical structures such as trees — for example, a folder structure, UI components, organization charts, menus in web apps, and more. In this blog, we will understand what the Composite Pattern is, when to use it, its advantages, and a real-time Java example. If you are preparing for Java interviews, system design, or scalable application development , this article will help you. What is the Composite Design Pattern in Java? The Composite Pattern allows you to treat individual objects and a group of objects in the same way . It is mainly used to implement tree-like structures . Every node in the tree can be either: Leaf – an individual object Composite – a container that holds leaf or other composite objects The main objective is to let the client treat both leaf and composite objects uniformly . Real-Time Use Cases Fil...

Serialization in Java

Image
Serialization in Java is a mechanism of converting the state of an object into a byte stream . This byte stream can be persisted into a file, transferred over a network, or stored in a database. The reverse process of recreating an object from the byte stream is known as Deserialization . ✨ Why Serialization? To save the state of an object for later use (Persistence). To send objects between JVMs (Distributed applications, RMI, Messaging). To cache data temporarily. To store objects in databases or files. ⚙️ How Serialization Works Serialization is implemented using the java.io.Serializable interface. This is a marker interface (does not contain methods) that signals the JVM that the class can be serialized. Basic Example: import java.io.*; class Student implements Serializable { int id; String name; Student(int id, String name) { this.id = id; this.name = name; } ...

Java Streams Terminal Operations Explained with Examples

Image
In our previous post, we explored intermediate operations in Java Streams. Now, let’s move to terminal operations . These are the final operations that produce a result (like a value, collection, or side-effect) and terminate the stream pipeline. 1. forEach() The forEach() method is used to perform an action for each element of the stream. List<String> words = Arrays.asList("apple", "banana", "cherry"); words.forEach(word -> System.out.println("item is " + word)); 2. collect() The collect() method gathers the elements of a stream into a collection (like a List, Set, or Map). List<Integer> nums = Arrays.asList(1,1,2,2,2,3,4,5,5,5,6); Set<Integer> res = nums.stream().collect(Collectors.toSet()); System.out.println(res); 3. reduce() The reduce() method performs a reduction on the elements of the stream using an accumulation function. List<Integer> nums = Arrays.asList(1,2,3,4,5); Optional<Integer...