Here is a simple Java program for beginners,
Write a Java program to find a leap year or not.
Formula for finding a Leap year is as follows:
1. A year should be evenly divisible by 4 (should not have a reminder):
year % 4 == 0 ( reminder should be 0 )
2. AND Year should not be evenly divisible by 100 (should have a reminder):
year % 100 != 0 ( reminder should not be 0 )
3. OR Year should be evenly divisible by 400 (should have a reminder):
year%400 == 0 ( reminder should be 0 )
So basically 1 && 2 || 3
if (1 and 2) both are true or 3 is true then it is a leap year
Here is the Java program to find the leap year,
import java.util.Scanner;
/**
*
* @author agur
*/
public class LeapYear {
public static void main(String[] args) {
int year;
Scanner in = new Scanner(System.in);
System.out.println("Enter a year:");
year = in.nextInt();
if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) {
System.out.println(year+" is a leap year");
} else {
System.out.println(year+" is not a leap year");
}
}
}
The output of the above program will be:
run: Enter a year: 1997 1997 is not a leap year BUILD SUCCESSFUL (total time: 3 seconds)
run: Enter a year: 1996 1996 is a leap year BUILD SUCCESSFUL (total time: 1 second)
Hope this post will be helpful for Java Beginners.