Wednesday 30 November 2016

Chapter 5.2: Array Lists in Java


If you don't know how many items are going to be held in your array, you may be better off using something called an ArrayList. An ArrayList is a dynamic data structure, meaning items can be added and removed from the list. A normal array in java is a static data structure, because you stuck with the initial size of your array.
To set up an ArrayList, you first have to import the package from the java.util library:
import java.util.ArrayList;
You can then create a new ArrayList object:
ArrayList listTest = new ArrayList( );
Notice that you don't need any square brackets this time.
Once you have a new ArrayList objects, you can add elements to it with the add method:
listTest.add( "first item" );
listTest.add( "second item" );
listTest.add( "third item" );
listTest.add( 7 );
In between the round brackets of add you put what it is you want to add to the ArrayList. You can only add objects, however. The first three items we've added to the list above are String objects. The fourth item is a number. But this will be a number object of type Integer, rather than the primitive data type int.
Items in the list can be referenced by an Index number, and by using the get method:
listTest.get( 3 )
This line will get the item at Index position 3 on the list. Index numbers start counting at zero, so this will be the fourth item.
You can also remove items from an ArrayList. You can either use the Index number:
listTest.remove(2);
Or you can use the value on the list:
listTest.remove( "second item" );
Removing an item will resize the ArrayList, so you have to be careful when trying to get an item on the list when using its Index number. If we've removed item number 2, then our list above will contain only 3 items. Trying to get the item with the Index number 3 would then result in an error.
To go through each item in your ArrayList you can set up something called an Iterator. This class can also be found in the java.util library:
import java.util.Iterator;
You can then attach your ArrayList to a new Iterator object:
Iterator it = listTest.iterator( );
This sets up a new Iterator object called it that can be used to go through the items in the ArrayList called listTest. The reason for using an Iterator object is because it has methods called next and hasNext. You can use these in a loop:
while ( it.hasNext( ) ) {
System.out.println( it.next( ) );
}
The method hasNext returns a Boolean value. The value will be false if there are no more items in the ArrayList. The next method can be used to go through all the items in the list.
To test all this theory out, try the following code:
                                                                  

Notice the line that prints out the entire list:
System.out.println( "Whole list=" + listTest );
This gives you a quick way to see which items are on your list, if it gets a bit too long.
When the code is run, the Output window will display the following:
first item
second item
third item
7
Whole list=[first item, third item, 7]
Position 1=third item

To sum up, then, use an ArrayList when you're not sure how many elements are going to be in a list of items.

Chapter 5.1: Arrays and Strings


You can place strings of text into arrays. This is done in the same way as for integers:
String[ ] aryString = new String[5] ;
aryString[0] = "This";
aryString[1] = "is";
aryString[2] = "a";
aryString[3] = "string";
aryString[4] = "array";
The code above sets up a string array with 5 positions. Text is then assigned to each position in the array.
Here's a loop that goes round all the positions in the array, printing out whatever is at each position:
int i;
for ( i=0; i < aryString.length; i++ ) {
System.out.println( aryString[i] );
}
The loop goes round and round while the value in the variable called i is less than the length of the array called aryString.
When the above programme is run, the Output window will look like this:




You can perform a sort on string arrays, just like you can with integers. But the sort is an alphabetical ascending one, meaning that "aa" will come first over "ab". However, Java uses Unicode characters to compare one letter in your string to another. This means that uppercase letter will come before lowercase ones. Try the following code:




When the programme is run, the Output window will display the following:

                                                 





Although we've sorted the array, the word "This" comes first. If this were an alphabetical sort, you'd expect the word "a" to come first." And it does if all the letters are lowercase. In your programming code, change the capital "T" of "This" to a lowercase "t". Now run your programme again. The Output window will now display the following:
                                                       

Chapter 5.0: Java Arrays


A programming concept you just have to get used to if you're to code effectively is the array. In this section, you'll learn what arrays are, and how to use them.

What is an Array?

. An array is a way to hold more than one value at a time. It's like a list of items. Think of an array as the columns in a spreadsheet. You can have a spreadsheet with only one column, or lots of columns. The data held in a single-list array might look like this:


Like a spreadsheet, arrays have a position number for each row. The positions in an array start at 0 and go up sequentially. Each position in the array can then hold a value. In the image above array position 0 is holding a value of 10, array position 1 is holding a value of 14, position 2 has a value of 36, and so on.
To set up an array of number like that in the image above, you have to tell Java what kind of data is going in to your array (integers, strings, boolean values, etc). You then need to say how many positions the array has. You set them up like this:
int[ ] aryNums;
The only difference between setting up a normal integer variable and an array is a pair of square brackets after the data type. The square brackets are enough to tell Java that you want to set up an array. The name of the array above is aryNums. Just like normal variables, you can call them almost anything you like (with the same exceptions we mentioned earlier).
But this just tells Java that you want to set up an integer array. It doesn't say how many positions the array should hold. To do that, you have to set up a new array object:
aryNums = new int[6];
You start with your array name, followed by the equals sign. After the equals sign, you need the Java keyword new, and then your data type again. After the data type come a pair of square brackets. In between the square brackets you need the size of the array. The size is how many positions the array should hold.
If you prefer, you can put all that on one line:
int[ ] aryNums = new int[6];
So we are telling Java to set up an array with 6 positions in it. After this line is executed, Java will assign default values for the array. Because we've set up an integer array, the default values for all 6 positions will be zero ( 0 ).
To assign values to the various positions in an array, you do it in the normal way:
aryNums[0] = 10;
Here, a value of 10 is being assigned to position 0 in the array called aryNums. Again, the square brackets are used to refer to each position. If you want to assign a value of 14 to array position 1, the code would be this:
aryNums[1] = 14;
And to assign a value of 36 to array position 2, it's this:
aryNums[2] = 36;
Don't forget, because arrays start at 0, the third position in an array has the index number 2.
If you know what values are going to be in the array, you can set them up like this instead:
int[ ] aryNums = { 1, 2, 3, 4 };
This method of setting up an array uses curly brackets after the equals sign. In between the curly brackets, you type out the values that the array will hold. The first value will then be position 0, the second value position 1, and so on. Note that you still need the square brackets after int, but not the new keyword, or the repetition of the data type and square brackets. But this is just for data types of int values, string, and char values. Otherwise, you need the new keyword. So you can do this:
String[ ] aryStrings = {"Autumn", "Spring", "Summer", "Winter" };
But not this:
boolean[ ] aryBools = {false, true, false, true};
To set up a boolean array you still need the new keyword:
boolean[ ] aryBools = new boolean[ ] {false, true, false, true};
To get at the values held in your array, you type the name of the array followed by an array position in square brackets. Like this:
System.out.println( aryNums[2] );
The above code will print out whatever value is held at array position 2 in the array called aryNums. But let's get some coding practice.
Start a new project and call it anything you like. Don't forget to change the name of the Class to something relevant.
Type the following code into your new Main method:

When you run the programme you should see this in the Output window:


Change the array position number in the print line from 2 to 5 and 18 should print out instead.

Chapter 4.2 Java - Date & Time-Parsing Strings into Dates, GregorianCalendar Class

                        

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

For a complete list of constant available in Calendar class, you can refer to standard Java documentation.