In Java, Map Interface is present in the java.util package represents a mapping between a key and a value. Java Map interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the rest of the collection types.
- No Duplicates in Keys: Ensures that keys are unique. However, values can be duplicated.
- Null Handling: Allows one
null key in implementations like HashMap and LinkedHashMap and allows multiple null values in most implementations. - Thread-Safe Alternatives: Use
ConcurrentHashMap for thread-safe operations also, wrap an existing Map using Collections.synchronizedMap() for synchronized access.
The Map data structure in Java is implemented by two interfaces, the Map Interface and the SortedMap Interface. Three primary classes implement these interfaces HashMap, TreeMap, and LinkedHashMap.
Example:
Java
// Java Program Implementing HashMap
import java.util.HashMap;
import java.util.Map;
public class MapCreationExample {
public static void main(String[] args)
{
// Create a Map using HashMap
Map<String, Integer> map = new HashMap<>();
// Displaying the Map
System.out.println("Map elements: " + map);
}
}
Geeks, the brainstormer should have been why and when to use Maps.
Maps are perfect to use for key-value association mapping such as dictionaries. The maps are used to perform lookups by keys or when someone wants to retrieve and update elements by keys. Some common scenarios are as follows:
- A map of error codes and their descriptions.
- A map of zip codes and cities.
- A map of managers and employees. Each manager (key) is associated with a list of employees (value) he manages.
- A map of classes and students. Each class (key) is associated with a list of students (value).

Creating Map Objects
Since Map is an interface, objects cannot be created of the type map. We always need a class that extends this map in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Map.
Syntax: Defining Type-safe Map
Map hm = new HashMap(); // Obj is the type of the object to be stored in Map
Characteristics of a Map Interface
- A Map cannot contain duplicate keys and each key can map to at most one value. Some implementations allow null key and null values like the HashMap and LinkedHashMap, but some do not like the TreeMap.
- The order of a map depends on the specific implementations. For example, TreeMap and LinkedHashMap have predictable orders, while HashMap does not.
- There are two interfaces for implementing Map in Java. They are Map and SortedMap, and three classes: HashMap, TreeMap, and LinkedHashMap.
Methods in Java Map Interface
| Method | Action Performed |
|---|
| clear() | This method is used in Java Map Interface to clear and remove all of the elements or mappings from a specified Map collection. |
| containsKey(Object) | This method is used in Map Interface in Java to check whether a particular key is being mapped into the Map or not. It takes the key element as a parameter and returns True if that element is mapped in the map. |
| containsValue(Object) | This method is used in Map Interface to check whether a particular value is being mapped by a single or more than one key in the Map. It takes the value as a parameter and returns True if that value is mapped by any of the keys in the map. |
| entrySet() | This method is used in Map Interface in Java to create a set out of the same elements contained in the map. It basically returns a set view of the map or we can create a new set and store the map elements into them. |
| equals(Object) | This method is used in Java Map Interface to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not. |
| get(Object) | This method is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. |
| hashCode() | This method is used in Map Interface to generate a hashCode for the given map containing keys and values. |
| isEmpty() | This method is used to check if a map is having any entry for key and value pairs. If no mapping exists, then this returns true. |
| keySet() | This method is used in Map Interface to return a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. |
| put(Object, Object) | This method is used in Java Map Interface to associate the specified value with the specified key in this map. |
| putAll(Map) | This method is used in Map Interface in Java to copy all of the mappings from the specified map to this map. |
| remove(Object) | This method is used in Map Interface to remove the mapping for a key from this map if it is present in the map. |
| size() | This method is used to return the number of key/value pairs available in the map. |
| values() | This method is used in Java Map Interface to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap. |
| getOrDefault(Object key, V defaultValue) | Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. |
| merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) | If the specified key is not already associated with a value or is associated with null, associate it with the given non-null value. |
| putIfAbsent(K key, V value) | If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current associate value. |
Example:
Java
// Java Program to Demonstrate
// Working of Map interface
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an empty HashMap
Map<String, Integer> hm
= new HashMap<String, Integer>();
// Inserting pairs in above Map
// using put() method
hm.put("a", new Integer(100));
hm.put("b", new Integer(200));
hm.put("c", new Integer(300));
hm.put("d", new Integer(400));
// Traversing through Map using for-each loop
for (Map.Entry<String, Integer> me :
hm.entrySet()) {
// Printing keys
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
}
}
Outputa:100
b:200
c:300
d:400
Hierarchy of Map Interface in Java
Classes that implement the Map interface are depicted in the below media and described later as follows:

