You are not logged in. Please login at www.codechef.com to post your questions!

×

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

asked 22 Jun '17, 11:36

siddharth_3007's gravatar image

2★siddharth_3007
32
accept rate: 0%

edited 22 Jun '17, 11:38


@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 ^_^
if needed further help ping me

link

answered 22 Jun '17, 12:41

hemant_dhanuka's gravatar image

5★hemant_dhanuka
533112
accept rate: 3%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×2,698

question asked: 22 Jun '17, 11:36

question was seen: 660 times

last updated: 22 Jun '17, 12:41