Java – Array, String, Character, Number, Date and Time

Array

Java Provides a data structure array, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.Instead of declaring individual variables, such as number 0, number 1, …, and number 99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables.

Declaring Array Variables:

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:

dataType[] arrayRefVar;   // preferred way.

or

dataType arrayRefVar[];  //  works but not preferred way.

Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

Example:

The following code snippets are examples of this syntax:

double[] myList;         // preferred way.

or

double myList[];         //  works but not preferred way.

Creating Arrays:

You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:

  • It creates an array using new dataType[arraySize];
  • It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.

Example:

Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList:

double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.

Java Array

Processing Arrays:

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Example:

Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }
      // Summing all elements
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
         total += myList[i];
      }
      System.out.println("Total is " + total);
      // Finding the largest element
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);
   }
}

This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops:

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.

Example:

The following code displays all the elements in the array myList:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (double element: myList) {
         System.out.println(element);
      }
   }
}

This would produce the following result:

1.9
2.9
3.4
3.5

Passing Arrays to Methods:

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:

public static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
  }
}

You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:

printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method:

A method may also return an array. For example, the method shown below returns an array that is the reversal of another array:

public static int[] reverse(int[] list) {
  int[] result = new int[list.length];

  for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
    result[j] = list[i];
  }
  return result;
}

The Arrays Class:

The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.

SN Methods with Description
1 public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1).
2 public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.)
3 public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other primitive data types (Byte, short, Int etc.)
4 public static void sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other primitive data types ( Byte, short, Int, etc.)

String

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:

String greeting = "Hello world!";

In this case, “Hello world!” is a string literal—a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates aString object with its value—in this case, Hello world!.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println(helloString);

The last line of this code snippet displays hello.


Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.


String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17:

String palindrome = "Dot saw I was Tod";
int len = palindrome.length();

A palindrome is a word or sentence that is symmetric—it is spelled the same forward and backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a palindrome string. It invokes the String method charAt(i), which returns the ith character in the string, counting from 0.

public class StringDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";
        int len = palindrome.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];
        
        // put original string in an 
        // array of chars
        for (int i = 0; i < len; i++) {
            tempCharArray[i] = 
                palindrome.charAt(i);
        } 
        
        // reverse array of chars
        for (int j = 0; j < len; j++) {
            charArray[j] =
                tempCharArray[len - 1 - j];
        }
        
        String reversePalindrome =
            new String(charArray);
        System.out.println(reversePalindrome);
    }
}

Running the program produces this output:

doT saw I was toD

To accomplish the string reversal, the program had to convert the string to an array of characters (first for loop), reverse the array into a second array (second for loop), and then convert back to a string. The String class includes a method, getChars(), to convert a string, or a portion of a string, into an array of characters so we could replace the first for loop in the program above with

palindrome.getChars(0, len, tempCharArray, 0);

Concatenating Strings

The String class includes a method for concatenating two strings:

string1.concat(string2); 

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:

"My name is ".concat("Rumplestiltskin");

Strings are more commonly concatenated with the + operator, as in

"Hello," + " world" + "!"

which results in

"Hello, world!"

The + operator is widely used in print statements. For example:

String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");

which prints

Dot saw I was Tod

Such a concatenation can be a mixture of any objects. For each object that is not a String, its toString() method is called to convert it to a String.


Note: The Java programming language does not permit literal strings to span lines in source files, so you must use the + concatenation operator at the end of each line in a multi-line string. For example:

String quote = 
    "Now is the time for all good " +
    "men to come to the aid of their country.";

Breaking strings between lines using the + concatenation operator is, once again, very common in print statements.


Creating Format Strings

You have seen the use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a Stringobject rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of

System.out.printf("The value of the float " +
                  "variable is %f, while " +
                  "the value of the " + 
                  "integer variable is %d, " +
                  "and the string is %s", 
                  floatVar, intVar, stringVar); 

you can write

String fs;
fs = String.format("The value of the float " +
                   "variable is %f, while " +
                   "the value of the " + 
                   "integer variable is %d, " +
                   " and the string is %s",
                   floatVar, intVar, stringVar);
