Solution of Problem 2 in Java