'How to save a stack element to a variable?

I'm new to programming and am trying to write a function that takes a stack if integers. (5,4,3,2) and returns the added results of all of the elements. (Returns 14).

My idea was initialize the stack. Push a couple elements. Loop through each element and pop it. Save the popped elements to a variable and then add those variables. Am I thinking/going about this the wrong way?

{
    public static void main(String[] args) {
    Stack<Integer> nums = new Stack<Integer>();  
    nums.push(5);
    nums.push(4);
    nums.push(3); //I want for this to return 12 (the sum of the elements inside of the stack)
    System.out.println(nums);
    
    int sum= 0;
    
while(nums!=null){
    sum+=nums.pop();  // while the nums stack is EMPTY. Pop out the last variable...go back and do the process again until empty.
        System.out.println(nums);
}    
//System.out.print("done");
}
} 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source