Building A Blockchain In Java: A Beginner’s Guide

Building a simple blockchain in Java is a great way to learn how it works. A blockchain is a sequence of blocks linked with cryptographic hashes. In Java, you can create a Block class with data, hash, previousHash, and timestamp. Use SHA-256 to generate each block’s hash based on its content and the previous hash. For example: new Block("Second Block", previousHash). Validate each block to ensure the chain’s integrity.This project shows how secure, tamper-proof chains are built using basic Java.

Go Back
Blog Thumbnail

🕒 12:28 PM

📅 May 24, 2025

✍️ By ChessTica542319

Blockchain is one of the most revolutionary technologies of the 21st century. Originally designed as the underlying system for Bitcoin, its applications have grown to include supply chain tracking, voting systems, and secure record-keeping. In simple terms, a blockchain is a chain of blocks that hold data and are secured using cryptographic principles.

In this article, we’ll walk through the key concepts of blockchain and demonstrate how to build a basic blockchain using the Java programming language.

What Is a Blockchain?

A blockchain is a distributed and immutable digital ledger. Each entry in the ledger is grouped into a block, and each block is linked to the one before it using a cryptographic hash. This structure makes the blockchain resistant to tampering.

Each block typically contains:

Data: The content or transaction information.


Hash: A unique digital fingerprint of the block.

Previous Hash: The hash of the previous block, linking the two blocks.

Timestamp: The time the block was created.

Together, these components ensure that each block is securely connected to the previous one. If even a small change is made to one block, its hash changes, breaking the link to the next block and exposing the alteration.

Core Concepts
1. Hashing
A hash function takes data and produces a fixed-size string (hash) that represents it. We’ll use SHA-256, a secure hashing algorithm. Hashes are unique; even a tiny change in the input will drastically change the output.

2. Chaining
Blocks are linked by storing the hash of the previous block inside each new block. This creates a secure, unbreakable chain from the first block (called the Genesis Block) to the last.

3. Immutability
Because each block depends on the hash of the previous one, tampering with any block breaks the chain. This makes blockchain ideal for recording data that must remain unchanged over time.

4. Validation
A blockchain is considered valid when:

Each block’s hash matches its calculated hash.

Each block’s previousHash matches the hash of the previous block.

Implementation 

Let’s create a simple blockchain in Java. We'll start by defining a Block class and then build a chain using a list.

Step 1: The Block Class

import java.util.Date;

import java.security.MessageDigest;


public class Block {

    public String hash;

    public String previousHash;

    public String data;

    private long timeStamp;


    public Block(String data, String previousHash) {

        this.data = data;

        this.previousHash = previousHash;

        this.timeStamp = new Date().getTime();

        this.hash = calculateHash();

    }


    public String calculateHash() {

        String input = previousHash + Long.toString(timeStamp) + data;

        return applySha256(input);

    }


    public static String applySha256(String input){

        try {

            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            byte[] hashBytes = digest.digest(input.getBytes("UTF-8"));

            StringBuilder hexString = new StringBuilder();

            for (byte b : hashBytes) {

                String hex = Integer.toHexString(0xff & b);

                if (hex.length() == 1) hexString.append('0');

                hexString.append(hex);

            }

            return hexString.toString();

        } catch(Exception e) {

            throw new RuntimeException(e);

        }

    }

}

Step 2: Create the Blockchain

import java.util.ArrayList;


public class Blockchain {

    public static ArrayList<Block> blockchain = new ArrayList<>();


    public static void main(String[] args) {

        blockchain.add(new Block("Genesis Block", "0"));

        blockchain.add(new Block("Second Block", blockchain.get(0).hash));

        blockchain.add(new Block("Third Block", blockchain.get(1).hash));


        for (Block block : blockchain) {

            System.out.println("Data: " + block.data);

            System.out.println("Hash: " + block.hash);

            System.out.println("Previous Hash: " + block.previousHash);

            System.out.println("-----------------------");

        }


        System.out.println("Blockchain is valid: " + isChainValid());

    }


    public static boolean isChainValid() {

        for (int i = 1; i < blockchain.size(); i++) {

            Block current = blockchain.get(i);

            Block previous = blockchain.get(i - 1);


            if (!current.hash.equals(current.calculateHash())) return false;

            if (!current.previousHash.equals(previous.hash)) return false;

        }

        return true;

    }

}

By running this program, you learn the fundamentals of:

Creating and linking data blocks.

Generating and comparing SHA-256 hashes.

Validating the integrity of data using cryptographic principles.

If you manually change a block's data and rerun the program, the validation check will fail—demonstrating blockchain’s resistance to tampering.