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 elements.
- The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector.
- Can add Null values that depend on the implementation.
- The List interface offers methods to access elements by their index and includes the listIterator() method, which returns a ListIterator.
- Using ListIterator, we can traverse the list in both forward and backward directions.
Example:
Java
// Java program to show the use of List Interface
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Creating a List of Strings using ArrayList
List<String> li = new ArrayList<>();
// Adding elements in List
li.add("Java");
li.add("Python");
li.add("DSA");
li.add("C++");
System.out.println("Elements of List are:");
// Iterating through the list
for (String s : li) {
System.out.println(s);
}
// Accessing elements
System.out.println("Element at Index 1: "+ li.get(1));
// Updating elements
li.set(1, "JavaScript");
System.out.println("Updated List: " + li);
// Removing elements
li.remove("C++");
System.out.println("List After Removing Element: " + li);
}
}
OutputElements of List are:
Java
Python
DSA
C++
Element at Index 1: Python
Updated List: [Java, JavaScript, DSA, C++]
List After Removing Element: [Java, JavaScript, DSA]
Declaration of Java List Interface
public interface List<E> extends Collection<E> ;
Let us elaborate on creating objects or instances in a List. Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List 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 List. Just like several other user-defined ‘interfaces’ implemented by user-defined ‘classes’, List is an ‘interface’, implemented by the ArrayList class, pre-defined in java.util package.
Syntax:
List<Obj> list = new ArrayList<Obj> ();
Obj is the type of the object to be stored in List.

