Why is it showing NULL POINTER EXCEPTION???

import java.util.;
import java.lang.
;
import java.io.*;

class Queue{
int front, rear, size, capacity;

int array[];

Queue(int capacity){

    this.capacity = capacity;
    front=0;
    rear=-1;
    size=0;
    
}

boolean isEmpty(){
    return (size==0);
}

boolean isFull(){
    return(size==capacity);
}

void enqueue(int item){
    if(this.isFull()) return;
    
    else {rear=(rear+1)%capacity;
    array[rear]=item;
        size=size+1;
    }
}
int dequeue(){
    if(this.isEmpty()) return Integer.MIN_VALUE;
    else { int item;
    item=array[front];
    front=(front+1)%capacity;
        size=size-1;
        return item;
    }

}

}

class Driver{

public static void main(String[] args){

    Queue queue = new Queue(5);
    queue.enqueue(1);
    queue.enqueue(2);
    System.out.println(queue.dequeue());
}

}

This code is the array implementation of queue…
The above code is showing null pointer exception on third line of enqueue() method, can anybody explain me the reason

@siddharth_3007 hey Bro, i Debug your code—
here in third line of deque
array[rear]=item;
u are tring to assign a value to int type array at index rear…
problem its is showing null pointer exception

at top u wrote int array[]; it means ur just declaring array variable who will be of integer type…
so upto this line, it will just create a refrence of int[] type and and it will not hold any array object
so it means int array[]=null indirectly

and u are calling null[rear]… obviously this line will cause null pointer exception…
to overcome this null pointer exception u should have to initilised array as well like
int array[]=new int[arraysize];

or u can initilise it inside main() by just declaring it globally as u did…

static int array[];
inside maim(){
size=5;
array=new int[size];
}

if u got ur answer just vote up mysolution and accept this answer on clicking tick marks at top near question
Happy Coding :slight_smile:
if needed further help ping me

1 Like