Counting number of days in a given month of a year

Number of days in a given month of a given year in  Java

 
 

Here, in this page we will discuss the program to find the number of days in a given month of a given year in java . Number of days in any month of a year can vary specifically in February as the cycle of leap year repeats in every 4 years when the year is leap February gives the count to 29 days but the when the year is not leap it gives count to 28 days and so no of days in a year varies from 365 to 366. 
Rather than February every month gives the count of 30 or 31 days in any case whether the year is a leap or not.

Number of days in a given month of a year in java

Implementation:

  •  Start.
  •  Take user inputs like month and year.
  •  Check if the given month is February. 
  •  If True Check if the year is a year leap or not.
  •  If year is a leap year Print 29 Days, Else Print 28 Days.
  •  If Condition in Step 3 is False Check the month. 
  •  Print the number of days assigned to specific Month.
  •  End.
java program for counting numbers of days in a given month of a year

Code in Java:

import java.io.*;

import java.util.*;

class PrepInsta

{

    public static void main(String args[])

    {

    int month, year;

    Scanner sc = new Scanner(System.in);

    System.out.println("enter the month and year: ");

    month=sc.nextInt();

    year=sc.nextInt();

    if(((month==2) && (year%4==0)) || ((year%100==0)&&(year%400==0)))

    {

        printf("Number of days is 29");

    }

    else if(month==2)

    {

        printf("Number of days is 28");

    }

    else if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)

    {

        printf("Number of days is 31");

    }

    else

    {

        printf("Number of days is 30");

    }

}

}
Output:

enter the month and year

1

2021

Number of days is 31