Explanation
This Java program is designed to calculate the factorial of a non-negative integer entered by the user. A factorial, denoted by n!, is the product of all positive integers less than or equal to n. For example, the factorial of 5 (5!) is 5 * 4 * 3 * 2 * 1 = 120.
The code begins by importing the Scanner class, which is necessary to read input from the console. Inside the main method, which is the entry point of any Java application, a Scanner object is created to handle user input. The program then prompts the user to enter a number. This number is read and stored in an integer variable num.
To calculate the factorial, a long type variable named factorial is initialized to 1. long is used instead of int because factorials grow very quickly, and an int might not be large enough to hold the result for even moderately sized numbers (e.g., 13! or higher). A for loop is then used to iterate from 1 up to the number entered by the user (num). In each iteration of the loop, the current value of factorial is multiplied by the loop counter i, and the result is stored back into factorial. This repeatedly multiplies factorial by 1, then 2, then 3, and so on, until it reaches num, effectively computing the product 1 * 2 * ... * num.
Finally, after the loop completes, the program prints the original number and its calculated factorial to the console. The input.close() statement is crucial for releasing the system resources used by the Scanner object, which is good practice for resource management.