Reputation: 123
I'm implementing a Character Buffer with two stacks. I am inserting an element with insert() method:
class Buffer
{
private Stack<Character> stackLeft;
private Stack<Character> stackRight;
private int size;
Buffer()
{
Stack<Character> stackLeft = new Stack<Character>();
Stack<Character> stackRight = new Stack<Character>();
size = 0;
}
public void insert(char c)
{
size ++;
stackLeft.push(c); //This line returns NullPointerException
}
}
Everytime it tries to push the c character variable, it throws Null pointer exception. Here's how I have called it from main:
public static void main(String[] args)
{
Buffer tb = new Buffer();
Character ch = new Character('a');
tb.insert(ch);
tb.insert(new Character('a'));
tb.insert('a');
}
All of these return a null exception. Asserted that Character reaches inside the method fine. I used java.util.Stack; when it failed, I implemented my own. But it still failed.
What could I be doing wrong?
Any kind of help is appreciated!
Upvotes: 0
Views: 8857
Reputation: 649
Buffer()
{
Stack<Character> stackLeft = new Stack<Character>();
Stack<Character> stackRight = new Stack<Character>();
size = 0;
}
You need to change this to
Buffer()
{
stackLeft = new Stack<Character>();
stackRight = new Stack<Character>();
size = 0;
}
It thinks you are creating new local variables in the Buffer() constructor, instead of instantiating the class fields;
Upvotes: 1
Reputation: 13465
Its because the constructer Buffer()
doesn't set the class variables, but create its own local variable(stackLeft, stackRight) and initializes that
Change this::
class Buffer
{
private Stack<Character> stackLeft;
private Stack<Character> stackRight;
private int size;
Buffer()
{
stackLeft = new Stack<Character>();
stackRight = new Stack<Character>();
size = 0;
}
public void insert(char c)
{
size ++;
stackLeft.push(c); //This line returns NullPointerException
}
}
Upvotes: 0
Reputation: 178263
With these lines in the constructor:
Stack<Character> stackLeft = new Stack<Character>();
Stack<Character> stackRight = new Stack<Character>();
You've created local variables named the same as the instance variables, so you haven't initialized the instance variables stackLeft
and stackRight
, so Java initializes them to null
.
Remove the types so the names will resolve to the instance variables.
stackLeft = new Stack<Character>();
stackRight = new Stack<Character>();
Upvotes: 6