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 known as networking.

In simple words, the term network programming or networking associates with writing programs that can be executed over various computer devices, in which all the devices are connected to each other to share resources using a network. Here, we are going to discuss Java Networking.
- What is Java Networking?
- Common Network Protocols
- Java Network Terminology
- Java Networking Classes
- Java Networking Interfaces
- Socket Programming
- Inet Address
- URL Class
What is Java Networking?
Networking supplements a lot of power to simple programs. With networks, a single program can regain information stored in millions of computers positioned anywhere in the world. Java is the leading programming language composed from scratch with networking in mind. Java Networking is a notion of combining two or more computing devices together to share resources.
All the Java program communications over the network are done at the application layer. The java.net package of the J2SE APIs comprises various classes and interfaces that execute the low-level communication features, enabling the user to formulate programs that focus on resolving the problem.
Common Network Protocols
As stated earlier, the java.net package of the Java programming language includes various classes and interfaces that provide an easy-to-use means to access network resources. Other than classes and interfaces, the java.net package also provides support for the two well-known network protocols. These are:
- Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol allows secure communication between different applications. TCP is a connection-oriented protocol which means that once a connection is established, data can be transmitted in two directions. This protocol is typically used over the Internet Protocol. Therefore, TCP is also referred to as TCP/IP. TCP has built-in methods to examine for errors and ensure the delivery of data in the order it was sent, making it a complete protocol for transporting information like still images, data files, and web pages.
- User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a connection-less protocol that allows data packets to be transmitted between different applications. UDP is a simpler Internet protocol in which error-checking and recovery services are not required. In UDP, there is no overhead for opening a connection, maintaining a connection, or terminating a connection. In UDP, the data is continuously sent to the recipient, whether they receive it or not.
Note: You can study more about TCP and UDP from the Differences between TCP and UDP.
Java Networking Terminology
In Java Networking, many terminologies are used frequently. These widely used Java Networking Terminologies are given as follows:
- IP Address – An IP address is a unique address that distinguishes a device on the internet or a local network. IP stands for “Internet Protocol.” It comprises a set of rules governing the format of data sent via the internet or local network. IP Address is referred to as a logical address that can be modified. It is composed of octets. The range of each octet varies from 0 to 255.
- Range of the IP Address – 0.0.0.0 to 255.255.255.255
- For Example – 192.168.0.1
- Port Number – A port number is a method to recognize a particular process connecting internet or other network information when it reaches a server. The port number is used to identify different applications uniquely. The port number behaves as a communication endpoint among applications. The port number is correlated with the IP address for transmission and communication among two applications. There are 65,535 port numbers, but not all are used every day.
- Protocol – A network protocol is an organized set of commands that define how data is transmitted between different devices in the same network. Network protocols are the reason through which a user can easily communicate with people all over the world and thus play a critical role in modern digital communications. For Example – TCP, FTP, POP, etc.
- MAC Address – MAC address stands for Media Access Control address. It is a bizarre identifier that is allocated to a NIC (Network Interface Controller/ Card). It contains a 48 bit or 64-bit address, which is combined with the network adapter. MAC address can be in hexadecimal composition. In simple words, a MAC address is a unique number that is used to track a device in a network.
- Socket – A socket is one endpoint of a two-way communication connection between the two applications running on the network. The socket mechanism presents a method of inter-process communication (IPC) by setting named contact points between which the communication occurs. A socket is tied to a port number so that the TCP layer can recognize the application to which the data is intended to be sent.
- Connection-oriented and connection-less protocol – In a connection-oriented service, the user must establish a connection before starting the communication. When the connection is established, the user can send the message or the information, and after this, they can release the connection. However, In connectionless protocol, the data is transported in one route from source to destination without verifying that the destination is still there or not or if it is ready to receive the message. Authentication is not needed in the connectionless protocol.
- Example of Connection-oriented Protocol – Transmission Control Protocol (TCP)
- Example of Connectionless Protocol – User Datagram Protocol (UDP)
Java Networking classes
The java.net package of the Java programming language includes various classes that provide an easy-to-use means to access network resources. The classes covered in the java.net package are given as follows –
- CacheRequest – The CacheRequest class is used in java whenever there is a need to store resources in ResponseCache. The objects of this class provide an edge for the OutputStream object to store resource data into the cache.
- CookieHandler – The CookieHandler class is used in Java to implement a callback mechanism for securing up an HTTP state management policy implementation inside the HTTP protocol handler. The HTTP state management mechanism specifies the mechanism of how to make HTTP requests and responses.
- CookieManager – The CookieManager class is used to provide a precise implementation of CookieHandler. This class separates the storage of cookies from the policy surrounding accepting and rejecting cookies. A CookieManager comprises a CookieStore and a CookiePolicy.
- DatagramPacket – The DatagramPacket class is used to provide a facility for the connectionless transfer of messages from one system to another. This class provides tools for the production of datagram packets for connectionless transmission by applying the datagram socket class.
- InetAddress – The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses.
- Server Socket – The ServerSocket class is used for implementing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used.
- Socket – The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object built using java.net.Socket class has been connected exactly with 1 remote host; for connecting to another host, a user must create a new socket object.
- DatagramSocket – The DatagramSocket class is a network socket that provides a connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can further be practiced for transmitting and accepting broadcast information. Datagram Sockets is Java’s mechanism for providing network communication via UDP instead of TCP.
- Proxy – A proxy is a changeless object and a kind of tool or method or program or system, which serves to preserve the data of its users and computers. It behaves like a wall between computers and internet users. A Proxy Object represents the Proxy settings to be applied with a connection.
- URL – The URL class in Java is the entry point to any available sources on the internet. A Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide Web. A source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to a database or a search engine.
- URLConnection – The URLConnection class in Java is an abstract class describing a connection of a resource as defined by a similar URL. The URLConnection class is used for assisting two distinct yet interrelated purposes. Firstly it provides control on interaction with a server(especially an HTTP server) than a URL class. Furthermore, with a URLConnection, a user can verify the header transferred by the server and can react consequently. A user can also configure header fields used in client requests using URLConnection.
Java Networking Interfaces
The java.net package of the Java programming language includes various interfaces also that provide an easy-to-use means to access network resources. The interfaces included in the java.net package are as follows:
- CookiePolicy – The CookiePolicy interface in the java.net package provides the classes for implementing various networking applications. It decides which cookies should be accepted and which should be rejected. In CookiePolicy, there are three pre-defined policy implementations, namely ACCEPT_ALL, ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER.
- CookieStore – A CookieStore is an interface that describes a storage space for cookies. CookieManager combines the cookies to the CookieStore for each HTTP response and recovers cookies from the CookieStore for each HTTP request.
- FileNameMap – The FileNameMap interface is an uncomplicated interface that implements a tool to outline a file name and a MIME type string. FileNameMap charges a filename map ( known as a mimetable) from a data file.
- SocketOption – The SocketOption interface helps the users to control the behavior of sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions allows the user to set various standard options.
- SocketImplFactory – The SocketImplFactory interface defines a factory for SocketImpl instances. It is used by the socket class to create socket implementations that implement various policies.
- ProtocolFamily – This interface represents a family of communication protocols. The ProtocolFamily interface contains a method known as name(), which returns the name of the protocol family.
Socket Programming
Java Socket programming is practiced for communication between the applications working on different JRE. Sockets implement the communication tool between two computers using TCP. Java Socket programming can either be connection-oriented or connection-less. In Socket Programming, Socket and ServerSocket classes are managed for connection-oriented socket programming. However, DatagramSocket and DatagramPacket classes are utilized for connection-less socket programming.
A client application generates a socket on its end of the communication and strives to combine that socket with a server. When the connection is established, the server generates an object of socket class on its communication end. The client and the server can now communicate by writing to and reading from the socket.
The java.net.Socket class describes a socket, and the java.net.ServerSocket class implements a tool for the server program to host clients and build connections with them.
Steps to establishing a TCP connection between two computing devices using Socket Programming
The following are the steps that occur on establishing a TCP connection between two computers using socket programming are given as follows:
Step 1 – The server instantiates a ServerSocket object, indicating at which port number communication will occur.
Step 2 – After instantiating the ServerSocket object, the server requests the accept() method of the ServerSocket class. This program pauses until a client connects to the server on the given port.
Step 3 – After the server is idling, a client instantiates an object of Socket class, defining the server name and the port number to connect to.
Step 4 – After the above step, the constructor of the Socket class strives to connect the client to the designated server and the port number. If communication is authenticated, the client forthwith has a Socket object proficient in interacting with the server.
Step 5 – On the server-side, the accept() method returns a reference to a new socket on the server connected to the client’s socket.
After the connections are stabilized, communication can happen using I/O streams. Each object of a socket class has both an OutputStream and an InputStream. The client’s OutputStream is correlated to the server’s InputStream, and the client’s InputStream is combined with the server’s OutputStream. Transmission Control Protocol (TCP) is a two-way communication protocol. Hence information can be transmitted over both streams at the corresponding time.
Socket Class
The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object created using java.net.Socket class has been correlated specifically with 1 remote host. If a user wants to connect to another host, then he must build a new socket object.
Methods of Socket Class
In Socket programming, both the client and the server have a Socket object, so all the methods under the Socket class can be invoked by both the client and the server. There are many methods in the Socket class.
S No. |
Method
|
Description
|
1 |
public void connect(SocketAddress host, int timeout) |
This method is used to connect the socket to the particularized host. This method is required only when the user instantiates the Socket applying the no-argument constructor. |
2 |
public int getPort() |
This method is used to return the port to which the socket is pinned on the remote machine. |
3 |
public InetAddress getInetAddress() |
This method is used to return the location of the other computer to which the socket is connected. |
4 |
public int getLocalPort() |
This method is used to return the port to which the socket is joined on the local machine. |
5 |
public SocketAddress getRemoteSocketAddress() |
This method returns the location of the remote socket. |
6 |
public InputStream getInputStream() |
This method is used to return the input stream of the socket. This input stream is combined with the output stream of the remote socket. |
7 |
public OutputStream getOutputStream() |
This method is used to return the output stream of the socket. The output stream is combined with the input stream of the remote socket. |
8 |
public void close() |
This method is used to close the socket, which causes the object of the Socket class to no longer be able to connect again to any server. |
ServerSocket Class
The ServerSocket class is used for providing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used.
Methods of ServerSocket Class:
There are many methods in the ServerSocket class which are very useful for the users. These methods are:
S no. |
Method
|
Description
|
1 |
public int getLocalPort() |
This method is used to return the port that the server socket is monitoring on. This method is beneficial if a user passed 0 as the port number in a constructor and lets the server find a port for him. |
2 |
public void setSoTimeout(int timeout) |
This method is used to set the time-out value for the time in which the server socket pauses for a client during the accept() method. |
3 |
public Socket accept() |
This method waits for an incoming client. This method is blocked till either a client combines to the server on the specified port or the socket times out, considering that the time-out value has been set using the setSoTimeout() method. Otherwise, this method will be blocked indefinitely. |
4 |
public void bind(SocketAddress host, int backlog) |
This method is used to bind the socket to the particularized server and port in the object of SocketAddress. The user should use this method if he has instantiated the ServerSocket using the no-argument constructor. |
Example of Socket Programming in Java:
The below example illustrates a pretty basic one-way Client and Server setup where a Client connects, sends messages to the server and the server shows them using a socket connection.
Client-Side Java Implementation:
Java
import java.io.*;
import java.net.*;
public class clientSide {
private Socket socket = null ;
private DataInputStream input = null ;
private DataOutputStream out = null ;
public clientSide(String address, int port)
{
try {
socket = new Socket(address, port);
System.out.println( "Connected" );
input = new DataInputStream(System.in);
out = new DataOutputStream(
socket.getOutputStream());
}
catch (UnknownHostException u) {
System.out.println(u);
}
catch (IOException i) {
System.out.println(i);
}
String line = "" ;
while (!line.equals( "End" )) {
try {
line = input.readLine();
out.writeUTF(line);
}
catch (IOException i) {
System.out.println(i);
}
}
try {
input.close();
out.close();
socket.close();
}
catch (IOException i) {
System.out.println(i);
}
}
public static void main(String[] args)
{
clientSide client
= new clientSide( "127.0.0.1" , 5000 );
}
}
|
Server Side Java Implementation:
Java
import java.io.*;
import java.net.*;
public class serverSide {
private Socket socket = null ;
private ServerSocket server = null ;
private DataInputStream in = null ;
public serverSide( int port)
{
try {
server = new ServerSocket(port);
System.out.println( "Server started" );
System.out.println( "Waiting for a client ..." );
socket = server.accept();
System.out.println( "Client accepted" );
in = new DataInputStream(
new BufferedInputStream(
socket.getInputStream()));
String line = "" ;
while (!line.equals( "End" )) {
try {
line = in.readUTF();
System.out.println(line);
}
catch (IOException i) {
System.out.println(i);
}
}
System.out.println( "Closing connection" );
socket.close();
in.close();
}
catch (IOException i) {
System.out.println(i);
}
}
public static void main(String[] args)
{
serverSide server = new serverSide( 5000 );
}
}
|
To run on Terminal or Command Prompt
Open two windows one for Server and another for Client.
1. First run the Server application. It will show –
Server started
Waiting for a client …
2. Then run the Client application on another terminal. It will show:
Connected
and the server accepts the client and shows,
Client accepted
3. Then you can start typing messages in the Client window. Here is the sample video of the output.
InetAddress
The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by 32-bit or 128-bit unsigned number. An object of InetAddress describes the IP address with its analogous hostname. InetAddress can control both IPv4 and IPv6 addresses.
There are two different types of addresses:
- Unicast – It is an identifier for a single interface.
- Multicast – It is an identifier for a collection of interfaces.
Methods of InetAddress Class
Java InetAddress class represents an IP address. The following given are the important methods of the InetAddress class –
S No. |
Method
|
Description
|
1 |
static InetAddress getByAddress(byte[] addr) |
This method is used to return an object of the InetAddress class provided the raw IP address. |
2 |
static InetAddress getByAddress(String host, byte[] addr) |
This method is used to create an InetAddress based on the given hostname and IP address. |
3 |
static InetAddress getByName(String host) |
This method is used to determine the IP address of a host when the host’s name is given. |
4 |
static InetAddress InetAddress getLocalHost() |
This method is used to return the localhost. |
5 |
String getHostName() |
This method is used to get the name of the IP address. |
6 |
String getHostAddress() |
This method returns the IP address in the form of a string in a textual display. |
7 |
String toString() |
This method is used to convert the IP address to a string. |
Examples of Inet Address Class Methods:
The Java implementation of the Inet Address class to illustrate the usage of methods is shown below:
Example 1:
Java
import java.net.*;
public class InetAddressExample1 {
public static void main(String[] args) throws UnknownHostException{
InetAddress address = InetAddress.getLocalHost();
System.out.println( "InetAddress of the Local Host : " +address);
String hostName=address.getHostName();
System.out.println( "\nHost name of the Local Host : " +hostName);
}
}
|
Output
InetAddress of the Local Host : localhost/127.0.0.1
Host name of the Local Host : localhost
Example 2:
Java
import java.net.*;
public class InetAddressExample2 {
public static void main(String[] args)
throws UnknownHostException
{
InetAddress address1 = InetAddress.getByName(
"write.geeksforgeeks.org" );
System.out.println( "Inet Address of named hosts : "
+ address1);
InetAddress arr[] = InetAddress.getAllByName(
"www.geeksforgeeks.org" );
System.out.println( "\nInet Address of ALL named hosts :" );
for ( int i = 0 ; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
|
Output

URL Class
The URL class in Java is the entry point to any available sources on the internet. A Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide Web. A source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to a database or a search engine. URL is a string of text that recognizes all the sources on the Internet, showing us the address of the source, how to interact with it, and recover something from it.

Components of a URL
A URL can have many forms. The most general however follows a three-components system-
- Protocol – The protocol in a URL defines how information is transported among the host and a client (or web browser).
- Hostname – The hostname is the name of the device on which the resource exists.
- File Name – The filename is the pathname to the file on the device.
- Port Number – The port number is used to identify different applications uniquely. It is typically optional.
Methods of Java URL Class
There are many methods in Java URL Class that are commonly used in Java Networking. These methods are:
S. No. |
Methods |
Description |
1 |
public String getProtocol() |
This method returns the protocol that is used by the URL. |
2 |
public String getHost() |
This method returns the hostname of the URL in IPv6 composition. |
3 |
public int getPort() |
This method returns the port associated with the protocol specified by the URL. |
4 |
public String getFile() |
This method returns the filename. |
5 |
public String getPath() |
This method returns the path of the URL, or null if empty. |
6 |
public String toString() |
This method is used to return the string representation of the provided URL object. |
7 |
public int getDefaultPort() |
This method returns the default port used. |
Examples of URL Class Methods
The Java implementation of the URL class to illustrate the usage of methods is shown below
Example 1:
Java
import java.net.*;
public class URLclassExample1 {
public static void main(String[] args)
throws MalformedURLException
{
URL url = new URL(
String s = url.toString();
System.out.println( "URL :" + s);
}
}
|
Output
URL :https://write.geeksforgeeks.org/post/3038131
Example 2:
Java
import java.net.*;
public class URLclassExample2 {
public static void main(String[] args)
throws MalformedURLException
{
URL url = new URL(
String protocol = url.getProtocol();
System.out.println( "Protocol : " + protocol);
String host = url.getHost();
System.out.println( "HostName : " + host);
String fileName = url.getFile();
System.out.println( "File Name : " + fileName);
}
}
|
Output
Protocol : https
HostName : write.geeksforgeeks.org
File Name : /post/3038131
Example 3:
Java
import java.net.*;
public class URLclassExample3 {
public static void main(String[] args)
throws MalformedURLException
{
URL url = new URL(
int defaultPort = url.getDefaultPort();
System.out.println( "Default Port : " + defaultPort);
String path = url.getPath();
System.out.println( "Path : " + path);
}
}
|
Output
Default Port : 443
Path : /post/3038131
This was a brief introduction to Java Networking. In this article, many important topics like Introduction of Java Networking, Common Network Protocols, Java Network Terminology, Java Networking Classes, Java Networking Interfaces, Socket Programming, Inet Address, and URL Class were covered.
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, televisions, etc. Originally, C++ was considered to be used in the project, but the idea was rejected for se
6 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 article will guide you on how to write, compile, and run your first Java program. With the help of Java, we can develop web and mobile applicat
6 min read
Java Identifiers
An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names used to identify programming elements. Every Java Variable must be identified with a unique name. Example: public class Test{ public static void main(String[] args) { int a =
2 min read
Java Keywords
In Java, keywords are the reserved words that have some predefined meanings and are used by the Java compiler for some internal process or represent some predefined actions. These words cannot be used as identifiers such as variable names, method names, class names, or object names. Now, let us go t
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
15 min read
Java Variables
In Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated. Key Components of Variables in Java: A variable in Java has three components, which are listed below: Data Type: Defines the k
9 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. These operators are essential in programming as they allow you to manipulate data efficiently. They can be classified into different categories based on their functionality. In this article, we will explore different
15 min read
Java User Input - Scanner Class
The most common way to take user input in Java is using the Scanner class. It is a part of java.util package. The scanner class can handle input from different places, like as we are typing at the console, reading from a file, or working with data streams. This class was introduced in Java 5. Before
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. Now let's go through a simple Java for l
5 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: Using a for-each l
8 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 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 linear data structure, which is used to store multiple values of the same data type. In array each element has a unique index value, which makes it easy to access individual elements. We first need to declare the size of an array because the size of the array is fixed in Java.
6 min read
Java Multi-Dimensional Arrays
Multidimensional arrays are used to store the data in rows and columns, where each row can represent another individual array are multidimensional array. It is also known as array of arrays. The multidimensional array has more than one dimension, where each row is stored in the heap independently. T
10 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 an Object class. The methods of this class can be used by the class name itself. Th
15 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, a String is the type of object that can store a 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, allowi
10 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
The StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters. Features of StringBuffer ClassThe key features of StringBuffer
11 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
In Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
10 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 details or features to the user. It allows to focus on what an object does rather than how it does it. The unnecessary details are not displayed to the user. Key features of abstraction: Abstractio
10 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 one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Method Overloading in Java
In Java, Method Overloading allows us to define multiple methods with the same name but different parameters within a class. This difference can be in the number of parameters, the types of parameters, or the order of those parameters. Method overloading in Java is also known as Compile-time Polymor
10 min read
Overriding in Java
Overriding in Java occurs when a subclass or child class implements a method that is already defined in the superclass or base class. When a subclass provides its own version of a method that is already defined in its superclass, we call it method overriding. The subclass method must match the paren
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
9 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
The Comparator interface in Java is used to sort the objects of user-defined classes. The Comparator interface is present in java.util package. This interface allows us to define custom comparison logic outside of the class for which instances we want to sort. The comparator interface is useful when
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 the java.util package. It is used to store the ordered collections of elements. In a Java List, we can organize and manage the data sequentially. Key Features: Maintained the order of elements in which they are added.Allows
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 in Java implements a growable array of objects. Vectors were legacy classes, but now it is fully compatible with collections. It comes under java.util package and implement the List interface. Key Features of Vector: It expands as elements are added.Vector class is synchronized in n
12 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
The Java Collection framework provides a Stack class, which implements a Stack data structure. The class is based on the basic principle of LIFO (last-in-first-out). Besides the basic push and pop operations, the class also provides three more functions, such as empty, search, and peek. The Stack cl
12 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 duplicat
14 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 a part of java.util package and extends the Collection interface. It stores and processes the data in order means elements are inserted at the end and removed from the front. Key Features: Most implementations, like PriorityQueue, do not allow null elements.Implementation Clas
12 min read
PriorityQueue in Java
The PriorityQueue class in Java is part of the java.util package. It implements a priority heap-based queue that processes elements based on their priority rather than the FIFO (First-In-First-Out) concept of a Queue. Key Points: The PriorityQueue is based on the Priority Heap. The elements of the p
9 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, the Map Interface is part of the java.util package and represents a mapping between a key and a value. The Java Map interface is not a subtype of the Collections interface. So, it behaves differently from the rest of the collection types. Key Features: No Duplicates in Keys: Keys should be
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
The Comparator interface in Java is used to sort the objects of user-defined classes. The Comparator interface is present in java.util package. This interface allows us to define custom comparison logic outside of the class for which instances we want to sort. The comparator interface is useful when
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