0

how this code is making NullPointerException in push and main: Here is the code:

class Stack {
  private char ch[];
  private int top;

  Stack(int n) {
    char ch[] = new char[n];
    top = -1;
  }

  void push(char c) {
    if (top == ch.length - 1) {
      System.out.println("Stack full.");
      return;
    }
    top++;
    ch[top] = c;
  }

  char pop() {
    if (isEmpty()) {
      System.out.println("Stack empty");
      return (char) 0;
    }
    char p;
    p = ch[top];
    top--;
    return p;
  }

  boolean isEmpty() {
    if (top == -1)
      return true;
    else
      return false;
  }
}


class StackDemo {
  public static void main(String args[]) {
    final int size = 10;
    Stack s = new Stack(size);

    // Push charecters into the stack
    for (int i = 0; i < size; i++) {
      s.push((char) ((int) 'A' + i));
    }
    // pop the stack untill its empty
    for (int i = size - 1; i >= 0; i--) {
      System.out.println("Poped element " + i + " is " + s.pop());
    }
  }
}

The error code generated is :

0Exception in thread "main" java.lang.NullPointerException at Stack.push(StackDemo.java:11) at StackDemo.main(StackDemo.java:46)

Do i have to put these classes in a package as there is already a Stack library in java?

3 Answers 3

4

The problem is here:

char ch[] = new char[n];

You are declaring the array locally in the constructor, so the field never gets assigned. Fix it by doing this:

this.ch = new char[n];

The keyword this is, of course, optional, but it makes it more clear what you're doing and your code more readable.


A NullPointerException occurs, generally, when you call . on null. For example, this code will throw a NPE:

Object o = null;
o.toString();

Your code was throwing a NullPointerException because you never assigned the ch variable. Your assignment statement was assigning the variable in local scope.

  • Local Scope - Scope that only applies to your current { } block, for example a Constructor declaration or a Method Declaration
  • Global Scope - Scope that applies outside the curernt { } block, for example a field assignment.

Because char ch[] = new char[n]; is a local scope assignment, your globally scoped private char ch[]; was never assigned, and therefore had the default value of null.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help....But can you explain more clearly why it was generating a nullpointer exception?
@m.souvik this will solve one of your problems but if you look at my answer above you will see you have another problem too. Check it out.
2

you declared twice char ch[]! one as global and another local inside the constructor! in the constructor you must have :

Stack(int n) {
   ch = new char[n];
   top = -1;
 }

Comments

2

One problem is that you declared ch twice once globally and once in your constructor. You should not declare in your constructor.

Stack(int n) {
    char ch[] = new char[n];
    top = -1;
}

to:

Stack(int n) {
    this.ch = new char[n];
    top = -1;
}

Instead of 0 isEmpty() should be -1:

boolean isEmpty() {
        if (top == 0)
          return true;
        else
          return false;
}

isEmpty() method should be:

boolean isEmpty() {
    if (top == -1)
      return true;
    else
      return false;
}

Another problem is when you initialize the object in the constructor you set top = -1. In your pop method you check isEmpty() which returns true if top == 0. The problem is it is empty when it is initialized but top == -1. So pop() will throw an IndexOutOfBounds exception if called right after the object is initialized because you are trying to access ch[top] or ch[-1].

The reason you were getting the NullPointerException is because your global variable ch is being initialized to null when the object is created. In your constructor you are supposed to change from null to your new array of size n but you are instead creating a local array ch and not initializing the global array which is what you use throughout your other methods.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.