System.out.println(fs);

Converting Between Numbers and Strings

Converting Strings to Numbers

Frequently, a program ends up with numeric data in a string object—a value entered by the user, for example.

The Number subclasses that wrap primitive numeric types ( Byte, Integer,Double,FLoat, LOng and Short) each provide a class method named valueOf that converts a string to an object of that type. Here is an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:

public class ValueOfDemo {
    public static void main(String[] args) {

        // this program requires two 
        // arguments on the command line 
        if (args.length == 2) {
            // convert strings to numbers
            float a = (Float.valueOf(args[0])).floatValue(); 
            float b = (Float.valueOf(args[1])).floatValue();

            // do some arithmetic
            System.out.println("a + b = " +
                               (a + b));
            System.out.println("a - b = " +
                               (a - b));
            System.out.println("a * b = " +
                               (a * b));
            System.out.println("a / b = " +
                               (a / b));
            System.out.println("a % b = " +
                               (a % b));
        } else {
            System.out.println("This program " +
                "requires two command-line arguments.");
        }
    }
}

The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:

a + b = 91.7
a - b = -82.7
a * b = 392.4
a / b = 0.0516055
a % b = 4.5

Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat()) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemoprogram, we could use:

float a = Float.parseFloat(args[0]);
float b = Float.parseFloat(args[1]);

Converting Numbers to Strings

Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:

int i;
// Concatenate "i" with an empty string; conversion is handled for you.
String s1 = "" + i;

or

// The valueOf class method.
String s2 = String.valueOf(i);

Each of the Number subclasses includes a class method, toString(), that will convert its primitive type to a string. For example:

int i;
double d;
String s3 = Integer.toString(i); 
String s4 = Double.toString(d); 

The ToStringDemo example uses the toString method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point:

public class ToStringDemo {
    
    public static void main(String[] args) {
        double d = 858.48;
        String s = Double.toString(d);
        
        int dot = s.indexOf('.');
        
        System.out.println(dot + " digits " +
            "before decimal point.");
        System.out.println( (s.length() - dot - 1) +
            " digits after decimal point.");
    }
}

The output of this program is:

3 digits before decimal point.
2 digits after decimal point.

Manipulating Characters in a String

The String class has a number of methods for examining the contents of strings, finding characters or substrings within a string, changing case, and other tasks.

Getting Characters and Substrings by Index

You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character islength()-1. For example, the following code gets the character at index 9 in a string:

String anotherPalindrome = "Niagara. O roar again!"; 
char aChar = anotherPalindrome.charAt(9);

Indices begin at 0, so the character at index 9 is ‘O’, as illustrated in the following figure:

Use the charAt method to get a character at a particular index.If you want to get more than one consecutive character from a string, you can use the substring method. The substring method has two versions, as shown in the following table:

The substring Methods in the String Class
Method Description
String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. The first integer argument specifies the index of the first character. The second integer argument is the index of the last character – 1.
String substring(int beginIndex) Returns a new string that is a substring of this string. The integer argument specifies the index of the first character. Here, the returned substring extends to the end of the original string.

The following code gets from the Niagara palindrome the substring that extends from index 11 up to, but not including, index 15, which is the word “roar”:

String anotherPalindrome = "Niagara. O roar again!"; 
String roar = anotherPalindrome.substring(11, 15); 

Use the substring method to get part of a string.

Other Methods for Manipulating Strings

Here are several other String methods for manipulating strings:

Other Methods in the String Class for Manipulating Strings
Method Description
String[] split(String regex)
String[] split(String regex, int limit)
Searches for a match as specified by the string argument (which contains a regular expression) and splits this string into an array of strings accordingly. The optional integer argument specifies the maximum size of the returned array. Regular expressions are covered in the lesson titled “Regular Expressions.”
CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence constructed from beginIndex index up until endIndex – 1.
String trim() Returns a copy of this string with leading and trailing white space removed.
String toLowerCase()
String toUpperCase()
Returns a copy of this string converted to lowercase or uppercase. If no conversions are necessary, these methods return the original string.

