1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Circular Queue
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
16Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Circular Queue

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
16Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Circular Queue

Overview

A standard Queue implemented with an array suffers from 'memory drift'. If you enqueue 5 items and dequeue 5 items, the front and rear pointers have drifted to the end of the array. The array is technically empty, but you can't add any more items without an expensive O(N) shift operation.

A Circular Queue solves this by connecting the end of the array back to the beginning using modulo arithmetic ((index + 1) % capacity). When the rear pointer reaches the end of the array, it seamlessly wraps around to index 0, reusing the empty spaces left behind by dequeued elements.

This guarantees strict O(1) performance for both enqueue and dequeue operations with zero memory waste and zero shifting, making it the standard implementation for bounded (fixed-size) queues in operating systems and hardware buffers.

Syntax

Implementing a Circular Queue with an Array
java
public class CircularQueue {
    private int[] array;
    private int front;
    private int rear;
    private int size;
    private int capacity;

    public CircularQueue(int k) {
        capacity = k;
        array = new int[capacity];
        front = 0;
        rear = -1;
        size = 0;
    }

    public boolean enqueue(int value) {
        if (isFull()) return false;
        
        // Modulo wrap-around! If rear was at capacity-1, it becomes 0
        rear = (rear + 1) % capacity;
        array[rear] = value;
        size++;
        return true;
    }

    public boolean dequeue() {
        if (isEmpty()) return false;
        
        // Modulo wrap-around for the front pointer
        front = (front + 1) % capacity;
        size--;
        return true;
    }

    public int Front() {
        return isEmpty() ? -1 : array[front];
    }

    public boolean isEmpty() { return size == 0; }
    public boolean isFull() { return size == capacity; }
}

Common Pitfalls

  • Miscalculating the modulo arithmetic. (rear + 1) % capacity is correct. Doing rear % capacity + 1 is wrong and will throw an ArrayIndexOutOfBoundsException.
  • Failing to track size correctly. Differentiating between a full queue and an empty queue based purely on front and rear pointers is complex (they often overlap in both states). Maintaining a dedicated size integer makes isFull() and isEmpty() trivial and bug-free.
  • Not handling concurrent access. In real-world systems, circular queues (ring buffers) are highly concurrent. Modifying front, rear, and size from different threads will corrupt the queue without proper synchronization or volatile variables.

Interview Questions

Why use a Circular Queue over a standard array-based Queue?

A standard array-based queue suffers from 'false full' conditions. As items are dequeued, empty space is left at the front of the array. Once the rear pointer hits the array's end, you cannot enqueue more items, even if the array is mostly empty, unless you shift all elements left (O(N)). A circular queue reuses the front spaces via modulo wrap-around, maintaining strict O(1) operations.

What is a 'Ring Buffer'?

A Ring Buffer is simply another name for a Circular Queue. The term is most commonly used in operating system design, hardware drivers, and low-level networking where a fixed-size contiguous memory block is used to buffer data streams continuously.

Real-World Example

Video and audio streaming software (like YouTube or Spotify clients) use Circular Queues (Ring Buffers). The network thread downloads video frames and enqueues them. The video player thread dequeues them and paints them to the screen. The buffer is a fixed size (e.g., 5 seconds of video) to prevent the application from consuming all available RAM.

example
java
// A Ring Buffer for Audio Streaming
class AudioStreamBuffer {
    CircularQueue buffer = new CircularQueue(4096); // 4KB bounded buffer
    
    // Network thread calls this
    public void onDataReceived(byte[] data) {
        for (byte b : data) {
            // If full, we might drop packets or block the thread
            buffer.enqueue(b); 
        }
    }
    
    // Audio hardware thread calls this
    public byte[] getNextAudioChunk(int size) {
        byte[] chunk = new byte[size];
        for (int i = 0; i < size; i++) {
            chunk[i] = (byte) buffer.Front();
            buffer.dequeue();
        }
        return chunk;
    }
}

Check Your Knowledge

Test your understanding of Circular Queue with these quick questions.

Question 1

What mathematical operator is the secret to a Circular Queue's logic?

Question 2

What problem does a Circular Queue solve compared to a standard Array Queue?

Question 3