1. HashMap
HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. This class uses a technique called Hashing. Hashing is a technique of converting a large String to a small String that represents the same String. A shorter value helps in indexing and faster searches. Let’s see how to create a map object using this class.
Example:
Java
// Java Program to illustrate the Hashmap Class
// Importing required classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty HashMap
Map<String, Integer> map = new HashMap<>();
// Inserting entries in the Map
// using put() method
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);
// Iterating over Map
for (Map.Entry<String, Integer> e : map.entrySet())
// Printing key-value pairs
System.out.println(e.getKey() + " "
+ e.getValue());
}
}
Outputvaibhav 20
vishal 10
sachin 30
2. LinkedHashMap
LinkedHashMap is just like HashMap with the additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. Let’s see how to create a map object using this class.
Example:
Java
// Java Program to Illustrate the LinkedHashmap Class
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Creating an empty LinkedHashMap
Map<String, Integer> map = new LinkedHashMap<>();
// Inserting pair entries in above Map
// using put() method
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);
// Iterating over Map
for (Map.Entry<String, Integer> e : map.entrySet())
// Printing key-value pairs
System.out.println(e.getKey() + " "
+ e.getValue());
}
}
Outputvishal 10
sachin 30
vaibhav 20
3. TreeMap
The TreeMap in Java is used to implement the Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs. The storing order maintained by the treemap must be consistent with equals just like any other sorted map, irrespective of the explicit comparators. Let’s see how to create a map object using this class.
Example:
Java
// Java Program to Illustrate TreeMap Class
// Importing required classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty TreeMap
Map<String, Integer> map = new TreeMap<>();
// Inserting custom elements in the Map
// using put() method
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);
// Iterating over Map using for each loop
for (Map.Entry<String, Integer> e : map.entrySet())
// Printing key-value pairs
System.out.println(e.getKey() + " "
+ e.getValue());
}
}
Outputsachin 30
vaibhav 20
vishal 10
Performing Operations using Map Interface and HashMap Class
Since Map is an interface, it can be used only with a class that implements this interface. Now, let’s see how to perform a few frequently used operations on a Map using the widely used HashMap class. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the map.
1. Adding Elements
In order to add an element to the map, we can use the put() method. However, the insertion order is not retained in the hashmap. Internally, for every element, a separate hash is generated and the elements are indexed based on this hash to make it more efficient.
Example:
Java
// Java program to demonstrate
// the working of Map interface
import java.util.*;
class GFG {
public static void main(String args[])
{
// Default Initialization of a
// Map
Map<Integer, String> hm1 = new HashMap<>();
// Initialization of a Map
// using Generics
Map<Integer, String> hm2
= new HashMap<Integer, String>();
// Inserting the Elements
hm1.put(1, "Geeks");
hm1.put(2, "For");
hm1.put(3, "Geeks");
hm2.put(new Integer(1), "Geeks");
hm2.put(new Integer(2), "For");
hm2.put(new Integer(3), "Geeks");
System.out.println(hm1);
System.out.println(hm2);
}
}
Output{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}
2. Changing Element
After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the map are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change.
Example:
Java
// Java program to demonstrate
// the working of Map interface
import java.util.*;
class GFG {
public static void main(String args[])
{
// Initialization of a Map
// using Generics
Map<Integer, String> hm1
= new HashMap<Integer, String>();
// Inserting the Elements
hm1.put(new Integer(1), "Geeks");
hm1.put(new Integer(2), "Geeks");
hm1.put(new Integer(3), "Geeks");
System.out.println("Initial Map " + hm1);
hm1.put(new Integer(2), "For");
System.out.println("Updated Map " + hm1);
}
}
OutputInitial Map {1=Geeks, 2=Geeks, 3=Geeks}
Updated Map {1=Geeks, 2=For, 3=Geeks}
3. Removing Elements
In order to remove an element from the Map, we can use the remove() method. This method takes the key value and removes the mapping for a key from this map if it is present in the map.
Example:
Java
// Java program to demonstrate
// the working of Map interface
import java.util.*;
class GFG {
public static void main(String args[])
{
// Initialization of a Map
// using Generics
Map<Integer, String> hm1
= new HashMap<Integer, String>();
// Inserting the Elements
hm1.put(new Integer(1), "Geeks");
hm1.put(new Integer(2), "For");
hm1.put(new Integer(3), "Geeks");
hm1.put(new Integer(4), "For");
// Initial Map
System.out.println(hm1);
hm1.remove(new Integer(4));
// Final Map
System.out.println(hm1);
}
}
Output{1=Geeks, 2=For, 3=Geeks, 4=For}
{1=Geeks, 2=For, 3=Geeks}
4. Iterating through the Map
There are multiple ways to iterate through the Map. The most famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method.
Example:
Java
// Java program to demonstrate
// the working of Map interface
import java.util.*;
class GFG {
public static void main(String args[])
{
// Initialization of a Map
// using Generics
Map<Integer, String> hm1
= new HashMap<Integer, String>();
// Inserting the Elements
hm1.put(new Integer(1), "Geeks");
hm1.put(new Integer(2), "For");
hm1.put(new Integer(3), "Geeks");
for (Map.Entry mapElement : hm1.entrySet()) {
int key = (int)mapElement.getKey();
// Finding the value
String value = (String)mapElement.getValue();
System.out.println(key + " : " + value);
}
}
}
Output1 : Geeks
2 : For
3 : Geeks
5. Count the Occurrence of numbers using Hashmap
In this code, we are using putIfAbsent() along with Collections.frequency() to count the exact occurrence of numbers. In many programs, you need to count the occurrence of a particular number or letter. You use the following approach to solve those types of problems .
Example:
Java
// Java program to Count the Occurrence
// of numbers using Hashmap
import java.util.*;
class HelloWorld {
public static void main(String[] args)
{
int a[] = { 1, 13, 4, 1, 41, 31, 31, 4, 13, 2 };
// put all elements in arraylist
ArrayList<Integer> aa = new ArrayList();
for (int i = 0; i < a.length; i++) {
aa.add(a[i]);
}
HashMap<Integer, Integer> h = new HashMap();
// counting occurrence of numbers
for (int i = 0; i < aa.size(); i++) {
h.putIfAbsent(aa.get(i), Collections.frequency(
aa, aa.get(i)));
}
System.out.println(h);
}
}
Output{1=2, 2=1, 4=2, 41=1, 13=2, 31=2} FAQs in Java Map Interface
Q. What is a map interface in Java?
Answer:
The map contains key-value pairs, where we access elements in the map using key values.
Q. What are the types of map interfaces in Java?
Answer:
There are 3 map interface implementations HashMap, LinkedHashMap, and TreeMap.
Similar Reads
Java Tutorial
Java is a high-level, object-oriented programming language used to build applications across platformsâfrom web and mobile apps to enterprise software. It is known for its Write Once, Run Anywhere capability, meaning code written in Java can run on any device that supports the Java Virtual Machine (
10 min read
Java Overview
Introduction to Java
Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is intended to let application developers Write Once and Run Anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the
9 min read
The Complete History of Java Programming Language
Java is an Object-Oriented programming language developed by James Gosling in the early 1990s. The team initiated this project to develop a language for digital devices such as set-top boxes, television, etc. Originally C++ was considered to be used in the project but the idea was rejected for sever
5 min read
How to Install Java on Windows, Linux and macOS?
Java is a versatile programming language widely used for building applications. To start coding in Java, you first need to install the Java Development Kit (JDK) on your system. This article provides detailed steps for installing Java on Windows 7, 8, 10, 11, Linux Ubuntu, and macOS. Download and In
5 min read
Setting up Environment Variables For Java - Complete Guide to Set JAVA_HOME
In the journey to learning the Java programming language, setting up environment variables for Java is essential because it helps the system locate the Java tools needed to run the Java programs. Now, this guide on how to setting up environment variables for Java is a one-place solution for Mac, Win
5 min read
How JVM Works - JVM Architecture
JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment). Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one s
7 min read
JDK in Java
The Java Development Kit (JDK) is a cross-platformed software development environment that offers a collection of tools and libraries necessary for developing Java-based software applications and applets. It is a core package used in Java, along with the JVM (Java Virtual Machine) and the JRE (Java
5 min read
Differences Between JDK, JRE and JVM
Understanding the difference between JDK, JRE, and JVM plays a very important role in understanding how Java works and how each component contributes to the development and execution of Java applications. The main difference between JDK, JRE, and JVM is: JDK: Java Development Kit is a software devel
4 min read
Java Basics
Java Syntax
Java is an object-oriented programming language that is known for its simplicity, portability, and robustness. The syntax of Java programming language is very closely aligned with C and C++, which makes it easier to understand. Java Syntax refers to a set of rules that defines how Java programs are
6 min read
Java Hello World Program
Java is one of the most popular and widely used programming languages and platforms. In this article, we will learn how to write a simple Java Program. This Java Hello World article will guide you through writing, compiling, and running your first Java program. Learning Java helps to develop applica
5 min read
Java Identifiers
An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names and every Java Variables must be identified with unique names. Example: public class Test{ public static void main(String[] args) { int a = 20; }}In the above Java code, we h
2 min read
Java Keywords
In Java, Keywords are the Reserved words in a programming language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Example : [GFGTABS] Java // Java Program to demonstrate Keywords class GFG { pub
5 min read
Java Data Types
Java is statically typed and also a strongly typed language because each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be declared with the specifi
14 min read
Java Variables
Variables are the containers for storing the data values or you can also call it a memory location name for the data. Every variable has a: Data Type - The kind of data that it can hold. For example, int, string, float, char, etc.Variable Name - To identify the variable uniquely within the scope.Val
7 min read
Scope of Variables in Java
The scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e. scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about J
6 min read
Java Operators
Java operators are special symbols that perform operations on variables or values. They can be classified into several categories based on their functionality. These operators play a crucial role in performing arithmetic, logical, relational, and bitwise operations etc. Example: Here, we are using +
14 min read
Java User Input
The most common way to take user input in Java is using Scanner class which is part of java.util package. The scanner class can read input from various sources like console, files or streams. This class was introduced in Java 5. Before that we use BufferedReader class(Introduced in Java 1.1). As a b
4 min read
Java Flow Control
Java if statement
The Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statements is executed otherwise not. Example: [GFGTABS] Java // Java program to ill
5 min read
Java if-else Statement
The if-else statement in Java is a powerful decision-making tool used to control the program's flow based on conditions. It executes one block of code if a condition is true and another block if the condition is false. In this article, we will learn Java if-else statement with examples. Example: [GF
4 min read
Java if-else-if ladder with Examples
The Java if-else-if ladder is used to evaluate multiple conditions sequentially. It allows a program to check several conditions and execute the block of code associated with the first true condition. If none of the conditions are true, an optional else block can execute as a fallback. Example: The
3 min read
Java For Loop
Java for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The for loop in Java provides an efficient way to iterate over a range of values, execute code multiple times, or traverse arrays and collections. Example: [GFGTABS] Java class Geeks { pu
4 min read
For-Each Loop in Java
The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required. Example: Below is a basic e
6 min read
Java while Loop
Java while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed. Let's go through a simple example of a Java while loop: [GFGT
3 min read
Java Do While Loop
Java do-while loop is an Exit control loop. Unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Example: [GFGTABS] Java // Java program to show the use of do while loop public class GFG { public static void main(String[] args) { int c = 1; //
4 min read
Java Break Statement
The Break Statement in Java is a control flow statement used to terminate loops and switch cases. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Example: [GFGTABS]
3 min read
Java Continue Statement
In Java, the continue statement is used inside the loops such as for, while, and do-while to skip the current iteration and move directly to the next iteration of the loop. Example: [GFGTABS] Java // Java Program to illustrate the use of continue statement public class Geeks { public static void mai
4 min read
Java return Keyword
return keyword in Java is a reserved keyword which is used to exit from a method, with or without a value. The usage of the return keyword can be categorized into two cases: Methods returning a valueMethods not returning a value1. Methods Returning a ValueFor the methods that define a return type, t
4 min read
Java Methods
Java Methods
Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects. Example: [GFGTABS] Java // Creating a method //
8 min read
How to Call a Method in Java?
Calling a method allows to reuse code and organize our program effectively. Java Methods are the collection of statements used for performing certain tasks and for returning the result to the user. In this article, we will learn how to call different types of methods in Java with simple examples. Ex
3 min read
Static Method vs Instance Method in Java
In Java, methods are mainly divided into two parts based on how they are associated with a class, which are the static method and the Instance method. The main difference between static and instance methods is: Static method: This method belongs to the class and can be called without creating an obj
4 min read
Access Modifiers in Java
Access Modifiers in Java control the visibility and accessibility of classes, methods, and variables, ensuring better security and encapsulation. Understanding default, private, protected, and public access modifiers is essential for writing efficient and structured Java programs. In this article, w
7 min read
Command Line Arguments in Java
Java command-line argument is an argument i.e. passed at the time of running the Java program. In Java, the command line arguments passed from the console can be received in the Java program and they can be used as input. The users can pass the arguments during the execution bypassing the command-li
3 min read
Variable Arguments (Varargs) in Java
Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplify the creation of methods that need to take a variable number of arguments. Example: We will see the demonstration of using Varargs in Java to pass a variable number of argum
5 min read
Java Arrays
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
How to Initialize an Array in Java?
An array in Java is a data structure used to store multiple values of the same data type. Each element in an array has a unique index value. It makes it easy to access individual elements. In an array, we have to declare its size first because the size of the array is fixed. In an array, we can stor
6 min read
Java Multi-Dimensional Arrays
A multidimensional array can be defined as an array of arrays. Multidimensional arrays in Java are not stored in tabular form. Each row is independently heap allocated, making it possible to have arrays with different row sizes. Example: [GFGTABS] Java // Java Program to Demonstrate // Multi Dimensi
9 min read
Jagged Array in Java
In Java, Jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. Example: arr [][]= { {1,2}, {3,4,5,6},{7,8,9}}; So, here you can check that the number of columns in row1!=row2!=row3. Tha
5 min read
Arrays class in Java
The Arrays class in java.util package is a part of the Java Collection Framework. This class provides static methods to dynamically create and access Java arrays. It consists of only static methods and the methods of Object class. The methods of this class can be used by the class name itself. The c
13 min read
Final Arrays in Java
As we all know final variable declared can only be initialized once whereas the reference variable once declared final can never be reassigned as it will start referring to another object which makes usage of the final impracticable. But note here that with final we are bound not to refer to another
4 min read
Java Strings
Java Strings
In Java, String is the type of objects that can store the sequence of characters enclosed by double quotes and every character is stored in 16 bits i.e using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowing
9 min read
Why Java Strings are Immutable?
In Java, strings are immutable means their values cannot be changed once they are created. This feature enhances performance, security, and thread safety. In this article, we will explain why strings are immutable in Java and how this benefits Java applications. What Does Immutable Mean?An immutable
3 min read
Java String concat() Method with Examples
The string concat() method concatenates (appends) a string to the end of another string. It returns the combined string. It is used for string concatenation in Java. It returns NullPointerException if any one of the strings is Null. In this article, we will learn how to concatenate two strings in Ja
4 min read
String class in Java
String is a sequence of characters. In Java, objects of the String class are immutable which means they cannot be changed once created. In this article, we will learn about the String class in Java. Example of String Class in Java: [GFGTABS] Java // Java Program to Create a String import java.io.*;
7 min read
StringBuffer class in Java
StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an alternative to the immutable String class, allowing you to modify the contents of a string without creating a new object every time. Features of StringBuffer ClassHere are some important features and met
12 min read
Java StringBuilder Class
In Java, the StringBuilder class is a part of the java.lang package that provides a mutable sequence of characters. Unlike String (which is immutable), StringBuilder allows in-place modifications, making it memory-efficient and faster for frequent string operations. Declaration: StringBuilder sb = n
7 min read
String vs StringBuilder vs StringBuffer in Java
A string is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed once created. In Java, String, StringBuilder, and StringBuffer are used for handling strings. The main difference is: String: Immutable, meaning its value cannot be changed onc
6 min read
Java OOPs Concepts
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable. The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Classes and Objects in Java
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
12 min read
Java Constructors
Java constructors or constructors in Java is a terminology used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects when they are created. It is automatically called when an object is instantiated using the new keyword. It can be used
11 min read
Object Class in Java
Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
8 min read
Abstraction in Java
Abstraction in Java is the process of hiding the implementation details and only showing the essential functionality or features to the user. This helps simplify the system by focusing on what an object does rather than how it does it. The unnecessary details or complexities are not displayed to the
9 min read
Encapsulation in Java
Encapsulation is one of the core concepts in Java Object-Oriented Programming (OOP). It is the process of wrapping data (variables) and methods that operate on the data into a single unit, i.e., a class. Encapsulation is used to hide the internal implementation details of a class. This technique ens
10 min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
14 min read
Polymorphism in Java
Polymorphism in Java is a fundamental concept in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms. In Java, polymorphism refers to the ability of a message to be displayed in more than one fo
8 min read
Method Overloading in Java
In Java, Method Overloading allows different methods to have the same name, but different signatures, where the signature can differ by the number of input parameters or the type of input parameters, or a mixture of both. Method overloading in Java is also known as Compile-time Polymorphism, Static
10 min read
Overriding in Java
Overriding in Java occurs when a subclass (child class) implements a method that is already defined in the superclass or Base Class. The overriding method must have the same name, parameters, and return type as the method in the parent class. This allows subclasses to modify inherited behavior while
15 min read
Java Packages
Packages in Java are a mechanism that encapsulates a group of classes, sub-packages, and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easie
8 min read
Java Interfaces
Java Interface
An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface: The interface in Java is a mechanism to
13 min read
Interfaces and Inheritance in Java
A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Example: [GFGTABS] Java //Driver Code Starts{ // A class can implement multiple interfaces import java.io.*; //Driver Code
7 min read
Java Class vs Interfaces
In Java, the difference between a class and an interface is syntactically similar; both contain methods and variables, but they are different in many aspects. The main difference is, A class defines the state of behaviour of objects.An interface defines the methods that a class must implement.Class
5 min read
Java Functional Interfaces
A functional interface in Java is an interface that contains only one abstract method. Functional interfaces can have multiple default or static methods, but only one abstract method. Runnable, ActionListener, and Comparator are common examples of Java functional interfaces. From Java 8 onwards, lam
7 min read
Nested Interface in Java
We can declare interfaces as members of a class or another interface. Such an interface is called a member interface or nested interface. Interfaces declared outside any class can have only public and default (package-private) access specifiers. In Java, nested interfaces (interfaces declared inside
5 min read
Marker Interface in Java
Marker Interface in Java is an empty interface means having no field or methods. Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces. Example: [GFGTABS] Java //Driver Code Starts{ interface Serializable { // Marker Interface } //Dr
4 min read
Java Comparator Interface
Comparator interface in Java is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2. Syntax: public int compare(Object obj1, Object obj2): Suppose we have an Array/ArrayList of our own
6 min read
Java Collections
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Collections Class in Java
Collections class in Java is one of the utility classes in Java Collections Framework. The java.util package contains the Collections class in Java. Java Collections class is used with the static methods that operate on the collections or return the collection. All the methods of this class throw th
13 min read
Collection Interface in Java
The Collection interface in Java is a core member of the Java Collections Framework located in the java.util package. It is one of the root interfaces of the Java Collection Hierarchy. The Collection interface is not directly implemented by any class. Instead, it is implemented indirectly through it
6 min read
Java List Interface
The List Interface in Java extends the Collection Interface and is a part of java.util package. It is used to store the ordered collections of elements. So in a Java List, you can organize and manage the data sequentially. Maintained the order of elements in which they are added.Allows the duplicate
15+ min read
ArrayList in Java
Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
10 min read
Vector Class in Java
The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is fully compatible with collections. It is found in java.util package and implement the List interface. Thread-Safe: All methods are synchronized, making it suitable for multi-threaded environments.
13 min read
LinkedList in Java
Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and addr
13 min read
Stack Class in Java
Java Collection framework provides a Stack class that models and implements a Stack data structure. The class is based on the basic principle of LIFO(last-in-first-out). In addition to the basic push and pop operations, the class provides three more functions of empty, search, and peek. The Stack cl
11 min read
Set in Java
The Set Interface is present in java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface adds a feature that restricts the insertion of the dupl
13 min read
Java HashSet
HashSet in Java implements the Set interface of Collections Framework. It is used to store the unique elements and it doesn't maintain any specific order of elements. Can store the Null values.Uses HashMap (implementation of hash table data structure) internally.Also implements Serializable and Clon
12 min read
TreeSet in Java
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree(red - black tree) for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equ
13 min read
Java LinkedHashSet
LinkedHashSet in Java implements the Set interface of the Collection Framework. It combines the functionality of a HashSet with a LinkedList to maintain the insertion order of elements. Stores unique elements only.Maintains insertion order.Provides faster iteration compared to HashSet.Allows null el
8 min read
Queue Interface In Java
The Queue Interface is present in java.util package and extends the Collection interface. It stores and processes the data in FIFO(First In First Out) order. It is an ordered list of objects limited to inserting elements at the end of the list and deleting elements from the start of the list. No Nul
13 min read
PriorityQueue in Java
The PriorityQueue class in Java is part of the java.util package. It is known that a Queue follows the FIFO(First-In-First-Out) Algorithm, but the elements of the Queue are needed to be processed according to the priority, that's when the PriorityQueue comes into play. The PriorityQueue is based on
11 min read
Deque Interface in Java
Deque Interface present in java.util package is a subtype of the queue interface. The Deque is related to the double-ended queue that supports adding or removing elements from either end of the data structure. It can either be used as a queue(first-in-first-out/FIFO) or as a stack(last-in-first-out/
10 min read
Map Interface in Java
In Java, Map Interface is present in the java.util package represents a mapping between a key and a value. Java Map interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the rest of the collection types. No Duplicates in Keys: Ensures that keys are uniqu
12 min read
HashMap in Java
In Java, HashMap is part of the Java Collections Framework and is found in the java.util package. It provides the basic implementation of the Map interface in Java. HashMap stores data in (key, value) pairs. Each key is associated with a value, and you can access the value by using the corresponding
15+ min read
Java LinkedHashMap
LinkedHashMap in Java implements the Map interface of the Collections Framework. It stores key-value pairs while maintaining the insertion order of the entries. It maintains the order in which elements are added. Stores unique key-value pairs.Maintains insertion order.Allows one null key and multipl
7 min read
Hashtable in Java
Hashtable class, introduced as part of the Java Collections framework, implements a hash table that maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method an
13 min read
Java Dictionary Class
Dictionary class in Java is an abstract class that represents a collection of key-value pairs, where keys are unique and used to access the values. It was part of the Java Collections Framework and it was introduced in Java 1.0 but has been largely replaced by the Map interface since Java 1.2. Store
5 min read
SortedSet Interface in Java with Examples
The SortedSet interface is present in java.util package extends the Set interface present in the collection framework. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this
8 min read
Java Comparator Interface
Comparator interface in Java is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2. Syntax: public int compare(Object obj1, Object obj2): Suppose we have an Array/ArrayList of our own
6 min read
Java Comparable Interface
The Comparable interface in Java is used to define the natural ordering of objects for a user-defined class. It is part of the java.lang package and it provides a compareTo() method to compare instances of the class. A class has to implement a Comparable interface to define its natural ordering. Exa
4 min read
Java Comparable vs Comparator
In Java, both Comparable and Comparator are used for sorting objects. The main difference between Comparable and Comparator is: Comparable: It is used to define the natural ordering of the objects within the class.Comparator: It is used to define custom sorting logic externally.Difference Between Co
4 min read
Java Iterator
An Iterator in Java is an interface used to traverse elements in a Collection sequentially. It provides methods like hasNext(), next(), and remove() to loop through collections and perform manipulation. An Iterator is a part of the Java Collection Framework, and we can use it with collections like A
7 min read