For a project I am working on I needed to access the computer’s current year. This used to be done one way in java, but the older class technique has been deprecated so I took note of the new way of doing this. The recommended class to use the Calender class. The source code appears like…
import java.util.*;
public class Test {
public static void main(String[] args) {
Calendar mycalendar = new GregorianCalendar();
Date mydate = new Date();
mycalendar.setTime(mydate);
int intcurrentyear = mycalendar.get(Calendar.YEAR);
System.out.println(intcurrentyear + “is the current year.”);
}
}
Explanation: The first line imports the necessary classes, the second and last lines are standard for any java program and can be ignored.
The next line creates an object called mycalender from the Calendar class and constructs it as a standard Gregorian type calendar when it does so.
The next line creates a date object called mydate which is basically a copy of the current system date at the moment of the object’s creation.
The next line sets the mycalendar’s variables to those stored in mydate, which were a copy of the system’s date, so now our calendar is set to the current date as it should be.
The next line creates an integer called intcurrentyear and uses the get method to copy an integer value from mycalender into it. The get method is getting something from the calendar and in this case we used the Calendar class to get a YEAR; that seems a bit confusing I know, but basically we copied the year which our Gregorian calendar was set to, which had been set from the system’s year, into an easily accessed integer. This was not a necessary step, but it makes the next line more easily read. (We could replace the word YEAR with date to get the day of the month, or month for the number of the month of the year, etc.).
The next line just displays that integer so we know the work was successful.
Another useful bit of code relating to calendars would be something to determine if the current year is a leap year or not. The evaluation of the year (which is an integer) is pretty straight forward. If the year is evenly divisible by four (in other words a multiple of 4 like the years 4, 8, 12, 16, etc., 2012, 2016, etc.) it COULD be a leap year and most likely is, but if it is also evenly divisible by one-hundred (years like 2100, 2200) it is not a leap year, UNLESS it is also evenly divisible by 400 (years like 2000, 2400).
That means a program that evaluates the current year will need three elements.
One: It will need a way to acquire the current year from the system computer. Pretty complicated, but already detailed above and can be written as a function to keep things nice and neat.
Two: It will need a way to check it a number is a multiple of another number or is evenly divisible by another number.
Three: A way to display the result (pretty obvious).
So let’s focus on the second element: What we are essentially checking for is a boolean operative. Whether something is true or false. Whether the year is or is not a leap year. And so the result should be stored in a boolean variable space in memory. Something like…
boolean answer = false;
can declare and initialize a boolean variable called answer to store the result of the function we will write later. Pretty simple. But what is concerning is how we evaluate whether a number is evenly divisible by another. The syntax however for this is surprisingly simple in java, but a bit strange. It goes something like this…
x % 4==0
Strange huh? It APPEARS the variable x is being simply being divided by 4, but a different symbol is being used. Normally for division in java we use the slash as it is found on the number pad of a keyboard (like this /). And division is taking place even with this symbol in the equation, but the percent sign we used (%) is called the remainder operator or modulo operator to be more technical and it used specifically to determine if the division can occur without a remainder. If used and the division between the two numbers results in no remainder the equation (of x % x for instance) is equal to zero and so can be evaluated on that basis.
The next thing you must note is that while we are using the equals symbol we are using it in a different way than a beginner java programmer may be familiar with. Normally we use the equals sign to assign values or copy values, but we are not doing that here. The double equals symbol is NOT an assignment operator, but rather an EVALUATION operator. That is; it is being used to make a COMPARISON to see if two things are or are not equal. It is easy to overlook one and two equal signs so watch for the difference between a single equal sign and a double one because they do very different things.
So we are making progress, but our syntax is not quite complete. We need an if statement, maybe with an else statement, and we need to follow the syntax for if and else statements to use them so…
if (x % 4 == 0){
System.out.println(“This number IS a multiple of 4.”);
}
would work. The word “if” is a java keyword and sets up a logical construct (things like if this then do this or if not do this, otherwise do this, etc.). These types of logical constructs are the basis of artificial intelligence that video games use. But the syntax is particular and you have to take note of it. The word if is lowercase, the expression being evaluated must be withing parenthesis followed by a curly brace block wherein is your code that will execute if the statement is true and the end of all those lines must follow the same syntax as a normal line terminating with a semi-colon. Below is an example including an else statement
if (x % 4 == 0){
System.out.println(“This number IS a multiple of 4.”);
else {
System.out.println(“This number is NOT a multiple of 4.”);
}
}
And so all we need is a sequence of these kinds of evaluations to determine if any year is a leap year and we need to store the result somehow, so by creating a boolean that will act as a flag keeping track of whether something is true or false we have a basic method.
The declaration of the method must allow a number (an integer) which represents the year to be passed into it and it must return a boolean (true or false) result so we will know whether the year is or is not a leap year. We are going to make the declaration within the basic class of our program between the braces, but outside of the main method. The declaration should look like…
public static boolean leapyeartest(int x){}
The word “public” just means the method is accessible to every part of the program accessing the class in which it is declared. The word “static” means you do not need to make an instanced object to use this method. The word “boolean” is the return type. The word “leapyeartest” is the name of the method. Within parenthesis is the argument list which is takes that will be the variables passed into the method. The word “int” means the variable passed into the method will be an integer. The letter “x” represents that variable within the method. And then you have the braces as usual. Within the braces we declare a simple boolean which will keep track of whether or not the variable (the year we are testing to see whether or not it is a leap year or not – the variable x as it is know within the method) passes certain criteria. We just call this boolean “flag” which is a word I like to use for this sort of thing because it reminds me of a flag flipping in the wind back and forth. We start the flag in the state of false assuming the year to not be a leap year.
boolean flag = false;
We also need a return statement to return the results of the test, which is being held by our flag so we return the flag. So now our method looks like…
public static boolean leapyeartest(int x){
boolean flag = false;
return flag;
}
Now we need to subject the variable x to certain tests. First we need to know whether it is divisible by 4. If so it will set the flag to true. If not it will still be set to false. We use that remainder operator as I explained before. If x % 4 is equal to 0 (meaning no remainder is left after x is divided by 4) then something will happen. What? Well “flag = true”. Got it?
if (x % 4==0){
flag = true;
}
But now if it passes the first test it must FAIL the second, or we could say if it passes the second we need the result (the flag set) to reverse). But we have to place our next statement within the if statement we wrote before. The test it needs to fail is that it is divisible by 100.
if (x % 100 == 0){flag = false;}
But we need it within the first if statement so…
boolean flag = false;
if (x % 4==0)
{flag = true;
if (x % 100 == 0){flag = false;
}
}
Okay, we are almost done. Now we need one final test. If year is divisible by 4, and but not 100, and IS STILL divisible by 400, it is a leap year. So we need another statement to test if divisible by 400.
if (x % 400 == 0){flag = true;}
But it must be embedded in the braces of the previous if statement, which is also embedded in a previous if statement itself. So now our method complete looks like this…
public static boolean leapyeartest(int x){
boolean flag = false;
if (x % 4==0){flag = true;
if (x % 100 == 0){flag = false;//tests if not divisible by 100
if (x % 400 == 0){flag = true;}//tests if divisible by 400
}
}
return flag;
}
And so we can write in our main method a couple of lines to test our method…
boolean isleapyear = leapyeartest(2400);//test to see if number is a leapyear
System.out.println(“This year is a leap year? : ” + isleapyear);
Using any number within the parenthesis on the first line to test if that year is a leap year. The output should say “true” for the years, 2012, 2016, “false” for the years 2100,2200, and “true” for the years 2000, and 2400.
Now is there a way we can gather up the current system date and test the current year? Of course. The code is rather simple now…
import java.util.*;
public class Test {
public static void main(String[] args) {
Calendar mycalendar = new GregorianCalendar();
Date mydate = new Date();
mycalendar.setTime(mydate);
int intcurrentyear = mycalendar.get(Calendar.YEAR);
System.out.println(intcurrentyear + ” is the current year.”);
if (leapyeartest(intcurrentyear) ==true){
System.out.println(intcurrentyear + ” is a leapyear.”);
}
else{
System.out.println(intcurrentyear + “is not a leapyear.”);
}
}
public static boolean leapyeartest(int x){
boolean flag = false;
if (x % 4==0){flag = true;
if (x % 100 == 0){flag = false;//tests if not divisible by 100
if (x % 400 == 0){flag = true;}//tests if divisible by 400
}
}
return flag;
}
}
And since the date of the publication of this article is 2016 the output shows…
2016 is the current year.
2016 is a leapyear.
Which it is!
Now we could rewrite our program to get input to test any year instead of just the current year. We could do this so it accepts input from the console, but let’s be fancy and do a swing dialog box so it’ll work in windows or xwindows or whatever. We need to import javax.swing.*
Luckily once that is done we do not need to create a whole JFrame. We can just use a JOptionPane to get input in a string format and then we can reparse it as an integer for use in our program. The code will look like…
String s = JOptionPane.showInputDialog(“Enter a calender year to test if it is a leap year – Example: 2006”);
int x = Integer.parseInt(s);
Now we can use x in our leap year testing method and let a popup give us the answer so we’ll need to move our if statement which displays the answer for our leapyear tester to its own method and rewrite it a bit. And we’ll want to still test the current year when a person starts the program and show them that result too just for fun.
Let’s put it all together now…
import java.util.*;
import javax.swing.*;
public class Test {
public static void main(String[] args){
displaycurrentyear();
String s = JOptionPane.showInputDialog(“Enter a calender year to test if it is a leap year – Example: 2006”);
int x = Integer.parseInt(s);
showanswer(x);
}
private static void displaycurrentyear() {
Calendar mycalendar = new GregorianCalendar();
Date mydate = new Date();
mycalendar.setTime(mydate);
int intcurrentyear = mycalendar.get(Calendar.YEAR);
JOptionPane.showMessageDialog(null,”Welcome! The current year is … ” + intcurrentyear);
showcurrentyearanswer(intcurrentyear);
}
private static void showanswer(int x) {
if (leapyeartest(x) ==true){
JOptionPane.showMessageDialog(null,”The year you entered which was… ” + x + ” is a leap year”);
}else{
JOptionPane.showMessageDialog(null,”The year you entered which was… ” + x + ” is not a leap year”);
}
}
private static void showcurrentyearanswer(int x) {
if (leapyeartest(x) ==true){
JOptionPane.showMessageDialog(null,”The current year which is… ” + x + ” is a leap year”);
}else{
JOptionPane.showMessageDialog(null,”The current year which is… ” + x + ” is not a leap year”);
}
}
public static boolean leapyeartest(int x){
boolean flag = false;
if (x % 4==0){flag = true;
if (x % 100 == 0){flag = false;//tests if not divisible by 100
if (x % 400 == 0){flag = true;}//tests if divisible by 400
}
}
return flag;
}
}
And it works!!!!!!!!!!