What is the time complexity of enqueuing an item into a Circular Queue?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Circular Queue

Overview

A standard Queue implemented with an array suffers from 'memory drift'. If you enqueue 5 items and dequeue 5 items, the front and rear pointers have drifted to the end of the array. The array is technically empty, but you can't add any more items without an expensive O(N) shift operation.

A Circular Queue solves this by connecting the end of the array back to the beginning using modulo arithmetic ((index + 1) % capacity). When the rear pointer reaches the end of the array, it seamlessly wraps around to index 0, reusing the empty spaces left behind by dequeued elements.

This guarantees strict O(1) performance for both enqueue and dequeue operations with zero memory waste and zero shifting, making it the standard implementation for bounded (fixed-size) queues in operating systems and hardware buffers.

Syntax

Implementing a Circular Queue with an Array
java
public class CircularQueue {
    private int[] array;
    private int front;
    private int rear;
    private int size;
    private int capacity;

    public CircularQueue(int k) {
        capacity = k;
        array = new int[capacity];
        front = 0;
        rear = -1;
        size = 0;
    }

    public boolean enqueue(int value) {
        if (isFull()) return false;
        
        // Modulo wrap-around! If rear was at capacity-1, it becomes 0
        rear = (rear + 1) % capacity;
        array[rear] = value;
        size++;
        return true;
    }

    public boolean dequeue() {
        if (isEmpty()) return false;
        
        // Modulo wrap-around for the front pointer
        front = (front + 1) % capacity;
        size--;
        return true;
    }

    public int Front() {
        return isEmpty() ? -1 : array[front];
    }

    public boolean isEmpty() { return size == 0; }
    public boolean isFull() { return size == capacity; }
}

Common Pitfalls

  • Miscalculating the modulo arithmetic. (rear + 1) % capacity is correct. Doing rear % capacity + 1 is wrong and will throw an ArrayIndexOutOfBoundsException.
  • Failing to track size correctly. Differentiating between a full queue and an empty queue based purely on front and rear pointers is complex (they often overlap in both states). Maintaining a dedicated size integer makes isFull() and isEmpty() trivial and bug-free.
  • Not handling concurrent access. In real-world systems, circular queues (ring buffers) are highly concurrent. Modifying front, rear, and size from different threads will corrupt the queue without proper synchronization or volatile variables.

Interview Questions

Why use a Circular Queue over a standard array-based Queue?

A standard array-based queue suffers from 'false full' conditions. As items are dequeued, empty space is left at the front of the array. Once the rear pointer hits the array's end, you cannot enqueue more items, even if the array is mostly empty, unless you shift all elements left (O(N)). A circular queue reuses the front spaces via modulo wrap-around, maintaining strict O(1) operations.

What is a 'Ring Buffer'?

A Ring Buffer is simply another name for a Circular Queue. The term is most commonly used in operating system design, hardware drivers, and low-level networking where a fixed-size contiguous memory block is used to buffer data streams continuously.

Real-World Example

Video and audio streaming software (like YouTube or Spotify clients) use Circular Queues (Ring Buffers). The network thread downloads video frames and enqueues them. The video player thread dequeues them and paints them to the screen. The buffer is a fixed size (e.g., 5 seconds of video) to prevent the application from consuming all available RAM.

example
java
// A Ring Buffer for Audio Streaming
class AudioStreamBuffer {
    CircularQueue buffer = new CircularQueue(4096); // 4KB bounded buffer
    
    // Network thread calls this
    public void onDataReceived(byte[] data) {
        for (byte b : data) {
            // If full, we might drop packets or block the thread
            buffer.enqueue(b); 
        }
    }
    
    // Audio hardware thread calls this
    public byte[] getNextAudioChunk(int size) {
        byte[] chunk = new byte[size];
        for (int i = 0; i < size; i++) {
            chunk[i] = (byte) buffer.Front();
            buffer.dequeue();
        }
        return chunk;
    }
}

Check Your Knowledge

Test your understanding of Circular Queue with these quick questions.

Question 1

What mathematical operator is the secret to a Circular Queue's logic?

Question 2

What problem does a Circular Queue solve compared to a standard Array Queue?

Question 3

What is the time complexity of enqueuing an item into a Circular Queue?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A