Searching for Characters and Substrings in a String

Here are some other String methods for finding characters or substrings within a string. The String class provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf(). The indexOf() methods search forward from the beginning of the string, and the lastIndexOf() methods search backward from the end of the string. If a character or substring is not found, indexOf() and lastIndexOf() return -1.

The String class also provides a search method, contains, that returns true if the string contains a particular character sequence. Use this method when you only need to know that the string contains a character sequence, but the precise location isn’t important.

The following table describes the various string search methods.

The Search Methods in the String Class
Method Description
int indexOf(int ch)
int lastIndexOf(int ch)
Returns the index of the first (last) occurrence of the specified character.
int indexOf(int ch, int fromIndex)
int lastIndexOf(int ch, int fromIndex)
Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.
int indexOf(String str)
int lastIndexOf(String str)
Returns the index of the first (last) occurrence of the specified substring.
int indexOf(String str, int fromIndex)
int lastIndexOf(String str, int fromIndex)
Returns the index of the first (last) occurrence of the specified substring, searching forward (backward) from the specified index.
boolean contains(CharSequence s) Returns true if the string contains the specified character sequence.

Note: CharSequence is an interface that is implemented by the String class. Therefore, you can use a string as an argument for the contains() method.


Replacing Characters and Substrings into a String

The String class has very few methods for inserting characters or substrings into a string. In general, they are not needed: You can create a new string by concatenation of substrings you haveremoved from a string with the substring that you want to insert.

The String class does have four methods for replacing found characters or substrings, however. They are:

Methods in the String Class for Manipulating Strings
Method Description
String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement) Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement.

An Example

The following class, Filename, illustrates the use of lastIndexOf() and substring() to isolate different parts of a file name.


Note: The methods in the following Filename class don’t do any error checking and assume that their argument contains a full directory path and a filename with an extension. If these methods were production code, they would verify that their arguments were properly constructed.


public class Filename {
    private String fullPath;
    private char pathSeparator, 
                 extensionSeparator;

    public Filename(String str, char sep, char ext) {
        fullPath = str;
        pathSeparator = sep;
        extensionSeparator = ext;
    }

    public String extension() {
        int dot = fullPath.lastIndexOf(extensionSeparator);
        return fullPath.substring(dot + 1);
    }

    // gets filename without extension
    public String filename() {
        int dot = fullPath.lastIndexOf(extensionSeparator);
        int sep = fullPath.lastIndexOf(pathSeparator);
        return fullPath.substring(sep + 1, dot);
    }

    public String path() {
        int sep = fullPath.lastIndexOf(pathSeparator);
        return fullPath.substring(0, sep);
    }
}

Here is a program, FilenameDemo, that constructs a Filename object and calls all of its methods:

public class FilenameDemo {
    public static void main(String[] args) {
        final String FPATH = "/home/user/index.html";
        Filename myHomePage = new Filename(FPATH, '/', '.');
        System.out.println("Extension = " + myHomePage.extension());
        System.out.println("Filename = " + myHomePage.filename());
        System.out.println("Path = " + myHomePage.path());
    }
}

And here’s the output from the program:

Extension = html
Filename = index
Path = /home/user

As shown in the following figure, our extension method uses lastIndexOf to locate the last occurrence of the period (.) in the file name. Then substring uses the return value oflastIndexOf to extract the file name extension — that is, the substring from the period to the end of the string. This code assumes that the file name has a period in it; if the file name does not have a period, lastIndexOf returns -1, and the substring method throws a StringIndexOutOfBoundsException.

The use of lastIndexOf and substring in the extension method in the Filename class.Also, notice that the extension method uses dot + 1 as the argument to substring. If the period character (.) is the last character of the string, dot + 1 is equal to the length of the string, which is one larger than the largest index into the string (because indices start at 0). This is a legal argument to substring because that method accepts an index equal to, but not greater than, the length of the string and interprets it to mean “the end of the string.”

The StringBuilder Class or String Buffer Class

String Builder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations.

