Reputation: 405
In some code, I have to push some numbers in a stack and print them later. So I have tried this:
package bf;
import java.util.Stack;
public class BF {
public static void main(String[] args) {
Stack<Integer> stack = null ;
stack.push(1);
int a = Integer.parseInt("" + stack.pop());
System.out.println(a);
}
}
Each time I try to do this, I get this error message:
Exception in thread "main" java.lang.NullPointerException
at bf.BF.main(BF.java:12)
C:\Users\user\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
My questions:
Is there any way to convert Integer
to int
? How?
I must use a stack. Later I need to pop and save it to an int
variable, so what else I can do? Is there not any way (I have to create a stack myself)?
There were some questions with the same/nearly the same title in Stack Overflow, but I couldn't find an answer that worked in my case.
Upvotes: 0
Views: 2165
Reputation: 45005
Yes, there is a way, it is called auto-unboxing, which is the process that will automatically convert a wrapper class (here Integer
) to its corresponding primitive type (here int
) so actually you have nothing to do.
Here is the correct code:
public static void main(String[] args) throws Exception {
Stack<Integer> stack = new Stack<>();
stack.push(1);
int a = stack.pop();
}
NB: The opposite also exists, it is called auto-boxing which is the process that will automatically convert a primitive type to its corresponding wrapper class
Upvotes: 1
Reputation: 9270
A couple of problems:
First, as Alex stated above, you need to initialize your stack before you use it. If it's null, then how could you expect to add anything to it?
Second, as I stated above, you can basically use Integer
as interchangeable with int
when boxing/unboxing due to autoboxing in Java.
Stack<Integer> stack = new Stack<>(); // initialize first
stack.push(1);
int a = stack.pop(); // just pop, no need to convert to string and parse
System.out.println(a);
Upvotes: 4