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
andMonth
. - In the main method, we declare the date of birth; where
birthDate
stores the day andmonth
is stored usingMonth 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()
andgetDay()
methods respectively. - In the
if-condition
, both the current day and month are compared with the declaredDOB
. - 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 thatToday is not your birthday
.