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
// A Java program for a ClientSide
import java.io.*;
import java.net.*;
public class clientSide {
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public clientSide(String address, int port)
{
// establish a connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(
socket.getOutputStream());
}
catch (UnknownHostException u) {
System.out.println(u);
}
catch (IOException i) {
System.out.println(i);
}
// string to read message from input
String line = "";
// keep reading until "End" is input
while (!line.equals("End")) {
try {
line = input.readLine();
out.writeUTF(line);
}
catch (IOException i) {
System.out.println(i);
}
}
// close the connection
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
// A Java program for a serverSide
import java.io.*;
import java.net.*;
public class serverSide {
// initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public serverSide(int port)
{
// starts server and waits for a connection
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");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(
socket.getInputStream()));
String line = "";
// reads message from client until "End" is sent
while (!line.equals("End")) {
try {
line = in.readUTF();
System.out.println(line);
}
catch (IOException i) {
System.out.println(i);
}
}
System.out.println("Closing connection");
// close 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{
// To get and print InetAddress of the Local Host
InetAddress address = InetAddress.getLocalHost();
System.out.println("InetAddress of the Local Host : "+address);
// To get and print host name of the Local Host
String hostName=address.getHostName();
System.out.println("\nHost name of the Local Host : "+hostName);
}
}
OutputInetAddress 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
{
// To get and print InetAddress of Named Hosts
InetAddress address1 = InetAddress.getByName(
"write.geeksforgeeks.org");
System.out.println("Inet Address of named hosts : "
+ address1);
// To get and print ALL InetAddress of Named Host
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
{
// creates a URL with string representation.
URL url = new URL(
"https://write.geeksforgeeks.org/post/3038131");
// print the string representation of the URL
String s = url.toString();
System.out.println("URL :" + s);
}
}
OutputURL :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(
"https://write.geeksforgeeks.org/post/3038131");
// to get and print the protocol of the URL
String protocol = url.getProtocol();
System.out.println("Protocol : " + protocol);
// to get and print the hostName of the URL
String host = url.getHost();
System.out.println("HostName : " + host);
// to get and print the file name of the URL
String fileName = url.getFile();
System.out.println("File Name : " + fileName);
}
}
OutputProtocol : 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(
"https://write.geeksforgeeks.org/post/3038131");
// to get and print the default port of the URL
int defaultPort = url.getDefaultPort();
System.out.println("Default Port : " + defaultPort);
// to get and print the path of the URL
String path = url.getPath();
System.out.println("Path : " + path);
}
}
OutputDefault 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 web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Basics
Introduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 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 Ins
5 min read
Differences Between JDK, JRE and JVMUnderstanding 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 develo
3 min read
Java IdentifiersAn 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
2 min read
Java KeywordsIn 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 VariablesIn 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 kind
9 min read
Java OperatorsJava 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
Decision Making in Java (if, if-else, switch, break, continue, jump)Decision-making statements in Java execute a block of code based on a condition. Decision-making in programming is similar to decision-making in real life. In programming, we also face situations where we want a certain block of code to be executed when some condition is fulfilled.A programming lang
10 min read
Java LoopsLooping in programming languages is a feature that facilitates the execution of a set of instructions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition
7 min read
Java MethodsJava 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: Java program to demonstrate how to crea
8 min read
How to Call a Method in Java?In Java, calling a method helps us to reuse code and helps everything be organized. Java methods are just a block of code that does a specific task and gives us the result back. In this article, we are going to learn how to call different types of methods in Java with simple examples.What is a Metho
3 min read
Static Method vs Instance Method in JavaIn Java, methods are mainly divided into two parts based on how they are connected to a class, which are the static method and the Instance method. The main difference between static and instance methods is listed below:Static method: A static method is a part of the class and can be called without
4 min read
Access Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. Understanding de
7 min read
Command Line Arguments in JavaJava 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 comman
3 min read
Variable Arguments (Varargs) in JavaIn Java, Variable Arguments (Varargs) write methods that can take any number of inputs, which simply means we do not have to create more methods for different numbers of parameters. This concept was introduced in Java 5 to make coding easier. Instead of passing arrays or multiple methods, we can sim
5 min read
Arrays in JavaArrays 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 Declare and Initialize an Array in Java?An array in Java is a linear data structure that is used to store multiple values of the same data type. In an 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
5 min read
Java Multi-Dimensional ArraysMultidimensional 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 JavaIn Java, a Jagged array is an array that holds other arrays. When we work with a jagged array, one thing to keep in mind is that the inner array can be of different lengths. It is like a 2D array, but each row can have a different number of elements.Example:arr [][]= { {10,20}, {30,40,50,60},{70,80,
6 min read
Arrays Class in JavaThe 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.The
15 min read
Final Arrays in JavaIn Java, final is a keyword that is used to make a variable constant. Once we declare a variable as final, its value can not be changed throughout the program. But when we use final with an array, it is a bit different thing. Final applies to the reference, not the contents. This means we cannot rea
4 min read
Java StringsIn 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
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 are going to learn why strings are immutable in Java and how this benefits Java applications.What Does Immutable Mean?When we
4 min read
Java String concat() Method with ExamplesThe 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 Jav
4 min read
String Class in JavaA 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 are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl
7 min read
StringBuffer Class in JavaThe 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 c
11 min read
Java StringBuilder ClassIn 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 = new
7 min read
String vs StringBuilder vs StringBuffer in JavaA string is a sequence of characters. In Java, String objects are immutable, which simply means once created, their values can not be changed. In Java, String, StringBuilder, and StringBuffer are used for handling strings. The main difference is:String: Immutable, meaning its value cannot be changed
6 min read
Regular Expressions in JavaIn Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressi
7 min read
Java Pattern pattern() Methodpattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method is used to get the same source expression. Example 1: Using the pattern() method to check the regex pattern
2 min read
Java Matcher pattern() MethodThe pattern() method of the Matcher class is used to get the pattern to be matched by this matcher.Example 1: The below example demonstrates how the pattern() method retrieves the regex pattern "G.*s$" used to match a string ending with "s" and starting with "G".Java// Java code to illustrate patter
2 min read
java.lang.Character Class Methods | Set 1java.lang.Character Class wraps the value of a primitive data type char to an object of datatype Character. This object contains a single field having the data type char. This class provides several methods regarding character manipulations like converting them from lowercase to uppercase. Character
6 min read
Java QuantifiersQuantifiers in Java allow users to specify the number of occurrences to match against. These are used with regular expressions to specify the number of times a particular pattern or character can appear in the Input. Below are some commonly used quantifiers in Java.QuantifiersDescriptionX*Zero or mo
5 min read
OOPs & Interfaces
Java OOP(Object Oriented Programming) ConceptsJava 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 JavaIn 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
11 min read
Java ConstructorsIn 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 JavaObject 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
7 min read
Abstraction in JavaAbstraction 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:Abstraction
10 min read
Encapsulation in JavaIn Java, encapsulation is one of the coret concept of Object Oriented Programming (OOP) in which we bind the data members and methods into a single unit. Encapsulation is used to hide the implementation part and show the functionality for better readability and usability. The following are important
10 min read
Inheritance in JavaJava 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
13 min read
Polymorphism in JavaPolymorphism 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 JavaIn Java, Method Overloading allows us to define multiple methods with the same name but different parameters within a class. This difference may include:The number of parametersThe types of parametersThe order of parametersMethod overloading in Java is also known as Compile-time Polymorphism, Static
10 min read
Overriding in JavaOverriding 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 PackagesPackages in Java are a mechanism that encapsulates a group of classes, sub-packages, and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easie
8 min read
Java InterfaceAn 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
12 min read
Interfaces and Inheritance in JavaJava supports inheritance and interfaces, which are important concepts for building reusable code. A class can extend another class and can implement one and more than one Java interface. Note: This topic has a major influence on the concept of Java and Multiple Inheritance. Interface Implementation
7 min read
Java Class vs InterfacesIn 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 InterfacesA 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 JavaIn 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 declar
5 min read
Marker Interface in JavaIn Java, a marker Interface is an empty interface that has no fields or methods. It is used just to mark or tag a class to tell Java or other programs something special about that class. These interfaces do not have any methods inside but act as metadata to provide information about the class. Examp
4 min read
Java Comparator InterfaceThe 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
7 min read
Collections
Collections in JavaAny 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 JavaCollections class in Java is one of the utility classes in the Java Collections Framework. The java.util package contains the Collections class in Java. The Java Collections class is used with the static methods that operate on the collections or return the collection. All the methods of this class
13 min read
Collection Interface in JavaThe 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 InterfaceThe 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 JavaJava 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
9 min read
LinkedList in JavaLinked 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 an
12 min read
Set in JavaThe 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 HashSetHashSet 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 JavaTreeSet 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
Queue Interface In JavaThe 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 Class
11 min read
PriorityQueue in JavaThe 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 pri
9 min read
Deque Interface in JavaDeque 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/
9 min read
Map Interface in JavaIn 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 un
11 min read
HashMap in JavaIn 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 IteratorAn 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
6 min read
Java Comparator InterfaceThe 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
7 min read
Java Comparable InterfaceThe 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.Exam
4 min read
Exception Handling
Java Exception HandlingException 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 ExceptionsIn Java, an exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at run time, that 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
5 min read
Java Try Catch BlockA try-catch block in Java is a mechanism to handle exceptions. This make sure 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: Here, we are going to handle the Arithmet
4 min read
Java final, finally and finalizeIn Java, the final, finally, and finalize keywords play an important role in exception handling. The main difference between final, finally, and finalize is listed below:final: The final is the keyword that can be used for immutability and restrictions in variables, methods, and classes.finally: The
4 min read
throw and throws in JavaIn 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 keywords
5 min read
User-Defined Custom Exception in JavaIn Java, an Exception is an issue (run-time error) that occurs during the execution of a program. When an exception occurs, the program terminates abruptly, and the code beyond the exception never gets executed.Java provides us the facility to create our own exceptions by extending the Exception cla
3 min read
Chained Exceptions in JavaChained 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 f
3 min read
Null Pointer Exception in JavaA NullPointerException in Java is a RuntimeException. It occurs when a program attempts to use an object reference that has the null value. In Java, "null" is a special value that can be assigned to object references to indicate the absence of a value.Reasons for Null Pointer ExceptionA NullPointerE
5 min read
Exception Handling with Method Overriding in JavaIn 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 by using constructs like try
5 min read
Java Advanced
Java Multithreading TutorialThreads are the backbone of multithreading. We are living in the 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
15+ min read
Java ThreadsJava 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
11 min read
Java Thread ClassThread 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 to manage the behavior of threads b
5 min read
Java Runnable Interfacejava.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 to subclass a Thread when a task can be done by overriding only the run
3 min read
Lifecycle and States of a Thread in JavaA thread in Java can exist in any one of the following states at any given time. A thread lies only in one of the shown states at any instant:New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram below represents various states of a thread at any instant:Lif
5 min read
Main thread in JavaJava 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 MultithreadingJava being Object-Oriented works within a Multithreading environment in which the thread scheduler assigns the processor to a thread based on the priority of the thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creatin
5 min read
Java Naming a Thread and Fetching Name of Current ThreadA thread can be referred to as a lightweight process. Assigning descriptive names to threads enhances code readability and simplifies debugging. Now let us discuss the different ways to name a thread in Java.Methods to Set the Thread NameThere are two ways by which we can set the name either be it d
4 min read
Java Thread.start() vs Thread.run() MethodIn Java's multi-threading concept, start() and run() are the two most important methods. In this article, we will learn the main differences between Thread.start() and Thread.run() in Java. Thread.start() vs Thread.run() MethodThread.start()Thread.run()Creates a new thread and the run() method is ex
4 min read
Java Thread.sleep() MethodThread 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. The sleep() method is used to stop the execution of the current thread (whichever might be executing in the system) fo
3 min read
Java Daemon ThreadIn 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
5 min read
Java Thread Safety and How to Achieve it?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 JavaBackground 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
Synchronization in JavaIn multithreading, synchronization is important to make sure multiple threads safely work on shared resources. Without synchronization, data can become inconsistent or corrupted if multiple threads access and modify shared variables at the same time. In Java, it is a mechanism that ensures that only
10 min read
Importance of Thread Synchronization in JavaThread synchronization in Java is important for managing shared resources in a multithreaded environment. It ensures that only one thread can access a shared resource at a time, which enhances the overall system performance and prevents race conditions and data corruption.Why is Thread Synchronizati
8 min read
Java Method and Block SynchronizationIn Java, Synchronization is very important in concurrent programming when multiple threads need to access shared resources. Java Synchronization can be applied to methods and blocks. Method synchronization in Java locks the entire method and Block synchronization locks only a specific section of the
6 min read
Java Atomic vs Volatile vs SynchronizedIn Java, multithreading can lead to challenges related to thread safety and data consistency. Java provides concurrency mechanisms like Atomic, Volatile, and Synchronized to address these issues and ensure thread safety. These mechanisms offer unique advantages and limitations.Atomic vs Volatile vs
5 min read
Java Lock Framework vs Thread SynchronizationIn Java, thread synchronization is achieved using the Lock framework which is present in the java.util.concurrent package. Synchronization ensures that only one thread can access a resource at a time by preventing issues like data corruption or inconsistency. Java offers two primary mechanisms for a
4 min read
Deadlock in Java MultithreadingDeadlock occurs in Java when multiple threads block each other while waiting for locks held by one another. To prevent deadlocks, we can use the synchronized keyword to make methods or blocks thread-safe which means only one thread can have the lock of the synchronized method and use it, other threa
4 min read
Deadlock Prevention And AvoidanceDeadlock prevention and avoidance are strategies used in computer systems to ensure that different processes can run smoothly without getting stuck waiting for each other forever. Think of it like a traffic system where cars (processes) must move through intersections (resources) without getting int
5 min read
Difference Between Lock and Monitor in Java ConcurrencyJava Concurrency deals with concepts like Multithreading and other concurrent operations. To manage shared resources effectively, tools like Locks (Mutex) and Monitors are used to ensure thread synchronization and avoid race conditions. Locks represent a low-level synchronization mechanism and Monit
5 min read
ReentrantLock in JavaReentrantLock in Java is a part of the java.util.concurrent package that helps to achieve synchronization more effectively and optimally compared to the traditional Synchronized keyword. It offers features like,TimeoutsInterruptible locksMore control over Thread SchedulingThese features make it a va
6 min read
File Handling in JavaIn 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 to create 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 languag
6 min read
Java File ClassJava 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 FileThere are two standard methods to create a new file, either directly with the help of the File class or indirectly with the help of the FileOutputStream class by creating an object of the file in both approaches.Methods to Create Files in JavaThere are two methods mentioned belowUsing the File Class
4 min read
Different ways of Reading a text file in JavaThere are multiple ways of writing and reading a text file in Java. this is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.
6 min read
Java Program to Write into a FileFileWriter class in Java is used to write character-oriented data to a file as this class is character-oriented because it is used in file handling in Java. There are many ways to write into a file in Java as there are many classes and methods which can fulfill the goal as follows:Using writeString(
5 min read
Delete a File Using JavaJava provides methods to delete files programmatically. In contrast 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. Example: A basic program to delete the file from a static path.Jav
2 min read
Java FileReader ClassFileReader 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 methods
3 min read
Java FileWriter ClassJava FileWriter class of the java.io package is used to write data in character form to a file. The FileWriter class in Java 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 w
5 min read
Java FilePermission Classjava.io.FilePermission class represents access to a file or directory. These accesses are in the form of a path name and a set of actions associated with the path name(specifies which file to open along with the extension and the path).Example: In FilePermission("GEEKS.txt", "read") "GEEKS.txt" is t
3 min read
Java FileDescriptor Classjava.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 IO - Input/Output in Java with ExamplesJava provides 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. The image below demonstrates the flow of data from a source to
6 min read
Java Reader ClassReader 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
6 min read
Java Writer ClassJava writer class is an abstract class in the java.io package. It is designed for writing character streams. Writer class in Java provides methods for writing characters, arrays of characters, and strings. Since it is an abstract class, we cannot create an instance of it directly. Instead, we will u
5 min read
Java FileInputStream ClassFileInputStream class in Java is useful for reading data from a file in the form of a Java sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.Example: FileInputStream class to read data from fi
4 min read
FileOutputStream in JavaIn Java, the FileOutputStream class is a subclass of OutputStream. It is used to write data to a file as a stream of bytes. FileOutputStream is commonly employed for writing primitive values into a file. FileOutputStream supports writing both byte-oriented and character-oriented data.Note: FileWrite
7 min read
Ways to Read Input from Console in JavaIn Java, there are four different ways to read input from the user in the command line environment(console). 1. Using Buffered Reader ClassBuffered Reader Class is the classical method to take input, Introduced in JDK 1.0. This method is used by wrapping the System.in (standard input stream) in an I
5 min read
Java BufferedOutputStream ClassBufferedOutputStream 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 ClassJava 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:Scanner class provides parsing and input reading capabilities with built-in methods for different data types.BufferedReader cla
2 min read
Fast I/O in Java in Competitive ProgrammingIn competitive programming, fast input and output (I/O) are essential to avoid time limit exceeded (TLE) errors. Java can be slower for I/O tasks, but there are different ways to speed it up. Using methods like BufferedReader, Scanner, and custom input classes, we can improve the performance of our
6 min read
Java Lambda ExpressionsLambda expressions in Java, introduced in Java SE 8. It represents the instances of functional interfaces (interfaces with a single abstract method). They provide a concise way to express instances of single-method interfaces using a block of code.Key Functionalities of Lambda ExpressionLambda Expre
5 min read
Java Method ReferencesIn Java, a method is a collection of statements that perform some specific task and return the result to the caller. A method reference is the shorthand syntax for a lambda expression that contains just one method call. In general, one does not have to pass arguments to method references.Why Use Met
9 min read
Java 8 Stream TutorialJava 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme
15+ min read
Java 8 Features - Complete TutorialJava 8 is the most awaited release of the Java programming language development because, in the entire history of Java, it has never released that many major features. It consists of major features of Java. It is a new version of Java and was released by Oracle on 18 March 2014. Java provided suppor
9 min read
Java NetworkingWhen 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 ModelThe TCP/IP model (Transmission Control Protocol/Internet Protocol) is a four-layer networking framework that enables reliable communication between devices over interconnected networks. It provides a standardized set of protocols for transmitting data across interconnected networks, ensuring efficie
7 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 IPv6In 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 tw
9 min read
Difference Between Connection-oriented and Connection-less ServicesIn 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 JavaSocket 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 ClassServerSocket 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, ServerS
4 min read
Java URL ClassURL class in Java is a part of java.net package that makes it easy to work with Uniform Resource Locators (URLs). URL 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. This
4 min read
JDBC (Java Database Connectivity)JDBC is an API that helps applications to communicate with databases, it allows Java programs to connect to a database, run queries, retrieve, and manipulate data. Because of JDBC, Java applications can easily work with different relational databases like MySQL, Oracle, PostgreSQL, and more.JDBC Arc
5 min read
JDBC DriversJava Database Connectivity (JDBC) is an application programming interface (API) for the Java programming language that defines how a client can access and interact with any kind of tabular data, especially a relational database. JDBC Drivers uses JDBC APIs which was developed by Sun Microsystem, but
4 min read
Establishing JDBC Connection in JavaBefore Establishing a JDBC Connection in Java (the front end, i.e., your Java Program, and the back end, i.e., the database), we should learn what precisely a JDBC is and why it came into existence. Now, let us discuss what exactly JDBC stands for and why it is essential, and how to establish a data
7 min read
Types of Statements in JDBCIn Java, the Statement interface in JDBC (Java Database Connectivity) is used to create and execute SQL queries in Java applications. JDBC provides three types of statements to interact with the database:StatementPrepared StatementCallable Statement1. StatementA Statement object is used for general-
5 min read
Java Memory ManagementJava 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, memory management is handled by the Java Virtual Machine (JVM). The breakdown of how objects are stored in memory:All Java objects are dynamically stored in the heap memory.References to these objects are stored in the stack memory.Objects are created using the "new" keyword and are allocat
5 min read
Stack vs Heap Memory AllocationIn C, C++, and Java, memory can be allocated on either a stack or a heap. Stack allocation happens in the function call stack, where each function gets its own memory for variables. In C/C++, heap memory is controlled by programmer as there is no automatic garbage collection.Stack AllocationStack al
7 min read
Java Virtual Machine (JVM) Stack AreaThe 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.JVM Stack AreaIn Java, each thread has its own stack called the Run-Time Stack, created w
5 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 that takes Java bytecode and converts the bytecode (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 in
4 min read
Garbage Collection in JavaGarbage 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 are created, which is a portion of memory dedicated
7 min read
JVM Garbage CollectorsJVM Garbage Collectors are essential for Java memory management. It automatically frees up unused memory to prevent memory leaks and improve performance. Java manages memory through the Java Virtual Machine using a process called garbage collection. Garbage collection automatically frees up memory b
5 min read
Stack vs Heap Memory AllocationIn C, C++, and Java, memory can be allocated on either a stack or a heap. Stack allocation happens in the function call stack, where each function gets its own memory for variables. In C/C++, heap memory is controlled by programmer as there is no automatic garbage collection.Stack AllocationStack al
7 min read
Memory Leaks in JavaIn programming, a memory leak happens when a program keeps using memory but does not give it back when it's done. It simply means the program slowly uses more and more memory, which can make things slow and even stop working. Working of Memory Management in JavaJava has automatic garbage collection,
3 min read
Practice Java
Java Interview Questions and AnswersJava 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 QuestionsJava 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-t
3 min read
Java Programs - Java Programming ExamplesIn this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Exercises - Basic to Advanced Java Practice Programs with SolutionsLooking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers
7 min read
Java Quiz | Level Up Your Java SkillsThe best way to scale up your coding skills is by practicing the exercise. And if you are a Java programmer looking to test your Java skills and knowledge? Then, this Java quiz is designed to challenge your understanding of Java programming concepts and assess your excellence in the language. In thi
4 min read
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 excel
15+ min read
Number Guessing Game in JavaA number-guessing game in Java is a simple program where the computer randomly selects a number, and the user has to guess it within a limited number of attempts. The program provides feedback on whether the guessed number is too high or too low, guiding the user toward the correct answer.This proje
4 min read
Mini Banking Application in JavaIn 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 AWTSwing is a part of the JFC (Java Foundation Classes). Building a Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components that 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 JavaTic-Tac-Toe is a classic game that two people can enjoy together. It is played on a 3x3 grid where players take turns placing their marks, X or O, in empty spots. The main goal is to get three of the same marks in a row-horizontally, vertically, or diagonally.In this article, we are going to build a
7 min read
Design Snake GameLet 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 JavaThe Memory Game is a fun and simple two-player game that tests your memory. In this game, a set of cards is laid face down. Players take turns flipping two cards to find matching pairs. If the two cards match, they remain face up. If not, they are flipped back down. The game continues until all pair
5 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 DetectionPrerequisites: 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 SystemPURPOSE 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 editorTo 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