-2

I implemented some code involving queues and while running it I get a NullPointerException.Please help me to fix it.I am only writing the shorter form of that code.

import java.util.*;
class ex
{
public static void main(String args[])throws IOException
{

    Scanner in=new Scanner(System.in);
    int i;
    String s;
    int n=in.nextInt();

    Queue<Integer> q=null;
    for(i=0;i<n;i++)
    {
        q.add(i);//I get the error in this line
    }
    System.out.println(q.size());
} 
}
K-ballo
  • 80,396
  • 20
  • 159
  • 169
codeKNIGHT
  • 63
  • 1
  • 8

6 Answers6

2

You have to initialize the queue first:

Queue<Integer> q=null;

Should be:

Queue<Integer> q = new Queue<Integer>();

The reason for the error is that you are trying to add values to q. q is only set to be of the type Queue<Integer> and not to be a reference to an object of that type itself.

Marcus
  • 12,296
  • 5
  • 48
  • 66
2

You get an NPE because q is null.

You have to create an object before you can use it, for example:

Queue<Integer> q = new LinkedList<Integer>();

Here, I've picked LinkedList as a class implementing the Queue interface. There are lots of others: see the "All Known Implementing Classes" section of the Queue javadoc.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1
Queue<Integer> q = null;

Well ... that's null and:

 q.add(i);

There you're trying to use it. Ergo, Exception.

You have to instantiate the object in order to have one that you can use:

Queue<Integer> q = new Queue<Integer>();

If this wasn't a simple typo / oversight, you may want to start at the beginning of the java tutorials provided by Oracle or get a "Learning java" type book before tackling something more complicated.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
0
Queue<Integer> q=null;
...
q.add(i);//I get the error in this line

Your Queue reference is null, so you get a NullPointerException when trying to access it. Before using it, q has to point to something valid like for example:

Queue<Integer> q = new Queue<Integer>();
K-ballo
  • 80,396
  • 20
  • 159
  • 169
0

That happens because q is null. You need to initialize it with something before you can use it, for example:

 Queue<Integer> q = new AbstractQueue<Integer>();

For some details and samples see:

Community
  • 1
  • 1
Yahia
  • 69,653
  • 9
  • 115
  • 144
0

You need to initialize q

Queue<Integer> q = new AbstractQueue<Integer>();
legendofawesomeness
  • 2,901
  • 2
  • 19
  • 32