Skip to content
Related Articles

Related Articles

Improve Article

Implementation of Blockchain in Java

  • Last Updated : 12 Aug, 2021

Blockchain is the backbone Technology of Digital CryptoCurrency BitCoin.

  • A Blockchain is a list of records called blocks that are linked together using linked lists and use the cryptographic technique.
  • Each block contains its own digital fingerprint called Hash, the hash of the previous block, a timestamp and the data of the transaction made, making it more secure towards any kind of data breach.
  • Therefore, if the data of one block is changed then its hash will also change. If the hash is changed, then its hash will be different from the next block that contains the hash of the previous block affecting all the hashes of the blocks after it. Changing of the hashes and then comparing it with other blocks allows us to check the blockchain.

Implementation of the Blockchain: The following are the functions used in the implementation of the blockchain.

  1. Creating Blocks: To create a block, a Block class is implemented. In the class Block:
    • hash will contain the hash of the block and
    • previousHash will contain the hash of the previous block.
    • String data is used to store the data of the block and
    • “long timeStamp” is used to store the timestamp of the block. Here long data type is used to store the number of milliseconds.
    • calculateHash() to generate the hash

    Below is the implementation of the class block:


    // Java implementation for creating
    // a block in a Blockchain
    import java.util.Date;
    public class Block {
        // Every block contains
        // a hash, previous hash and
        // data of the transaction made
        public String hash;
        public String previousHash;
        private String data;
        private long timeStamp;
        // Constructor for the block
        public Block(String data,
                     String previousHash)
   = data;
                = previousHash;
                = new Date().getTime();
                = calculateHash();
        // Function to calculate the hash
        public String calculateHash()
            // Calling the "crypt" class
            // to calculate the hash
            // by using the previous hash,
            // timestamp and the data
            String calculatedhash
                = crypt.sha256(
                    + Long.toString(timeStamp)
                    + data);
            return calculatedhash;
  2. Generating Hashes: To generate hash, SHA256 algorithm is used.

    Below is the implementation of the algorithm.


    // Java program for Generating Hashes
    public class crypt {
        // Function that takes the string input
        // and returns the hashed string.
        public static String sha256(String input)
            try {
                MessageDigest sha
                    = MessageDigest
                int i = 0;
                byte[] hash
                    = sha.digest(
                // hexHash will contain
                // the Hexadecimal hash
                StringBuffer hexHash
                    = new StringBuffer();
                while (i < hash.length) {
                    String hex
                        = Integer.toHexString(
                            0xff & hash[i]);
                    if (hex.length() == 1)
                return hexHash.toString();
            catch (Exception e) {
                throw new RuntimeException(e);
  3. Storing the blocks: Now, let us store the blocks in the ArrayList of Block type, along with their hash values by calling the constructor of the Block Class.


    // Java implementation to store
    // blocks in an ArrayList
    import java.util.ArrayList;
    public class GFG {
        // ArrayList to store the blocks
        public static ArrayList<Block> blockchain
            = new ArrayList<Block>();
        // Driver code
        public static void main(String[] args)
            // Adding the data to the ArrayList
            blockchain.add(new Block(
                "First block", "0"));
            blockchain.add(new Block(
                "Second block",
                    .get(blockchain.size() - 1)
            blockchain.add(new Block(
                "Third block",
                    .get(blockchain.size() - 1)
            blockchain.add(new Block(
                "Fourth block",
                    .get(blockchain.size() - 1)
            blockchain.add(new Block(
                "Fifth block",
                    .get(blockchain.size() - 1)
  4. Blockchain Validity: Finally, we need to check the validity of the BlockChain by creating a boolean method to check the validity. This method will be implemented in the “Main” class and checks whether the hash is equal to the calculated hash or not. If all the hashes are equal to the calculated hashes, then the block is valid.

    Below is the implementation of the validity:


    // Java implementation to check
    // validity of the blockchain
    // Function to check
    // validity of the blockchain
    public static Boolean isChainValid()
        Block currentBlock;
        Block previousBlock;
        // Iterating through
        // all the blocks
        for (int i = 1;
             i < blockchain.size();
             i++) {
            // Storing the current block
            // and the previous block
            currentBlock = blockchain.get(i);
            previousBlock = blockchain.get(i - 1);
            // Checking if the current hash
            // is equal to the
            // calculated hash or not
            if (!currentBlock.hash
                             .calculateHash())) {
                    "Hashes are not equal");
                return false;
            // Checking of the previous hash
            // is equal to the calculated
            // previous hash or not
            if (!previousBlock
                             .previousHash)) {
                    "Previous Hashes are not equal");
                return false;
        // If all the hashes are equal
        // to the calculated hashes,
        // then the blockchain is valid
        return true;

Advantages of the Blockchain:

  1. Blokchain is a distributed network of systems. Therefore, data breaches are very difficult to be carried out.
  2. Since, Blockchain generated hashes of each block, therefore, it is very difficult to carry out malicious attacks.
  3. Data Tampering will change the hash of each block which will make the blockchain invalid

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up
Recommended Articles
Page :