Strings should always be used unless string builders offer an advantage in terms of simpler code (see the sample program at the end of this section) or better performance. For example, if you need to concatenate a large number of strings, appending to a StringBuilder object is more efficient.

Length and Capacity

The StringBuilder class, like the String class, has a length() method that returns the length of the character sequence in the builder.

Unlike strings, every string builder also has a capacity, the number of character spaces that have been allocated. The capacity, which is returned by the capacity() method, is always greater than or equal to the length (usually greater than) and will automatically expand as necessary to accommodate additions to the string builder.

StringBuilder Constructors
Constructor Description
StringBuilder() Creates an empty string builder with a capacity of 16 (16 empty elements).
StringBuilder(CharSequence cs) Constructs a string builder containing the same characters as the specified CharSequence, plus an extra 16 empty elements trailing the CharSequence.
StringBuilder(int initCapacity) Creates an empty string builder with the specified initial capacity.
StringBuilder(String s) Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string.

For example, the following code

// creates empty builder, capacity 16
StringBuilder sb = new StringBuilder();
// adds 9 character string at beginning
sb.append("Greetings");

will produce a string builder with a length of 9 and a capacity of 16:

A string builder's length is the number of characters it contains; a string builder's capacity is the number of character spaces that have been allocated.The StringBuilder class has some methods related to length and capacity that the String class does not have:

Length and Capacity Methods
Method Description
void setLength(int newLength) Sets the length of the character sequence. If newLength is less than length(), the last characters in the character sequence are truncated. If newLength is greater than length(), null characters are added at the end of the character sequence.
void ensureCapacity(int minCapacity) Ensures that the capacity is at least equal to the specified minimum.

A number of operations (for example, append(), insert(), or setLength()) can increase the length of the character sequence in the string builder so that the resultant length() would be greater than the current capacity(). When this happens, the capacity is automatically increased.

StringBuilder Operations

The principal operations on a StringBuilder that are not available in String are the append() and insert() methods, which are overloaded so as to accept data of any type. Each converts its argument to a string and then appends or inserts the characters of that string to the character sequence in the string builder. The append method always adds these characters at the end of the existing character sequence, while the insert method adds the characters at a specified point.

Here are a number of the methods of the StringBuilder class.

Various StringBuilder Methods
Method Description
StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(double d)
StringBuilder append(float f)
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String s)
Appends the argument to this string builder. The data is converted to a string before the append operation takes place.
StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)
The first method deletes the subsequence from start to end-1 (inclusive) in theStringBuilder‘s char sequence. The second method deletes the character located atindex.
StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long lng)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String s)
Inserts the second argument into the string builder. The first integer argument indicates the index before which the data is to be inserted. The data is converted to a string before the insert operation takes place.
StringBuilder replace(int start, int end, String s)
void setCharAt(int index, char c)
Replaces the specified character(s) in this string builder.
StringBuilder reverse() Reverses the sequence of characters in this string builder.
String toString() Returns a string that contains the character sequence in the builder.

Note: You can use any String method on a StringBuilder object by first converting the string builder to a string with the toString() method of the StringBuilder class. Then convert the string back into a string builder using the StringBuilder(String str) constructor.


An Example

The StringDemo program that was listed in the section titled “Strings” is an example of a program that would be more efficient if a StringBuilder were used instead of a String.

StringDemo reversed a palindrome. Here, once again, is its listing:

public class StringDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";
        int len = palindrome.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];
        
        // put original string in an 
        // array of chars
        for (int i = 0; i < len; i++) {
            tempCharArray[i] = 
                palindrome.charAt(i);
        } 
        
        // reverse array of chars
        for (int j = 0; j < len; j++) {
            charArray[j] =
                tempCharArray[len - 1 - j];
        }
        
        String reversePalindrome =
            new String(charArray);
        System.out.println(reversePalindrome);
    }
}

Running the program produces this output:

doT saw I was toD

To accomplish the string reversal, the program converts the string to an array of characters (first for loop), reverses the array into a second array (second for loop), and then converts back to a string.

If you convert the palindrome string to a string builder, you can use the reverse() method in the StringBuilder class. It makes the code simpler and easier to read:

public class StringBuilderDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";
         
        StringBuilder sb = new StringBuilder(palindrome);
        
        sb.reverse();  // reverse it
        
        System.out.println(sb);
    }
}

Running this program produces the same output:

doT saw I was toD

Note that println() prints a string builder, as in:

System.out.println(sb);

because sb.toString() is called implicitly, as it is with any other object in a println() invocation.

Date and Time

Java provides the Date class available in java.util package, this class encapsulates the current date and time.

The Date class supports two constructors. The first constructor initializes the object with the current date and time.

Date( )

The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970

Date(long millisec)

Once you have a Date object available, you can call any of the following support methods to play with dates:

SN Methods with Description
1 boolean after(Date date)
Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.
2 boolean before(Date date)
Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false.
3 Object clone( )
Duplicates the invoking Date object.
4 int compareTo(Date date)
Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date.
5 int compareTo(Object obj)
Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.
6 boolean equals(Object date)
Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false.
7 long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.
8 int hashCode( )
Returns a hash code for the invoking object.
9 void setTime(long time)
Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970
10 String toString( )
Converts the invoking Date object into a string and returns the result.

Getting Current Date & Time

This is very easy to get current date and time in Java. You can use a simple Date object with toString()method to print current date and time as follows:

import java.util.Date;
  
public class DateDemo {
   public static void main(String args[]) {
       // Instantiate a Date object
       Date date = new Date();
        
       // display time and date using toString()
       System.out.println(date.toString());
   }
}

This would produce the following result:

Mon May 04 09:51:52 CDT 2009

Date Comparison:

There are following three ways to compare two dates:

  • You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values.
  • You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
  • You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.

Date Formatting using SimpleDateFormat:

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. For example:

import java.util.*;
import java.text.*;

public class DateDemo {
   public static void main(String args[]) {

      Date dNow = new Date( );
      SimpleDateFormat ft = 
      new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

      System.out.println("Current Date: " + ft.format(dNow));
   }
}

This would produce the following result:

Current Date: Sun 2004.07.18 at 04:14:09 PM PDT

Simple DateFormat format codes:

To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:

