Write a program to read gender and print the corresponding gender using switch statement


This is a Java program that prompts the user to enter a gender (as 'M' or 'F') and displays the corresponding gender as output. Here is the explanation of the code:

  • import java.util.Scanner; - This line imports the Scanner class from the java.util package, which is used for taking user input.
  • public class Read_Gender - This line declares the class named Read_Gender.
  • public static void main(String[] args) - This line is the main method that gets executed when the program runs.
  • Scanner input = new Scanner(System.in); - This line creates a new Scanner object named input that reads from the standard input stream.
  • char gen; - This line declares a char variable named gen to store the gender entered by the user.
  • System.out.printf("Enter the Gender(M/F) : "); - This line prompts the user to enter a gender.
  • gen = input.next().charAt(0); - This line reads the input from the user and stores the first character in the gen variable.
  • switch (gen) - This line starts a switch statement based on the value of gen.
  • case 'M': - This line checks if gen is equal to 'M'.
  • case 'm': - This line checks if gen is equal to 'm'.
  • System.out.printf("Male"); - This line displays "Male" as output if either case 9 or 10 is true.
  • break; - This line ends the switch statement for case 9 or 10.
  • case 'F': - This line checks if gen is equal to 'F'.
  • case 'f': - This line checks if gen is equal to 'f'.
  • System.out.printf("Female"); - This line displays "Female" as output if either case 13 or 14 is true.
  • break; - This line ends the switch statement for case 13 or 14.
  • default: - This line provides the default case when none of the above cases match.
  • System.out.printf("Unspecified Gender."); - This line displays "Unspecified Gender." as output for the default case.
  • break; - This line ends the switch statement for the default case.

Source Code

import java.util.Scanner;
public class Read_Gender
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		char gen;
 
		System.out.printf("Enter the Gender(M/F) : ");
		gen = input.next().charAt(0);
 
		switch (gen)
		{
		case 'M':
		case 'm':
			System.out.printf("Male");
			break;
		case 'F':
		case 'f':
			System.out.printf("Female");
			break;
		default:
			System.out.printf("Unspecified Gender.");
			break;
		}
	}
}

Output

Enter the Gender(M/F) : m
Male