The common implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector:
- ArrayList and LinkedList are the most widely used due to their dynamic resizing and efficient performance for specific operations.
- Stack is a subclass of
Vector, designed for Last-In-First-Out (LIFO) operations. - Vector is considered a legacy class and is rarely used in modern Java programming. It is replaced by ArrayList and java.util.concurrent package.
Now let us perform various operations using List Interface to have a better understanding of the same. We will be discussing the following operations listed below and later on implementing them via clean Java codes.
Java List – Operations
Since List 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 the List.
- Operation 1: Adding elements to List using add() method
- Operation 2: Updating elements in List using set() method
- Operation 3: Searching for elements using indexOf(), lastIndexOf methods
- Operation 4: Removing elements using remove() method
- Operation 5: Accessing Elements in List using get() method
- Operation 6: Checking if an element is present in the List using contains() method
Now let us discuss the operations individually and implement the same in the code to grasp a better grip over it.
1. Adding Elements
In order to add an element to the list, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters.
Parameters: It takes 2 parameters, namely:
- add(Object o): This method is used to add an element at the end of the List.
- add(int index, Object o): This method is used to add an element at a specific index in the List
Note: If we do not specify the length of the array in the ArrayList constructor while creating the List object, using add(int index, Object) for any index i will throw an Exception if we have not specified the values for 0 to i-1 index already.
Example:
Java
// Java Program to Add Elements to a List
import java.util.*;
class GFG {
public static void main(String args[])
{
// Creating an object of List interface,
// implemented by ArrayList class
List<String> al = new ArrayList<>();
// Adding elements to object of List interface
// Custom elements
al.add("Geeks");
al.add("Geeks");
al.add(1, "For");
// Print all the elements inside the
// List interface object
System.out.println(al);
}
}
Output[Geeks, For, Geeks]
2. Updating Elements
After adding the elements, if we wish to change the element, it can be done using the set() method. Since List is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index.
Example:
Java
// Java Program to Update Elements in a List
import java.util.*;
class GFG {
public static void main(String args[])
{
// Creating an object of List interface
List<String> al = new ArrayList<>();
// Adding elements to object of List class
al.add("Geeks");
al.add("Geeks");
al.add(1, "Geeks");
// Display theinitial elements in List
System.out.println("Initial ArrayList " + al);
// Setting (updating) element at 1st index
// using set() method
al.set(1, "For");
// Print and display the updated List
System.out.println("Updated ArrayList " + al);
}
}
OutputInitial ArrayList [Geeks, Geeks, Geeks]
Updated ArrayList [Geeks, For, Geeks]
3. Searching Elements
Searching for elements in the List interface is a common operation in Java programming. The List interface provides several methods to search for elements, such as the indexOf(), lastIndexOf() methods.
The indexOf() method returns the index of the first occurrence of a specified element in the list, while the lastIndexOf() method returns the index of the last occurrence of a specified element.
Parameters:
- indexOf(Object o): Returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found
- lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in the list, or -1 if the element is not found
Example:
Java
// Java program to search the elements in a List
import java.util.*;
class GFG {
public static void main(String[] args)
{
// create a list of integers
List<Integer> al = new ArrayList<>();
// add some integers to the list
al.add(1);
al.add(2);
al.add(3);
al.add(2);
// use indexOf() to find the first occurrence of an
// element in the list
int i = al.indexOf(2);
System.out.println("First Occurrence of 2 is at Index: "+i);
// use lastIndexOf() to find the last occurrence of
// an element in the list
int l = al.lastIndexOf(2);
System.out.println("Last Occurrence of 2 is at Index: "+l);
}
}
OutputFirst Occurrence of 2 is at Index: 1
Last Occurrence of 2 is at Index: 3
4. Removing Elements
In order to remove an element from a list, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are:
Parameters:
- remove(Object o): This method is used to simply remove an object from the List. If there are multiple such objects, then the first occurrence of the object is removed.
- remove(int index): Since a List is indexed, this method takes an integer value which simply removes the element present at that specific index in the List. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.
Example:
Java
// Java Program to Remove Elements from a List
import java.util.ArrayList;
import java.util.List;
class GFG {
public static void main(String args[])
{
// Creating List class object
List<String> al = new ArrayList<>();
// Adding elements to the object
// Custom inputs
al.add("Geeks");
al.add("Geeks");
// Adding For at 1st indexes
al.add(1, "For");
// Print the initialArrayList
System.out.println("Initial ArrayList " + al);
// Now remove element from the above list
// present at 1st index
al.remove(1);
// Print the List after removal of element
System.out.println("After the Index Removal " + al);
// Now remove the current object from the updated
// List
al.remove("Geeks");
// Finally print the updated List now
System.out.println("After the Object Removal " + al);
}
}
OutputInitial ArrayList [Geeks, For, Geeks]
After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]
5. Accessing Elements
In order to access an element in the list, we can use the get() method, which returns the element at the specified index
Parameters:
- get(int index): This method returns the element at the specified index in the list.
Example:
Java
// Java Program to Access Elements of a List
import java.util.*;
class GFG {
public static void main(String args[])
{
// Creating an object of List interface,
// implemented by ArrayList class
List<String> al = new ArrayList<>();
// Adding elements to object of List interface
al.add("Geeks");
al.add("For");
al.add("Geeks");
// Accessing elements using get() method
String first = al.get(0);
String second = al.get(1);
String third = al.get(2);
// Printing all the elements inside the
// List interface object
System.out.println(first);
System.out.println(second);
System.out.println(third);
System.out.println(al);
}
}
OutputGeeks
For
Geeks
[Geeks, For, Geeks]
6. Checking if an element is present or not
In order to check if an element is present in the list, we can use the contains() method. This method returns true if the specified element is present in the list, otherwise, it returns false.
Parameters:
- contains(Object o): This method takes a single parameter, the object to be checked if it is present in the list.
Example:
Java
// Java Program to Check if an Element is Present in a List
import java.util.*;
class GFG {
public static void main(String args[])
{
// Creating an object of List interface,
// implemented by ArrayList class
List<String> al = new ArrayList<>();
// Adding elements to object of List interface
al.add("Geeks");
al.add("For");
al.add("Geeks");
// Checking if element is present using contains()
// method
boolean isPresent = al.contains("Geeks");
// Printing the result
System.out.println("Is Geeks present in the list? "+ isPresent);
}
}
OutputIs Geeks present in the list? true
Complexity of List Interface in Java
Operation
| Time Complexity
| Space Complexity
|
|---|
Adding Element in List Interface
| O(1)
| O(1)
|
|---|
Remove Element from List Interface
| O(N)
| O(N)
|
|---|
Replace Element in List Interface
| O(N)
| O(N)
|
|---|
Traversing List Interface
| O(N)
| O(N)
|
|---|
Iterating over List Interface in Java
Till now we are having a very small input size and we are doing operations manually for every entity. Now let us discuss various ways by which we can iterate over the list to get them working for a larger sample set.
Methods: There are multiple ways to iterate through the List. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for a loop.
Example:
Java
// Java program to Iterate the Elements
// in an List
import java.util.*;
public class GFG {
public static void main(String args[])
{
// Creating an empty Arraylist of string type
List<String> al = new ArrayList<>();
// Adding elements to above object of ArrayList
al.add("Geeks");
al.add("Geeks");
// Adding element at specified position
// inside list object
al.add(1, "For");
// Using for loop for iteration
for (int i = 0; i < al.size(); i++) {
// Using get() method to
// access particular element
System.out.print(al.get(i) + " ");
}
// New line for better readability
System.out.println();
// Using for-each loop for iteration
for (String str : al)
// Printing all the elements
// which was inside object
System.out.print(str + " ");
}
}
OutputGeeks For Geeks
Geeks For Geeks
Methods of the List Interface
Since the main concept behind the different types of lists is the same, the list interface contains the following methods:
Method
| Description
|
|---|
| add(int index, element) | This method is used with Java List Interface to add an element at a particular index in the list. When a single parameter is passed, it simply adds the element at the end of the list. |
| addAll(int index, Collection collection) | This method is used with List Interface in Java to add all the elements in the given collection to the list. When a single parameter is passed, it adds all the elements of the given collection at the end of the list. |
| size() | This method is used with Java List Interface to return the size of the list. |
| clear() | This method is used to remove all the elements in the list. However, the reference of the list created is still stored. |
| remove(int index) | This method removes an element from the specified index. It shifts subsequent elements(if any) to left and decreases their indexes by 1. |
| remove(element) | This method is used with Java List Interface to remove the first occurrence of the given element in the list. |
| get(int index) | This method returns elements at the specified index. |
| set(int index, element) | This method replaces elements at a given index with the new element. This function returns the element which was just replaced by a new element. |
| indexOf(element) | This method returns the first occurrence of the given element or -1 if the element is not present in the list. |
| lastIndexOf(element) | This method returns the last occurrence of the given element or -1 if the element is not present in the list. |
| equals(element) | This method is used with Java List Interface to compare the equality of the given element with the elements of the list. |
| hashCode() | This method is used with List Interface in Java to return the hashcode value of the given list. |
| isEmpty() | This method is used with Java List Interface to check if the list is empty or not. It returns true if the list is empty, else false. |
| contains(element) | This method is used with List Interface in Java to check if the list contains the given element or not. It returns true if the list contains the element. |
| containsAll(Collection collection) | This method is used with Java List Interface to check if the list contains all the collection of elements. |
| sort(Comparator comp) | This method is used with List Interface in Java to sort the elements of the list on the basis of the given comparator. |
Java List vs Set
Both the List interface and the Set interface inherits the Collection interface. However, there exists some differences between them.
List
| Set
|
|---|
| The List is an ordered sequence. | The Set is an unordered sequence. |
| List allows duplicate elements | Set doesn’t allow duplicate elements. |
| Elements by their position can be accessed. | Position access to elements is not allowed. |
| Multiple null elements can be stored. | The null element can store only once. |
| List implementations are ArrayList, LinkedList, Vector, Stack | Set implementations are HashSet, LinkedHashSet. |
Classes Association with a Java List Interface
Now let us discuss the classes that implement the List Interface for which first do refer to the pictorial representation below to have a better understanding of the List interface. It is as follows:

AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the List interface. A separate functionality is implemented in each of the mentioned classes. They are as follows:
- AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
- CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.
- AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
We will proceed in this manner.
- ArrayList
- Vector
- Stack
- LinkedList
Let us discuss them sequentially and implement the same to figure out the working of the classes with the List interface.
1. ArrayList
An ArrayList class which is implemented in the collection framework provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. Let’s see how to create a list object using this class.
Example:
Java
// Java program to demonstrate the
// creation of list object using the
// ArrayList class
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Size of ArrayList
int n = 5;
// Declaring the List with initial size n
List<Integer> arrli = new ArrayList<Integer>(n);
// Appending the new elements
// at the end of the list
for (int i = 1; i <= n; i++)
arrli.add(i);
// Printing elements
System.out.println(arrli);
// Remove element at index 3
arrli.remove(3);
// Displaying the list after deletion
System.out.println(arrli);
// Printing elements one by one
for (int i = 0; i < arrli.size(); i++)
System.out.print(arrli.get(i) + " ");
}
}
Output[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
2. Vector
Vector is a class that is implemented in the collection framework implements a growable array of objects. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index. Vectors basically fall in legacy classes but now it is fully compatible with collections. Let’s see how to create a list object using this class.
Example:
Java
// Java program to demonstrate the
// creation of list object using the
// Vector class
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Size of the vector
int n = 5;
// Declaring the List with initial size n
List<Integer> v = new Vector<Integer>(n);
// Appending the new elements
// at the end of the list
for (int i = 1; i <= n; i++)
v.add(i);
// Printing elements
System.out.println(v);
// Remove element at index 3
v.remove(3);
// Displaying the list after deletion
System.out.println(v);
// Printing elements one by one
for (int i = 0; i < v.size(); i++)
System.out.print(v.get(i) + " ");
}
}
Output[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
3. Stack
Stack is a class that is implemented in the collection framework and extends the vector class models and implements the Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. Let’s see how to create a list object using this class.
Example:
Java
// Java program to demonstrate the
// creation of list object using the
// Stack class
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Size of the stack
int n = 5;
// Declaring the List
List<Integer> s = new Stack<Integer>();
// Appending the new elements
// at the end of the list
for (int i = 1; i <= n; i++)
s.add(i);
// Printing elements
System.out.println(s);
// Remove element at index 3
s.remove(3);
// Displaying the list after deletion
System.out.println(s);
// Printing elements one by one
for (int i = 0; i < s.size(); i++)
System.out.print(s.get(i) + " ");
}
}
Output[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
4. LinkedList
LinkedList is a class that is implemented in the collection framework which inherently implements the linked list data structure. It 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 address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. Let’s see how to create a list object using this class.
Example:
Java
// Java program to demonstrate the
// creation of list object using the
// LinkedList class
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Size of the LinkedList
int n = 5;
// Declaring the List with initial size n
List<Integer> ll = new LinkedList<Integer>();
// Appending the new elements
// at the end of the list
for (int i = 1; i <= n; i++)
ll.add(i);
// Printing elements
System.out.println(ll);
// Remove element at index 3
ll.remove(3);
// Displaying the list after deletion
System.out.println(ll);
// Printing elements one by one
for (int i = 0; i < ll.size(); i++)
System.out.print(ll.get(i) + " ");
}
}
Output[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Start your Java programming journey today with our Java Programming Online Course, designed for both beginners and advanced learners. With self-paced lessons covering everything from basic syntax to advanced concepts, you’ll gain the skills needed to excel in the world of programming.
Take the Three 90 Challenge! Complete 90% of the course in 90 days, and earn a 90% refund. Track your progress and stay motivated as you master Java.
Join now and start your path to becoming a Java expert!
Similar Reads
Java Tutorial
Java is one of the most popular and widely used programming languages. Used to develop mobile apps, desktop apps, web apps, web servers, games, and enterprise-level systems. Java was invented by James Gosling and Oracle currently owns it. JDK 23 is the latest version of Java. Java's syntax is simila
4 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
Setting up environment variables for Java is essential because it helps the system locate the Java tools needed to run the Java programs. Before setting up the environment variables, the Java Development Kit (JDK) needs to be installed on your system and you must know the JDK installation directory
4 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
3 min read
Java Basics
Java Syntax
Java is an object-oriented programming language which 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. Let's understand the Syntax and Structure of Java Programs with a basic
5 min read
Java Hello World Program
Java is one of the most popular and widely used programming languages and platforms. Java is fast, reliable, and secure. Java is used in every nook and corner from desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet. In this article, we will learn h
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, in Java, 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 described with
11 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
Scope of a variable 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 function call stack. Java programs are organized in the form of cla
5 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, continue statement is used inside the loops such as for, while and do-while to skip the curren 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 GFG { public static void main(String
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
In Java, Access modifiers helps to restrict the scope of a class, constructor, variable, method, or data member. It provides security, accessibility, etc. to the user depending upon the access modifier used with the element. In this article, let us learn about Java Access Modifiers, their types, and
6 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 are fundamental structures in Java 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 memory management. For
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, StringBuilder class is a part of the java.lang package that provides a mutable sequence of characters. Unlike String, which creates a new object for every modification, StringBuilder allows in-place changes, making it memory-efficient and faster for large or frequent string manipulations. I
4 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
Object-Oriented Programming or Java OOPs concept refers to programming languages that use objects in programming. They use objects as a primary source to implement what is to happen in the code. Objects are seen by the viewer or user, performing tasks you assign. Object-oriented programming aims to
11 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. For example, the animal type Dog is a class while a particular dog named
11 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. The constructor is called when an object of a class is created. It can be used to set initial values for object attrib
8 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 in which we only show essential details/functionality to the user. The non-essential implementation details are not displayed to the user. In this article, we will learn about abstraction and what abstraction means. Simple Example to understand Abstraction:Televisi
11 min read
Encapsulation in Java
Encapsulation in Java is a fundamental OOP (object-oriented programming) principle that combines data and methods in a class. It allows implementation details to be hidden while exposing a public interface for interaction. Example: Below is a simple example of Encapsulation in Java. [GFGTABS] Java /
7 min read
Inheritance in Java
Java, Inheritance is an important pillar of 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 ano
12 min read
Polymorphism in Java
The word ‘polymorphism’ means ‘having many forms’. In Java, polymorphism refers to the ability of a message to be displayed in more than one form. This concept is a key feature of Object-Oriented Programming and it allows objects to behave differently based on their specific class type. Real-life Il
6 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 type of input parameters, or a mixture of both. Method overloading in Java is also known as Compile-time Polymorphism, Static Polym
9 min read
Overriding in Java
Overriding in Java occurs when a subclass implements a method which is already defined in the superclass or Base Class. The method in the subclass must have the same signature as in the superclass. It allows the subclass to modify the inherited methods. Example: Below is an example of how overriding
13 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
7 min read
Java Interfaces
Java Interface
An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction. By defaul
9 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 behavior of objects.An interface defines the methods that a class must implement.Class v
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
Comparator Interface in Java with Examples
A comparator interface 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 class
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 collections framework and it is a class of java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in array is required. The main advantage of ArrayList is, unli
9 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
Comparator Interface in Java with Examples
A comparator interface 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 class
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
Java Exception Handling
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runt
10 min read
Java Checked vs Unchecked Exceptions
In Java, Exceptions an unwanted or unexpected event, that occurs during the execution of a program, i.e. at run time, disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions: Checked Exception: These exceptions are checked at compile time, forcing the progr
4 min read
Java Try Catch Block
try-catch block in Java is a mechanism to handle exceptions. This ensures that the application continues to run even if an error occurs. The code inside the try block is executed, and if any exception occurs, it is then caught by the catch block. Example 1: Here, in the below example we handled the
4 min read
final, finally and finalize in Java
This is an important question concerning the interview point of view. final keyword final (lowercase) is a reserved keyword in java. We can't use it as an identifier, as it is reserved. We can use this keyword with variables, methods, and also with classes. The final keyword in java has a different
13 min read
throw and throws in Java
In Java, Exception Handling is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. It handles runtime errors such as NullPointerException, ArrayIndexOutOfBoundsException, etc. To handle these errors effectively, Java provides two key conc
5 min read
User-Defined Custom Exception in Java
In Java, an Exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Java provides us the facility to create our own exceptions
4 min read
Chained Exceptions in Java
Chained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero, but the root cause of the error was an I/O
3 min read
Null Pointer Exception in Java
A NullPointerException in Java is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value. Example: [GFGTABS] Java // Demonstration of NullPointerException in J
5 min read
Exception Handling with Method Overriding in Java
An Exception is an unwanted or unexpected event that occurs during a program's execution, i.e., at runtime and disrupts the normal flow of the program’s instructions. Exception handling in Java handles runtime errors and helps maintain the program's normal flow. In any object-oriented programming,
4 min read
Java Multithreading
Java Multithreading Tutorial
Threads are the backbone of multithreading. We are living in a real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking ef
15+ min read
Java Threads
Threads are lightweight subprocesses, representing the smallest unit of execution with separate paths. The main advantage of multiple threads is efficiency (allowing multiple things at the same time). For example, in MS Word, one thread automatically formats the document while another thread is taki
11 min read
Java.lang.Thread Class in Java
Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls in order to manage the behavior of
8 min read
Runnable interface in Java
java.lang.Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread - Subclass Thread and implement Runnable. There is no need of subclassing a Thread when a task can be done by overriding only run(
3 min read
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant: New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram shown below represents various states of a thread at any inst
6 min read
Main thread in Java
Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running i
4 min read
Java Thread Priority in Multithreading
As we already know java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be give
5 min read
Naming a thread and fetching name of current thread in Java
Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. now let us discuss the eccentric concept of with what ways we can name a
5 min read
Difference between Thread.start() and Thread.run() in Java
In Java's multi-threading concept, start() and run() are the two most important methods. Below are some of the differences between the Thread.start() and Thread.run() methods: New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed.
3 min read
Thread.sleep() Method in Java With Examples
Thread Class is a class that is basically a thread of execution of the programs. It is present in Java.lang package. Thread class contains the Sleep() method. There are two overloaded methods of Sleep() method present in Thread Class, one is with one argument and another one is with two arguments. T
4 min read
Daemon Thread in Java
In Java, daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection or provide services to user threads. The life of a daemon thread depends on the mercy of user threads, meaning that when all user threads finish their execution, the Java Virtual M
4 min read
Thread Safety and how to achieve it in Java
As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already wor
5 min read
Thread Pools in Java
Background Server Programs such as database and web servers repeatedly execute requests from multiple clients and these are oriented around processing a large number of short tasks. An approach for building a server application would be to create a new thread each time a request arrives and service
9 min read
Java File Handling
File Handling in Java
In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file. Why File Handling is Required? File Handling is an integral part of any programming lan
7 min read
Java File Class
Java File class is a representation of a file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. Java File class contains several methods for working with the pathname, deleting and renaming files, crea
6 min read
Java Program to Create a New File
A File is an abstract path, it has no physical existence. It is only when "using" that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is created. The file is one way, in which data will be stored as per requirement. Steps to Create a N
8 min read
Java Program to Write into a File
In this article, we will see different ways of writing into a File using Java Programming language. Java FileWriter class in java is used to write character-oriented data to a file as this class is character-oriented class because of what it is used in file handling in java. There are many ways to
7 min read
Delete a File Using Java
Java provides methods to delete files using java programs. On contrary to normal delete operations in any operating system, files being deleted using the java program are deleted permanently without being moved to the trash/recycle bin. Methods used to delete a file in Java: 1. Using java.io.File.de
2 min read
Java FileReader Class
FileReader in Java is a class in the java.io package which can be used to read a stream of characters from the files. Java IO FileReader class uses either specified charset or the platform's default charset for decoding from bytes to characters. 1. Charset: The Charset class is used to define method
3 min read
FileWriter Class in Java
Java FileWriter class of java.io package is used to write data in character form to file. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in java. This class inherits from OutputStreamWriter class which in turn
7 min read
Java.io.FilePermission Class in Java
java.io.FilePermission class is used to represent access to a file or a directory. These accesses are in the form of a path name and a set of actions associated to the path name(specifies which file to be open along with the extension and the path). For Example, in FilePermission("GEEKS.txt", "read"
5 min read
Java FileDescriptor Class
java.io.FileDescriptor class in Java works for opening a file having a specific name. If there is any content present in that file it will first erase all that content and put "Beginning of Process" as the first line. Instances of the file descriptor class serve as an opaque handle to the underlying
4 min read
Java Streams and Lambda Expressions
Java IO
Java IO : Input-output in Java with Examples
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations. Before exploring various input and output streams lets look at 3 sta
6 min read
Java Reader Class
Reader class in Java is an abstract class used for reading character streams. It serves as the base class for various subclasses like FileReader, BufferedReader, CharArrayReader, and others, which provide more efficient implementations of the read() method. To work with the Reader class, we must ext
7 min read
Java.io.Writer Class in Java
java.io.Writer class is an abstract class. It is used to write to character streams. Declaration of Writer Class in Javapublic abstract class Writer extends Object implements Appendable, Closeable, FlushableConstructors of Java Writer Classprotected Writer(): Creates a new character stream that can
6 min read
Java.io.FileInputStream Class in Java
FileInputStream class is useful to read data from a file in the form of sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. Constructors of FileInputStream Class 1. FileInputStream(File file):
3 min read
FileOutputStream in Java
FileOutputStream is an outputstream for writing data/streams of raw bytes to file or storing data to file. FileOutputStream is a subclass of OutputStream. To write primitive values into a file, we use FileOutputStream class. For writing byte-oriented and character-oriented data, we can use FileOutpu
5 min read
Ways to read input from console in Java
In Java, there are four different ways to read input from the user in the command line environment(console). 1. Using Buffered Reader ClassThis is the Java classical method to take input, Introduced in JDK 1.0. This method is used by wrapping the System.in (standard input stream) in an InputStreamRe
5 min read
Java BufferedOutputStream Class
BufferedOutputStream class in Java is a part of the java.io package. It improves the efficiency of writing data to an output stream by buffering the data. This reduces the number of direct writes to the underlying output stream, making the process faster and more efficient. Example 1: The below Java
2 min read
Java BufferedReader vs Scanner Class
Java provides several classes for reading input but two of the most commonly used are Scanner and BufferedReader. The main difference between Scanner and BufferedReader is that Scanner Class provides parsing and input reading capabilities with built-in methods for different data types while Buffered
2 min read
Fast I/O in Java in Competitive Programming
Using Java in competitive programming is not something many people would suggest just because of its slow input and output, and well indeed it is slow. In this article, we have discussed some ways to get around the difficulty and change the verdict from TLE to (in most cases) AC. Example: Input:7 31
7 min read
Java Networking
Java Networking
When computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is
15+ min read
TCP/IP Model
The TCP/IP model is a fundamental framework for computer networking. It stands for Transmission Control Protocol/Internet Protocol, which are the core protocols of the Internet. This model defines how data is transmitted over networks, ensuring reliable communication between devices. It consists of
14 min read
User Datagram Protocol (UDP)
User Datagram Protocol (UDP) is a Transport Layer protocol. UDP is a part of the Internet Protocol suite, referred to as UDP/IP suite. Unlike TCP, it is an unreliable and connectionless protocol. So, there is no need to establish a connection before data transfer. The UDP helps to establish low-late
10 min read
Difference Between IPv4 and IPv6
In the digital world, where billions of devices connect and communicate, Internet Protocol (IP) Addresses play a crucial role. These addresses are what allow devices to identify and locate each other on a network. To know all about IP Addresses - refer to What is an IP Address? Currently, there are
9 min read
Difference Between Connection-oriented and Connection-less Services
In computer networks, communication between devices occurs using two types of services: connection-oriented and connectionless. These services define how data is transferred between a source and a destination. Connection-oriented services establish a dedicated connection before data transfer, ensuri
5 min read
Socket Programming in Java
Socket programming in Java allows different programs to communicate with each other over a network, whether they are running on the same machine or different ones. This article describes a very basic one-way Client and Server setup, where a Client connects, sends messages to the server and the serve
6 min read
Java ServerSocket Class
ServerSocket Class in Java provides a system-independent way to implement the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it can’t listen on the specified port (for example, the port is already being used). In the java.nio channel, Server
4 min read
URL Class in Java with Examples
URL known as Uniform Resource Locator is simply a string of text that identifies all the resources on the Internet, telling us the address of the resource, how to communicate with it, and retrieve something from it. Components of a URL A URL can have many forms. The most general however follows a th
4 min read
Java Memory Allocation
Java Memory Management
Java memory management is a fundamental concept that involves the automatic allocation and deallocation of objects, managed by the Java Virtual Machine (JVM). The JVM uses a garbage collector to automatically remove unused objects, freeing up memory in the background. This eliminates the need for de
5 min read
How are Java objects stored in memory?
In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In JAVA , when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.In Java, when we only de
3 min read
Stack vs Heap Memory Allocation
Memory in a C/C++/Java program can either be allocated on a stack or a heap.Prerequisite: Memory layout of C program. Stack Allocation: The allocation happens on contiguous blocks of memory. We call it a stack memory allocation because the allocation happens in the function call stack. The size of m
7 min read
Java Virtual Machine (JVM) Stack Area
The Java Virtual Machine is responsible for running Java applications, and it manages various memory areas, one of which is the Stack Area. In this article, we are going to discuss about JVM Stack Area in depth. In Java, each thread has its stack called the Run-Time Stack, created when the thread st
4 min read
How Many Types of Memory Areas are Allocated by JVM?
JVM (Java Virtual Machine) is an abstract machine, In other words, it is a program/software which takes Java bytecode and converts the byte code (line by line) into machine-understandable code. JVM acts as a run-time engine to run Java applications. JVM is the one that calls the main method present
4 min read
Garbage Collection in Java
Garbage collection in Java is an automatic memory management process that helps Java programs run efficiently. Java programs compile to bytecode that can be run on a Java Virtual Machine (JVM). When Java programs run on the JVM, objects in the heap, which is a portion of memory dedicated to the prog
7 min read
Types of JVM Garbage Collectors in Java with implementation details
prerequisites: Garbage Collection, Mark and Sweep algorithm Garbage Collection: Garbage collection aka GC is one of the most important features of Java. Garbage collection is the mechanism used in Java to de-allocate unused memory, which is nothing but clear the space consumed by unused objects. To
5 min read
Stack vs Heap Memory Allocation
Memory in a C/C++/Java program can either be allocated on a stack or a heap.Prerequisite: Memory layout of C program. Stack Allocation: The allocation happens on contiguous blocks of memory. We call it a stack memory allocation because the allocation happens in the function call stack. The size of m
7 min read
Memory leaks in Java
In C, programmers totally control allocation and deallocation of dynamically created objects. And if a programmer does not destroy objects, memory leak happens in C, Java does automatic Garbage collection. However there can be situations where garbage collector does not collect objects because there
1 min read
Java Interview Questions
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java Multiple Choice Questions
Java is a widely used high-level, general-purpose, object-oriented programming language and platform that was developed by James Gosling in 1982. Java Supports WORA(Write Once, Run Anywhere) also, it defined as 7th most popular programming language in the world. Java language is a high-level, multi-
3 min read
Java Projects
Top 50 Java Project Ideas For Beginners and Advanced [Update 2025]
Java is one of the most popular and versatile programming languages, known for its reliability, security, and platform independence. Developed by James Gosling in 1982, Java is widely used across industries like big data, mobile development, finance, and e-commerce. Building Java projects is an exce
15+ min read
Number guessing game in Java
The task is to write a Java program in which a user will get K trials to guess a randomly generated number. Below are the rules of the game: If the guessed number is bigger than the actual number, the program will respond with the message that the guessed number is higher than the actual number.If t
3 min read
Mini Banking Application in Java
In any Bank Transaction, there are several parties involved to process transaction like a merchant, bank, receiver, etc. so there are several numbers reasons that transaction may get failed, declined, so to handle a transaction in Java, there is a JDBC (Java Database Connectivity) which provides us
7 min read
Java program to convert Currency using AWT
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications.
4 min read
Tic-Tac-Toe Game in Java
In the Tic-Tac-Toe game, you will see the approach of the game is implemented. In this game, two players will be played and you have one print board on the screen where from 1 to 9 number will be displayed or you can say it box number. Now, you have to choose X or O for the specific box number. For
6 min read
Design Snake Game
Let us see how to design a basic Snake Game that provides the following functionalities: Snake can move in a given direction and when it eats the food, the length of snake increases. When the snake crosses itself, the game will be over. Food will be generated at a given interval.Asked In: Amazon, Mi
9 min read
Memory Game in Java
The Memory Game is a game where the player has to flip over pairs of cards with the same symbol. We create two arrays to represent the game board: board and flipped. The board is an array of strings that represents the state of the game board at any given time.When a player flips a card, we replace
3 min read
How to Implement a Simple Chat Application Using Sockets in Java?
In this article, we will create a simple chat application using Java socket programming. Before we are going to discuss our topic, we must know Socket in Java. Java Socket connects two different JREs (Java Runtime Environment). Java sockets can be connection-oriented or connection-less. In Java, we
4 min read
Image Processing in Java - Face Detection
Prerequisites: Image Processing in Java - Read and WriteImage Processing In Java - Get and Set PixelsImage Processing in Java - Colored Image to Grayscale Image ConversionImage Processing in Java - Colored Image to Negative Image ConversionImage Processing in Java - Colored to Red Green Blue Image C
3 min read
Design Media Sharing Social Networking System
PURPOSE OF MEDIA SOCIAL NETWORKING SERVICE SYSTEMThis system will allow users to share photos and videos with other users. Additionally, users can follow other users based on follow request and they can see other user's photos and videos. In this system, you can search users and see their profile if
14 min read
Java Swing | Create a simple text editor
To create a simple text editor in Java Swing we will use a JTextArea, a JMenuBar and add JMenu to it and we will add JMenuItems. All the menu items will have actionListener to detect any action.There will be a menu bar and it will contain two menus and a button: File menuopen: this menuitem is used
6 min read