Write a java method that will take two sorted stacks A and B (min on top), and return one

stack D that is sorted (min on top). You are allowed to use only the stack operations such as
pop, push, isEmpty and peek.
Example: suppose A={(top)1,4,7,9} and B={(top)2,3,6}, then the function will return a new
stack D= {(top) 1,2,3,4,6,7,9}

To create a Java method that takes two sorted stacks A and B and returns a sorted stack D, you can follow these steps:

1. Create a new empty stack D to store the sorted elements.
2. Loop until both stack A and stack B are not empty:
- Compare the top elements of stack A and stack B using peek() method.
- If the top element of A is smaller or equal to the top element of B, pop the element from A and push it onto stack D.
- If the top element of A is greater than the top element of B, pop the element from B and push it onto stack D.
- Repeat until one of the stacks becomes empty.
3. After the above loop, at least one of the stacks A or B will be empty. Now, move all the remaining elements from the non-empty stack to stack D.
4. The stack D will now contain all the elements from stacks A and B in sorted order (min on top).
5. Return the stack D.

Here is the Java method implementation:

```java
import java.util.Stack;

public class SortedStacks {
public static Stack<Integer> mergeStacks(Stack<Integer> stackA, Stack<Integer> stackB) {
Stack<Integer> stackD = new Stack<>();

while (!stackA.isEmpty() && !stackB.isEmpty()) {
if (stackA.peek() <= stackB.peek()) {
stackD.push(stackA.pop());
} else {
stackD.push(stackB.pop());
}
}

while (!stackA.isEmpty()) {
stackD.push(stackA.pop());
}

while (!stackB.isEmpty()) {
stackD.push(stackB.pop());
}

return stackD;
}

public static void main(String[] args) {
Stack<Integer> stackA = new Stack<>();
stackA.push(9);
stackA.push(7);
stackA.push(4);
stackA.push(1);

Stack<Integer> stackB = new Stack<>();
stackB.push(6);
stackB.push(3);
stackB.push(2);

Stack<Integer> stackD = mergeStacks(stackA, stackB);
System.out.println("Stack D: " + stackD);
}
}
```

Note: In the main method, we are pushing the elements onto the stacks A and B. After merging the stacks, the sorted stack D will be printed.