Program
Program
import java.util.Scanner;
This program demonstrates the structure of a simple blockchain with blocks linked
together.
import java.util.ArrayList;
import java.util.Date;
class Block {
public String hash;
public String previousHash;
private String data;
private long timeStamp;
Key Components:
1. Block Class:
○ Attributes:
■ hash: The current block's hash (unique identifier).
■ previousHash: The hash of the previous block in the chain.
■ data: The information stored in the block (in this case, it's a string,
but in real blockchains, it could be transactions).
■ timeStamp: The time at which the block was created.
○ Constructor:
■ Initializes the data, previousHash, and timeStamp when a block is
created.
■ Calls the calculateHash() method to generate a unique hash for
the block.
○ calculateHash():
■ Combines previousHash, timeStamp, and data to generate the
block's hash. It uses hashCode() to compute a hash, though in
actual blockchains, a more complex and secure hashing algorithm
like SHA-256 would be used.
2. SimpleBlockchain Class:
○ ArrayList<Block> blockchain:
■ A list to store all the blocks in the chain.
○ Main Method:
■ Creates three blocks.
■ Adds each block to the blockchain, where each block's
previousHash refers to the hash of the last block.
■ Prints out the hash and previousHash of each block in the chain.
Output Example: