Calculate Factorial in Java: Explanation & Practice

Calculate factorial of a number

Problem summary

Write a program that calculates n! (factorial). Your code should work for any non-negative integer.

Starter code

public class Main {
    public static void main(String[] args) {
        int n = 5; // Test case 1
        
        // Calculate n! = n * (n-1) * ... * 1
        // Print: Factorial: <result>
    }
}

Expected output and test cases

  • 5! = 120
    Factorial: 120
  • 4! = 24
    Factorial: 24
  • 0! = 1
    Factorial: 1

Hints

  1. Start from 1 and multiply up to n
  2. Or start from n and multiply down to 1
  3. 0! is defined as 1

Related Core Java Basics exercises

Practice all Core Java Basics exercises · Run this idea in the Java compiler