Check the Birthday and Print Birthday Message in Java

Exercise:

Write a Java Program to check the birthday and print happy birthday message.

Click Here to View the Solution!
 import java.time.LocalDate;
 import java.time.Month;
  
 public class Birthday{
    public static void main(String args[]) {
  
     // declare variables for birthday
     int birthDate = 6;
     Month birthMonth = Month.DECEMBER;
  
     // get current date using built in function
     LocalDate currentDate = LocalDate.now();
     System.out.println("Todays Date: " + currentDate);
  
     // get current date and month
     int date = currentDate.getDayOfMonth();
     Month month = currentDate.getMonth();
     if(date == birthDate && month == birthMonth) {
       System.out.println("HAPPY BIRTHDAY TO YOU!!");
     }
     else {
       System.out.println("Today is not your birthday.");
      }
    }
 } 
Click Here to View the Output!
Todays Date: 2020-12-05
Today is not your birthday.
Click Here to View the Explanation!
  • This program compares the date of birth with current date and display a message indicating Happy Birthday.
  • Two Java utilities are employed: LocalDate and Month.
  • In the main method, we declare the date of birth; where birthDate stores the day and month is stored using Month utility.
  • The next step involves fetching the current date, by calling the LocalDate.now() method.
  • After that, the current day and current month is fetched using getDayOfMonth() and getDay() methods respectively.
  • In the if-condition, both the current day and month are compared with the declared DOB.
  • If the day and the month are same as the current date, then a message is printed sating HAPYY BIRTHDAY TO YOU, otherwise the console displays that Today is not your birthday.