Print number of days for given month in Java

Print number of days for given month in Java

In this tutorial, you will be learning to write a Java Program to print the total number of days available in the given month and year.

Here we are taking the year for February month. Because for the leap year February has 29 days and for the rest year February has 28 days.

For Example:

Suppose the input given by the user is

Month 4

Year 2000

Then Output should be 30 because April has 30 days.

Java Program to print total number of days in a given month

import java.util.*;
public class Main
{
  public static void main (String[]args)
  {
        int year, month;
		Scanner sc = new Scanner(System.in);
		System.out.println("Print number of days in a given month");
		System.out.println("Please enter the month: ");
		month = sc.nextInt();
		System.out.println("Please enter the year: ");
		year = sc.nextInt();
		if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
			System.out.print("Total days in the month is 31");
		else if((month == 2) && ((year%400==0) || (year%4==0 && year%100!=0)))
		{
			System.out.print("Total days in the month is 29");
		}
		else if(month == 2)
		{
			System.out.print("Total days in the month is 28");
		}
		else{
			System.out.println("Total days in the month is 30");
		}
  }
}

Output

Print number of days in a given month
Please enter the month: 
11
Please enter the year: 
2002
Total days in the month is 30