Coders Packet

Graph Data Structure using Java

By Dendi Keerthi

This is a simple Java-based directed Graph Data Structure. It can be used in Google Maps for routes, network connections like LAN, and other network-based connections.

Implementation of Graph Data Structure

A graph is a non-linear data structure which has nodes and edges. Nodes are also referred to as vertices and the edges are the lines that connect two nodes. Graphs are used to represent networks such as telephone network, circuit network, social network etc. Here, we will learn how to create and implement a graph data structure.

-> In this, first, we create a main class called Graphstruct and initialize the code.

-> Create an inner class named Edge and declare two variables in the inner class named src and destn and close the inner class.

-> Initialize two integers named vertices and edges.

-> Create an array Edge[] to store all the edges and then initialize the edge array. Each element of the edge array is an object of Edge type.

-> In the main method, create an object of Graphstruct class.

-> Create a graph by declaring the number of vertices and edges and then print the graph.


The following code gives the complete idea for implementing graph data structure using Java.

class Graphstruct {

class Edge {
int src, destn;

int vertices, edges;

Edge[] edge;

Graphstruct(int vertices, int edges) {
this.vertices = vertices;
this.edges = edges;

edge = new Edge[edges];
for(int i = 0; i < edges; i++) {

edge[i] = new Edge();

public static void main(String[] args) {

int noVertices = 5;
int noEdges = 8;

Graphstruct g = new Graphstruct(noVertices, noEdges);

g.edge[0].src = 1;
g.edge[0].destn = 2;

g.edge[1].src = 1;
g.edge[1].destn = 3;

g.edge[2].src = 1;
g.edge[2].destn = 4;

g.edge[3].src = 2;
g.edge[3].destn = 4;

g.edge[4].src = 2;
g.edge[4].destn = 5;

g.edge[5].src = 3;
g.edge[5].destn = 4;

g.edge[6].src = 3;
g.edge[6].destn = 5;

g.edge[7].src = 4;
g.edge[7].destn = 5;

for(int i = 0; i < noEdges; i++) {
System.out.println(g.edge[i].src + " --> " + g.edge[i].destn);






The output shows the different vertices that are connected through edges. Here we have taken 5 vertices and 8 edges.

Here, src is the source vertice and destn is the destination vertice.

noVertices represents the number of vertices and noEdges represents the number of edges.

For loop is used twice to specify the conditions about the edges. 

Similarly, we can change the number of vertices and edges accordingly to obtain the graph of our choice.

This is the process of creating a Graph Data Structure using Java. 


Thank You


Download Complete Code


No comments yet