Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print DAY according to user input for day count.

Java Code Example — Conditional Programs

ADVERTISEMENT

Java Program to print DAY according to user input for day count.

Objective

Write a Java program to display the name of the day corresponding to a given number (1-7) using a switch statement.

Algorithm / Approach

  1. Prompt the user to enter an integer between 1 and 7.
  2. Pass the input integer into a switch statement.
  3. Provide a case block for each day (1 = Monday, 2 = Tuesday, etc.).
  4. Inside each case, print the day and use the break keyword.
  5. Add a default block to handle inputs outside the 1-7 range.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Day Number: ");
  int x = s.nextInt();
  switch(x) { 
   case 1:
    System.out.print("DAY IS MONDAY");
    break;
   case 2:
    System.out.print("DAY IS TUESDAY");
    break;
   case 3:
    System.out.print("DAY IS WEDNESDAY");
    break;
   case 4:
    System.out.print("DAY IS THURSDAY");
    break;
   case 5:
    System.out.print("DAY IS FRIDAY");
    break;
   case 6:
    System.out.print("DAY IS SATURDAY");
    break;
   case 7:
    System.out.print("DAY IS SUNDAY");
    break;
   default:
    System.out.print("Wrong Choice");
  }
 }
}

Expected Output

Enter Day Number 4
DAY IS THURSDAY

Explanation of the Program

  • A switch statement is a cleaner alternative to a long if-else if ladder when comparing a single variable against exact constant values.
  • The break statement forces the program to exit the switch block once a match is found and executed.
  • Without the break statement, execution would "fall through" and print the subsequent days as well.
  • The default case acts like a final else, catching invalid inputs.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Forgetting the break keyword at the end of each case block.
  • Using ranges or logical operators (like > or &&) inside case labels, which is not allowed in standard Java switch statements.
ADVERTISEMENT