Character Description Example
G Era designator AD
y Year in four digits 2001
M Month in year July or 07
d Day in month 10
h Hour in A.M./P.M. (1~12) 12
H Hour in day (0~23) 22
m Minute in hour 30
s Second in minute 55
S Millisecond 234
E Day in week Tuesday
D Day in year 360
F Day of week in month 2 (second Wed. in July)
w Week in year 40
W Week in month 1
a A.M./P.M. marker PM
k Hour in day (1~24) 24
K Hour in A.M./P.M. (0~11) 10
z Time zone Eastern Standard Time
Escape for text Delimiter
Single quote `

Date Formatting using printf:

Date and time formatting can be done very easily using printf method. You use a two-letter format, starting with t and ending in one of the letters of the table given below. For example:

import java.util.Date;

public class DateDemo {

  public static void main(String args[]) {
     // Instantiate a Date object
     Date date = new Date();

     // display time and date using toString()
     String str = String.format("Current Date/Time : %tc", date );

     System.out.printf(str);
  }
}

This would produce the following result:

Current Date/Time : Sat Dec 15 16:37:57 MST 2012

It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted.

The index must immediately follow the % and it must be terminated by a $. For example:

import java.util.Date;
  
public class DateDemo {

   public static void main(String args[]) {
       // Instantiate a Date object
       Date date = new Date();
        
       // display time and date using toString()
       System.out.printf("%1$s %2$tB %2$td, %2$tY", 
                         "Due date:", date);
   }
}

This would produce the following result:

Due date: February 09, 2004

Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again. For example:

import java.util.Date;
  
public class DateDemo {

   public static void main(String args[]) {
       // Instantiate a Date object
       Date date = new Date();
        
       // display formatted date
       System.out.printf("%s %tB %<te, %<tY", 
                         "Due date:", date);
   }
}

This would produce the following result:

Due date: February 09, 2004

Date and Time Conversion Characters:

Character Description Example
c Complete date and time Mon May 04 09:51:52 CDT 2009
F ISO 8601 date 2004-02-09
D U.S. formatted date (month/day/year) 02/09/2004
T 24-hour time 18:05:19
r 12-hour time 06:05:19 pm
R 24-hour time, no seconds 18:05
Y Four-digit year (with leading zeroes) 2004
y Last two digits of the year (with leading zeroes) 04
C First two digits of the year (with leading zeroes) 20
B Full month name February
b Abbreviated month name Feb
m Two-digit month (with leading zeroes) 02
d Two-digit day (with leading zeroes) 03
e Two-digit day (without leading zeroes) 9
A Full weekday name Monday
a Abbreviated weekday name Mon
j Three-digit day of year (with leading zeroes) 069
H Two-digit hour (with leading zeroes), between 00 and 23 18
k Two-digit hour (without leading zeroes), between 0 and 23 18
I Two-digit hour (with leading zeroes), between 01 and 12 06
l Two-digit hour (without leading zeroes), between 1 and 12 6
M Two-digit minutes (with leading zeroes) 05
S Two-digit seconds (with leading zeroes) 19
L Three-digit milliseconds (with leading zeroes) 047
N Nine-digit nanoseconds (with leading zeroes) 047000000
P Uppercase morning or afternoon marker PM
p Lowercase morning or afternoon marker pm
z RFC 822 numeric offset from GMT -0800
Z Time zone PST
s Seconds since 1970-01-01 00:00:00 GMT 1078884319
Q Milliseconds since 1970-01-01 00:00:00 GMT 1078884319047

There are other useful classes related to Date and time. For more details, you can refer to Java Standard documentation.

Parsing Strings into Dates:

The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to parse a string according to the format stored in the given SimpleDateFormat object. For example:

import java.util.*;
import java.text.*;
  
public class DateDemo {

   public static void main(String args[]) {
      SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); 

      String input = args.length == 0 ? "1818-11-11" : args[0]; 

      System.out.print(input + " Parses as "); 

      Date t; 

      try { 
          t = ft.parse(input); 
          System.out.println(t); 
      } catch (ParseException e) { 
          System.out.println("Unparseable using " + ft); 
      }
   }
}

A sample run of the above program would produce the following result:

$ java DateDemo
1818-11-11 Parses as Wed Nov 11 00:00:00 GMT 1818
$ java DateDemo 2007-12-01
2007-12-01 Parses as Sat Dec 01 00:00:00 GMT 2007

Sleeping for a While:

You can sleep for any period of time from one millisecond up to the lifetime of your computer. For example, following program would sleep for 10 seconds:

import java.util.*;
  
public class SleepDemo {
   public static void main(String args[]) {
      try { 
         System.out.println(new Date( ) + "\n"); 
         Thread.sleep(5*60*10); 
         System.out.println(new Date( ) + "\n"); 
      } catch (Exception e) { 
          System.out.println("Got an exception!"); 
      }
   }
}

This would produce the following result:

Sun May 03 18:04:41 GMT 2009

Sun May 03 18:04:51 GMT 2009

Measuring Elapsed Time:

Sometimes, you may need to measure point in time in milliseconds. So let’s re-write above example once again:

import java.util.*;
  
public class DiffDemo {

   public static void main(String args[]) {
      try {
         long start = System.currentTimeMillis( );
         System.out.println(new Date( ) + "\n");
         Thread.sleep(5*60*10);
         System.out.println(new Date( ) + "\n");
         long end = System.currentTimeMillis( );
         long diff = end - start;
         System.out.println("Difference is : " + diff);
      } catch (Exception e) {
         System.out.println("Got an exception!");
      }
   }
}

This would produce the following result:

Sun May 03 18:16:51 GMT 2009

Sun May 03 18:16:57 GMT 2009

Difference is : 5993

GregorianCalendar Class:

GregorianCalendar is a concrete implementation of a Calendar class that implements the normal Gregorian calendar with which you are familiar. I did not discuss Calendar class in this tutorial, you can look standard Java documentation for this.

The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the default locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar.

There are also several constructors for GregorianCalendar objects:

SN Constructor with Description
1 GregorianCalendar()
Constructs a default GregorianCalendar using the current time in the default time zone with the default locale.
2 GregorianCalendar(int year, int month, int date)
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
3 GregorianCalendar(int year, int month, int date, int hour, int minute)
Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
4 GregorianCalendar(int year, int month, int date, int hour, int minute, int second)
Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
5 GregorianCalendar(Locale aLocale)
Constructs a GregorianCalendar based on the current time in the default time zone with the given locale.
6 GregorianCalendar(TimeZone zone)
Constructs a GregorianCalendar based on the current time in the given time zone with the default locale.
7 GregorianCalendar(TimeZone zone, Locale aLocale)
Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.

Here is the list of few useful support methods provided by GregorianCalendar class:

SN Methods with Description
1 void add(int field, int amount)
Adds the specified (signed) amount of time to the given time field, based on the calendar’s rules.
2 protected void computeFields()
Converts UTC as milliseconds to time field values.
3 protected void computeTime()
Overrides Calendar Converts time field values to UTC as milliseconds.
4 boolean equals(Object obj)
Compares this GregorianCalendar to an object reference.
5 int get(int field)
Gets the value for a given time field.
6 int getActualMaximum(int field)
Return the maximum value that this field could have, given the current date.
7 int getActualMinimum(int field)
Return the minimum value that this field could have, given the current date.
8 int getGreatestMinimum(int field)
Returns highest minimum value for the given field if varies.
9 Date getGregorianChange()
Gets the Gregorian Calendar change date.
10 int getLeastMaximum(int field)
Returns lowest maximum value for the given field if varies.
11 int getMaximum(int field)
Returns maximum value for the given field.
12 Date getTime()
Gets this Calendar’s current time.
13 long getTimeInMillis()
Gets this Calendar’s current time as a long.
14 TimeZone getTimeZone()
Gets the time zone.
15 int getMinimum(int field)
Returns minimum value for the given field.
16 int hashCode()
Override hashCode.
17 boolean isLeapYear(int year)
Determines if the given year is a leap year.
18 void roll(int field, boolean up)
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
19 void set(int field, int value)
Sets the time field with the given value.
20 void set(int year, int month, int date)
Sets the values for the fields year, month, and date.
21 void set(int year, int month, int date, int hour, int minute)
Sets the values for the fields year, month, date, hour, and minute.
22 void set(int year, int month, int date, int hour, int minute, int second)
Sets the values for the fields year, month, date, hour, minute, and second.
23 void setGregorianChange(Date date)
Sets the GregorianCalendar change date.
24 void setTime(Date date)
Sets this Calendar’s current time with the given Date.
25 void setTimeInMillis(long millis)
Sets this Calendar’s current time from the given long value.
26 void setTimeZone(TimeZone value)
Sets the time zone with the given time zone value.
27 String toString()
Return a string representation of this calendar.

Example:

import java.util.*;
  
public class GregorianCalendarDemo {

   public static void main(String args[]) {
      String months[] = {
      "Jan", "Feb", "Mar", "Apr",
      "May", "Jun", "Jul", "Aug",
      "Sep", "Oct", "Nov", "Dec"};
      
      int year;
      // Create a Gregorian calendar initialized
      // with the current date and time in the
      // default locale and timezone.
      GregorianCalendar gcalendar = new GregorianCalendar();
      // Display current time and date information.
      System.out.print("Date: ");
      System.out.print(months[gcalendar.get(Calendar.MONTH)]);
      System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
      System.out.println(year = gcalendar.get(Calendar.YEAR));
      System.out.print("Time: ");
      System.out.print(gcalendar.get(Calendar.HOUR) + ":");
      System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
      System.out.println(gcalendar.get(Calendar.SECOND));
      
      // Test if the current year is a leap year
      if(gcalendar.isLeapYear(year)) {
         System.out.println("The current year is a leap year");
      }
      else {
         System.out.println("The current year is not a leap year");
      }
   }
}

This would produce the following result:

Date: Apr 22 2009
Time: 11:25:27
The current year is not a leap year

Leave a comment