Explore a comprehensive Project on Huffman coding algorithm in java. This GUI-based application uses Swing components to provide an intuitive interface for encoding and decoding text. Key features include priority queue management, frequency mapping, Huffman tree construction, and file I/O operations. Learn how to efficiently compress and decompress data with variable-length codes while working with Java’s graphical user interface elements such as JFrame
, JTextArea
, and JButton
.
Huffman Node Class
Represents a node in the Huffman tree.
Attributes:
int frequency
: The frequency of the character in the text.char character
: The character represented by this node.HuffmanNode left
: Pointer to the left child node.HuffmanNode right
: Pointer to the right child node.
Constructor:
HuffmanNode(char character, int frequency)
: Initializes a new node with a given character and frequency, and sets the left and right children tonull
.
NOTE
- Feel free to explore the code in my GitHub repository.
- Download the Zip File of Huffman coding algorithm in java
Huffman Comparator Class
Provides a way to compare HuffmanNode
objects based on their frequency.
Method:
public int compare(HuffmanNode x, HuffmanNode y)
: Compares two nodes by their frequency, allowing the priority queue to order nodes such that nodes with lower frequencies have higher priority.

Huffman Coding Class
Contains methods to build the Huffman tree, generate Huffman codes, and perform encoding and decoding.
Key Methods:
buildHuffmanTree(String data)
- Purpose: Constructs the Huffman tree from the input data.
- Functionality:
- Calculates character frequencies.
- Builds a priority queue of
HuffmanNode
instances. - Constructs the Huffman tree by merging nodes with the lowest frequencies.
- Generates Huffman codes for each character.
buildFrequencyMap(String data)
- Purpose: Creates a map of character frequencies.
- Functionality:
- Iterates over the input string and counts the occurrences of each character.
- Returns a map where the key is the character and the value is its frequency.
buildPriorityQueue(Map<Character, Integer> frequencyMap)
- Purpose: Builds a priority queue from the frequency map.
- Functionality:
- Creates a priority queue of
HuffmanNode
objects. - Adds nodes to the queue based on character frequencies.
- Creates a priority queue of
buildHuffmanTree(PriorityQueue<HuffmanNode> priorityQueue)
- Purpose: Constructs the Huffman tree using the priority queue.
- Functionality:
- Repeatedly removes two nodes with the lowest frequencies.
- Creates a new internal node with these two nodes as children.
- Adds the new node back into the priority queue.
- Returns the root of the Huffman tree.
generateHuffmanCodes(HuffmanNode root, String code, Map<Character, String> huffmanCodeMap)
- Purpose: Generates Huffman codes by traversing the Huffman tree.
- Functionality:
- Recursively traverses the tree.
- Assigns codes by appending ‘0’ for left edges and ‘1’ for right edges.
- Stores codes in the
huffmanCodeMap
.
encodeData(String data, Map<Character, String> huffmanCodeMap)
- Purpose: Encodes the input data into Huffman code.
- Functionality:
- Converts each character in the input data to its corresponding Huffman code.
- Constructs the encoded string.
decodeData(String encodedData, HuffmanNode root)
- Purpose: Decodes a Huffman-encoded string back to the original text.
- Functionality:
- Traverses the Huffman tree according to the bits in the encoded string.
- Collects characters when reaching leaf nodes.
- Constructs the decoded string.
encode(String data)
- Purpose: Encodes the input data.
- Functionality:
- Calls
buildHuffmanTree
to prepare the encoding map and tree. - Uses
encodeData
to return the encoded string.
- Calls
decode(String encodedData)
- Purpose: Decodes the Huffman-encoded string.
- Functionality:
- Uses
decodeData
to return the decoded string.
- Uses
Huffman Coding GUI Class
Creates the graphical user interface (GUI) for the application.
Key Components:
- Text Areas:
inputTextArea
: Area for user input text.encodedTextArea
: Displays the encoded result.decodedTextArea
: Shows the decoded output.
- Buttons:
encodeButton
: Initiates encoding of the text frominputTextArea
and displays the result inencodedTextArea
.decodeButton
: Initiates decoding of the text fromencodedTextArea
and displays the result indecodedTextArea
.loadFileButton
: Opens a file chooser to load text intoinputTextArea
.saveFileButton
: Opens a file chooser to save the encoded text fromencodedTextArea
.
- Status Label:
statusLabel
: Provides status updates, such as “Encoding completed” or “Error during encoding.”
How to Use the GUI
JFrame
: Main window for the application.JPanel
: Panels to organize layout, including text areas and buttons.BorderLayout
andGridLayout
: Layout managers to arrange components.
Action Listeners:
encodeButton
Action Listener: Reads text frominputTextArea
, encodes it usingHuffmanCoding.encode
, and displays it inencodedTextArea
. Updates the status label based on success or failure.decodeButton
Action Listener: Reads encoded text fromencodedTextArea
, decodes it usingHuffmanCoding.decode
, and displays it indecodedTextArea
. Updates the status label.loadFileButton
Action Listener: UsesJFileChooser
to open a file dialog, reads the file content, and sets it ininputTextArea
. Updates the status label.saveFileButton
Action Listener: UsesJFileChooser
to open a save file dialog and writes the content ofencodedTextArea
to a file. Updates the status label.
Conclusion of Project on Huffman coding algorithm in java
By following this detailed breakdown, you’ll gain a comprehensive understanding of how the Huffman coding algorithm in java is implemented and how it interacts with a graphical user interface. This knowledge allows you to create a robust and user-friendly application for text compression and decompression using Huffman coding algorithm in java.
Source code of Huffman coding algorithm in java
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
//Huffman coding algorithm implementation in java
class HuffmanNode {
int frequency;
char character;
HuffmanNode left, right;
HuffmanNode(char character, int frequency) {
this.character = character;
this.frequency = frequency;
left = right = null;
}
}
class HuffmanComparator implements Comparator<HuffmanNode> {
public int compare(HuffmanNode x, HuffmanNode y) {
return x.frequency - y.frequency;
}
}
class HuffmanCoding {
private static Map<Character, String> huffmanCodeMap;
private static HuffmanNode root;
private static void buildHuffmanTree(String data) {
Map<Character, Integer> frequencyMap = buildFrequencyMap(data);
PriorityQueue<HuffmanNode> priorityQueue = buildPriorityQueue(frequencyMap);
root = buildHuffmanTree(priorityQueue);
huffmanCodeMap = new HashMap<>();
generateHuffmanCodes(root, "", huffmanCodeMap);
}
private static Map<Character, Integer> buildFrequencyMap(String data) {
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char c : data.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
return frequencyMap;
}
private static PriorityQueue<HuffmanNode> buildPriorityQueue(Map<Character, Integer> frequencyMap) {
PriorityQueue<HuffmanNode> priorityQueue = new PriorityQueue<>(new HuffmanComparator());
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
priorityQueue.add(new HuffmanNode(entry.getKey(), entry.getValue()));
}
return priorityQueue;
}
private static HuffmanNode buildHuffmanTree(PriorityQueue<HuffmanNode> priorityQueue) {
while (priorityQueue.size() > 1) {
HuffmanNode left = priorityQueue.poll();
HuffmanNode right = priorityQueue.poll();
HuffmanNode parent = new HuffmanNode('\0', left.frequency + right.frequency);
parent.left = left;
parent.right = right;
priorityQueue.add(parent);
}
return priorityQueue.poll();
}
private static void generateHuffmanCodes(HuffmanNode root, String code, Map<Character, String> huffmanCodeMap) {
if (root == null) return;
if (root.left == null && root.right == null) {
huffmanCodeMap.put(root.character, code);
}
generateHuffmanCodes(root.left, code + '0', huffmanCodeMap);
generateHuffmanCodes(root.right, code + '1', huffmanCodeMap);
}
private static String encodeData(String data, Map<Character, String> huffmanCodeMap) {
StringBuilder encodedData = new StringBuilder();
for (char c : data.toCharArray()) {
encodedData.append(huffmanCodeMap.get(c));
}
return encodedData.toString();
}
private static String decodeData(String encodedData, HuffmanNode root) {
StringBuilder decodedData = new StringBuilder();
HuffmanNode current = root;
for (char c : encodedData.toCharArray()) {
if (c == '0') {
current = current.left;
} else {
current = current.right;
}
if (current.left == null && current.right == null) {
decodedData.append(current.character);
current = root;
}
}
return decodedData.toString();
}
public static String encode(String data) {
buildHuffmanTree(data);
return encodeData(data, huffmanCodeMap);
}
public static String decode(String encodedData) {
return decodeData(encodedData, root);
}
}
class HuffmanCodingGUI {
private static JTextArea inputTextArea;
private static JTextArea encodedTextArea;
private static JTextArea decodedTextArea;
private static JLabel statusLabel;
public static void main(String[] args) {
JFrame frame = new JFrame("Huffman Coding");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 500);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
frame.add(panel);
// Text area panel
JPanel textAreaPanel = new JPanel(new GridLayout(3, 1, 5, 5));
textAreaPanel.setBorder(BorderFactory.createTitledBorder("Text Areas"));
inputTextArea = new JTextArea();
inputTextArea.setLineWrap(true);
inputTextArea.setWrapStyleWord(true);
JScrollPane inputScrollPane = new JScrollPane(inputTextArea);
textAreaPanel.add(createLabeledPanel("Input Text", inputScrollPane));
encodedTextArea = new JTextArea();
encodedTextArea.setLineWrap(true);
encodedTextArea.setWrapStyleWord(true);
encodedTextArea.setEditable(false);
JScrollPane encodedScrollPane = new JScrollPane(encodedTextArea);
textAreaPanel.add(createLabeledPanel("Encoded Text", encodedScrollPane));
decodedTextArea = new JTextArea();
decodedTextArea.setLineWrap(true);
decodedTextArea.setWrapStyleWord(true);
decodedTextArea.setEditable(false);
JScrollPane decodedScrollPane = new JScrollPane(decodedTextArea);
textAreaPanel.add(createLabeledPanel("Decoded Text", decodedScrollPane));
panel.add(textAreaPanel, BorderLayout.CENTER);
// Button panel
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
JButton encodeButton = new JButton("Encode");
JButton decodeButton = new JButton("Decode");
JButton loadFileButton = new JButton("Load File");
JButton saveFileButton = new JButton("Save File");
buttonPanel.add(loadFileButton);
buttonPanel.add(saveFileButton);
buttonPanel.add(encodeButton);
buttonPanel.add(decodeButton);
panel.add(buttonPanel, BorderLayout.SOUTH);
// Status label
statusLabel = new JLabel("Status: Ready");
panel.add(statusLabel, BorderLayout.NORTH);
// Action listeners
encodeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String inputData = inputTextArea.getText();
if (inputData.isEmpty()) {
statusLabel.setText("Status: Input text is empty.");
return;
}
String encodedData = HuffmanCoding.encode(inputData);
encodedTextArea.setText(encodedData);
statusLabel.setText("Status: Encoding completed.");
} catch (Exception ex) {
statusLabel.setText("Status: Error during encoding.");
}
}
});
decodeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String encodedData = encodedTextArea.getText();
if (encodedData.isEmpty()) {
statusLabel.setText("Status: Encoded text is empty.");
return;
}
String decodedData = HuffmanCoding.decode(encodedData);
decodedTextArea.setText(decodedData);
statusLabel.setText("Status: Decoding completed.");
} catch (Exception ex) {
statusLabel.setText("Status: Error during decoding.");
}
}
});
loadFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
inputTextArea.setText("");
String line;
while ((line = reader.readLine()) != null) {
inputTextArea.append(line + "\n");
}
statusLabel.setText("Status: File loaded.");
} catch (IOException ex) {
statusLabel.setText("Status: Error loading file.");
}
}
}
});
saveFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(encodedTextArea.getText());
statusLabel.setText("Status: File saved.");
} catch (IOException ex) {
statusLabel.setText("Status: Error saving file.");
}
}
}
});
frame.setVisible(true);
}
//Huffman coding algorithm in java
private static JPanel createLabeledPanel(String labelText, JScrollPane scrollPane) {
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel(labelText);
panel.add(label, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
}