Professional Documents
Culture Documents
In addition to the collection interfaces, collections also use the Comparator, RandomAccess,
Iterator, and ListIterator interfaces
Set Interface
The Set interface defines a set. It extends Collection and declares the behavior of a
collection that does not allow duplicate elements. Therefore, the add( ) method returns
false if an attempt is made to add duplicate elements to a set. It does not define any
additional methods of its own. Set is a generic interface that has this declaration:
interface Set<E>
Here, E specifies the type of objects that the set will hold.
// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " +
al.size());
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}
The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
The LinkedList Class
The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue
interfaces. It provides a linked-list data structure. LinkedList is a generic class that has this
declaration:
class LinkedList<E>
Here, E specifies the type of objects that the list will hold. LinkedList has the two constructors
shown here:
LinkedList( )
LinkedList(Collection<? extends E> c)
The first constructor builds an empty linked list. The second constructor builds a linked list
that is initialized with the elements of the collection c.
Because LinkedList implements the Deque interface, you have access to the methods defined by
Deque. For example, to add elements to the start of a list you can use addFirst( ) or offerFirst( ).
To add elements to the end of the list, use addLast( ) or offerLast( ). To obtain the first element,
you can use getFirst( ) or peekFirst( ). To obtain the last element, use getLast( ) or peekLast( ). To
remove the first element, use removeFirst( ) or pollFirst( ). To remove the last element, use
removeLast( ) or pollLast( ).
The following program illustrates LinkedList:
// Demonstrate LinkedList.
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// Create a linked list.
LinkedList<String> ll = new LinkedList<String>();
// Add elements to the linked list.
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// Remove elements from the linked list.
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "
+ ll);
// Remove first and last elements.
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "
+ ll);
// Get and set a value.
String val = ll.get(2);
ll.set(2, val + " Changed");
System.out.println("ll after change: " + ll);
}
}
The output from this program is shown here:
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
Using an Iterator
Before you can access a collection through an iterator, you must obtain one. Each of the collection
classes provides an iterator( ) method that returns an iterator to the start of the collection. By
using this iterator object, you can access each element in the collection, one element at a time. In
general, to use an iterator to cycle through the contents of a collection, follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( )
returns true.
3. Within the loop, obtain each element by calling next( ).
For collections that implement List, you can also obtain an iterator by calling listIterator( ). As
explained, a list iterator gives you the ability to access the collection in either the forward or
backward direction and lets you modify an element. Otherwise, ListIterator is used just like
Iterator.
The Methods Defined by ListIterator
Method Description
void add(E obj) Inserts obj into the list in front of the element that will be returned
by the next call to next( ).
boolean hasNext( ) Returns true if there is a next element. Otherwise, returns false.
boolean hasPrevious( ) Returns true if there is a previous element. Otherwise, returns false.
E next( ) Returns the next element. A NoSuchElementException is thrown
if there is not a next element.
int nextIndex( ) Returns the index of the next element. If there is not a next element,
returns the size of the list.
E previous( ) Returns the previous element. A NoSuchElementException is thrown if
there is not a previous element.
int previousIndex( ) Returns the index of the previous element
void remove( ) Removes the current element from the list. An IllegalStateException is
thrown if remove( ) is called before next( ) or previous( ) is invoked.
void set(E obj) Assigns obj to the current element. This is the element last returned
by a call to either next( ) or previous( ).
// Demonstrate iterators.
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// Use iterator to display contents of al.
System.out.print("Original contents of al: ");
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Modify objects being iterated.
ListIterator<String> litr = al.listIterator();
while(litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Now, display the list backwards.
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
The output is shown here:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
Comparators
Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that
defines precisely what “sorted order” means. By default, these classes store their elements by
using what Java refers to as “natural ordering,” which is usually the ordering that you would
expect (A before B, 1 before 2, and so forth). If you want to order elements a different way, then
specify a Comparator when you construct the set or map. Doing so gives you the ability to govern
precisely how elements are stored within sorted collections and maps.
Comparator is a generic interface that has this declaration:
interface Comparator<T>
Here, T specifies the type of objects being compared.
The Comparator interface defines two methods: compare( ) and equals( ). The compare( )
method, shown here, compares two elements for order:
int compare(T obj1, T obj2)
obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It
returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned. The
method can throw a ClassCastException if the types of the objects are not compatible for
comparison. By overriding compare( ), you can alter the way that objects are ordered. For
example, to sort in reverse order, you can create a comparator that reverses the outcome of a
comparison.
The equals( ) method, shown here, tests whether an object equals the invoking comparator:
boolean equals(Object obj)
Here, obj is the object to be tested for equality. The method returns true if obj and the invoking
object are both Comparator objects and use the same ordering. Otherwise, it returns false.
Overriding equals( ) is unnecessary, and most simple comparators will not do so.
Using a Comparator
The following is an example that demonstrates the power of a custom comparator. It implements
the compare( ) method for strings that operates in reverse of normal. Thus, it causes a tree set to
be stored in reverse order.
// Use a custom comparator.
import java.util.*;
// A reverse comparator for strings.
class MyComp implements Comparator<String> {
public int compare(String a, String b) {
String aStr, bStr;
aStr = a;
bStr = b;
// Reverse the comparison.
return bStr.compareTo(aStr);
}
// No need to override equals.
}
class CompDemo {
public static void main(String args[]) {
// Create a tree set.
TreeSet<String> ts = new TreeSet<String>(new MyComp());
// Add elements to the tree set.
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
// Display the elements.
for(String element : ts)
System.out.print(element + " ");
System.out.println();
}
}
As the following output shows, the tree is now stored in reverse order:
FEDCBA
Algorithms
The collections framework defines several algorithms that can be applied to collections and
maps.
These algorithms are defined as static methods within the Collections class. Several of the
methods can throw a ClassCastException, which occurs when an attempt is made to compare
incompatible types, or an UnsupportedOperationException, which occurs when an attempt is
made to modify an unmodifiable collection.
The methods defined in collection framework's algorithm are summarized in the following table
Sr.No. Method & Description
Arrays
The Arrays class provides various methods that are useful when working with arrays. These
methods help bridge the gap between collections and arrays. Each method defined by Arrays is
examined in this section.
The asList( ) method returns a List that is backed by a specified array. In other words, both the list
and the array refer to the same location. It has the following signature:
static <T> List asList(T ... array)
Here, array is the array that contains the data.
methods
binarySearch(short[], short)
Searches the specified array of shorts for the specified value using the binary search
binarySearch(int[], int)
Searches the specified array of ints for the specified value using the binary search
binarySearch(double[], double)
Searches the specified array of doubles for the specified value using the binary search
binarySearch(A[], A, Comparator<A>)
Searches the specified array for the specified Object using the binary search algorithm
binarySearch(A[], A)
Searches the specified array for the specified Object using the binary search algorithm
binarySearch(float[], float)
Searches the specified array of floats for the specified value using the binary search
binarySearch(byte[], byte)
Searches the specified array of bytes for the specified value using the binary search
binarySearch(char[], char)
Searches the specified array of chars for the specified value using the binary search
binarySearch(long[], long)
Searches the specified array of longs for the specified value using the binary search
equals(short[], Object)
Returns true if the the specified array of short is equal to the given object
equals(byte[], Object)
Returns true if the the specified array of byte is equal to the given object
equals(double[], Object)
Returns true if the the specified array of double is equal to the given object
equals(A[], Object)
Returns true if the the specified array of Object is equal to the given object
equals(float[], Object)
Returns true if the the specified array of float is equal to the given object
equals(boolean[], Object)
Returns true if the the specified array of boolean is equal to the given object
equals(char[], Object)
Returns true if the the specified array of char is equal to the given object
equals(int[], Object)
Returns true if the the specified array of int is equal to the given object
equals(long[], Object)
Returns true if the the specified array of long is equal to the given object
fill(char[], char)
Sets each element of the specified array of chars with the specified char value.
fill(boolean[], boolean)
Sets each element of the specified array of booleans with the specified boolean value.
fill(float[], float)
Sets each element of the specified array of floats with the specified float value.
fill(A[], A)
Sets each element of the specified array of Objects with the specified Object value.
fill(double[], double)
Sets each element of the specified array of doubles with the specified double value.
fill(byte[], byte)
Sets each element of the specified array of bytes with the specified byte value.
fill(int[], int)
Sets each element of the specified array of ints with the specified int value.
fill(short[], short)
Sets each element of the specified array of shorts with the specified short value.
fill(long[], long)
Sets each element of the specified array of longs with the specified long value.
sort(short[])
Sorts the specified array of shorts into ascending numerical order. The sorting algorithm
sort(byte[])
Sorts the specified array of bytes into ascending numerical order. The sorting algorithm
sort(float[])
Sorts the specified array of floats into ascending numerical order. The sorting algorithm
sort(A[], Comparator<A>)
Sorts the specified array of objects according to the order induced by the specified
sort(A[])
Sorts the specified array of objects into ascending order, according to the natural
sort(double[])
Sorts the specified array of doubles into ascending numerical order. The sorting
sort(char[])
Sorts the specified array of chars into ascending numerical order. The sorting algorithm
sort(int[])
Sorts the specified array of ints into ascending numerical order. The sorting algorithm
sort(long[])
Sorts the specified array of longs into ascending numerical order. The sorting algorithm
toList(A[])
Returns a fixed-size List backed by the specified array
Vector class
1. Vector is similar to ArrayList which represents a dynamic array.
2. There are two differences between Vector and ArrayList. First, Vector is synchronized while
ArrayList is not, and Second, it contains many legacy methods that are not part of the
Collections Framework.
3. With the release of JDK 5, Vector also implements Iterable. This means that Vector is fully
compatible with collections, and a Vector can have its contents iterated by the for-each loop.
4. Vector class has following four constructor
Vector() //This creates a default vector, which has an initial size of 10.
Vector(int size) //This creates a vector whose initial capacity is specified by size.
Vector(int size, int incr) //This creates a vector whose initial capacity is specified by size and whose
increment is specified by incr. The increment specifies the number of elements to allocate each time when
a vector is resized for addition of objects.
Vector(Collection c) //This creates a vector that contains the elements of collection c.
Vector defines several legacy methods. Lets see some important legacy methods defined
by Vectorclass.
Method Description
Example of Vector
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Vector ve = new Vector();
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);
Enumeration en = ve.elements();
while(en.hasMoreElements())
{
System.out.println(en.nextElement());
}
}
}
Output :
10
20
30
40
50
60
Hashtable class
1. Like HashMap, Hashtable also stores key/value pair. However neither keys nor values can
be null.
2. There is one more difference between HashMap and Hashtable that is Hashtable is
synchronized while HashMap is not.
3. Hashtable has following four constructor
Hashtable() //This is the default constructor. The default size is 11.
Hashtable(int size) //This creates a hash table that has an initial size specified by size.
Hashtable(int size, float fillratio) //This creates a hash table that has an initial size specified by size and a
fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how full the hash
table can be before it is resized upward. Specifically, when the number of elements is greater than the
capacity of the hash table multiplied by its fill ratio, the hash table is expanded. If you do not specify a fill
ratio, then 0.75 is used.
Hashtable(Map< ? extends K, ? extends V> m) //This creates a hash table that is initialized with the
elements in m. The capacity of the hash table is set to twice the number of elements in m. The default load
factor of 0.75 is used.
Example of Hashtable
import java.util.*;
class HashTableDemo
{
public static void main(String args[])
{
Hashtable< String,Integer> ht = new Hashtable< String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));
Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+" "+itr.getValue());
}
}
}
Output:
a 100
b 200
c 300
d 400
Difference between HashMap and Hashtable
Hashtable HashMap
Neither key nor values can be null Both key and values can be null
Order of table remain constant over time. does not guarantee that order of map will remain
constant over time.
Properties class
1. Properties class extends Hashtable class.
2. It is used to maintain list of value in which both key and value are String
3. Properties class define two constructor
Properties() //This creates a Properties object that has no default values
Properties(Properties propdefault) //This creates an object that uses propdefault for its default values.
4. One advantage of Properties over Hashtable is that we can specify a default property that will
be useful when no value is associated with a certain key.
Note: In both cases, the property list is empty
5. In Properties class, you can specify a default property that will be returned if no value is
associated with a certain key.
}
Output :
Java was created by James Ghosling
C++ was created by Bjarne Stroustrup
C was created by Dennis Ritchie
C# was created by Microsoft Inc
Stack class
1. Stack class extends Vector.
2. It follows last-in, first-out principle for the stack elements.
3. It defines only one default constructor
Stack() //This creates an empty stack
4. If you want to put an object on the top of the stack, call push() method. If you want to remove
and return the top element, call pop() method. An EmptyStackException is thrown if you call
pop() method when the invoking stack is empty.
You can use peek() method to return, but not remove, the top object. The empty() method returns
true if nothing is on the stack. The search() method determines whether an object exists on the
stack and returns the number of pops that are required to bring it to the top of the stack.
Example of Stack
import java.util.*;
class StackDemo {
public static void main(String args[]) {
Stack st = new Stack();
st.push(11);
st.push(22);
st.push(33);
st.push(44);
st.push(55);
Enumeration e1 = st.elements();
while(e1.hasMoreElements())
System.out.print(e1.nextElement()+" ");
st.pop();
st.pop();
System.out.println("\nAfter popping out two elements");
Enumeration e2 = st.elements();
while(e2.hasMoreElements())
System.out.print(e2.nextElement()+" ");
}
}
Output:
11 22 33 44 55
After popping out two elements
11 22 33
Dictionary class
1. Dictionary is an abstract class.
2. It represents a key/value pair and operates much like Map.
3. Although it is not currently deprecated, Dictionary is classified as obsolete, because it is fully
superseded by Map class.
The Abstract Methods Defined by Dictionary
Method Purpose
Enumeration<V> Returns an enumeration of the values contained in the dictionary.
elements( )
V get(Object key) Returns the object that contains the value associated with key. If
key is not in the dictionary, a null object is returned.
boolean isEmpty( ) Returns true if the dictionary is empty, and returns false if it
contains at least one key.
Enumeration<K> keys( ) Returns an enumeration of the keys contained in the dictionary.
V put(K key, V value) Inserts a key and its value into the dictionary. Returns null if key
is not already in the dictionary; returns the previous value associated
with key if key is already in the dictionary.
V remove(Object key) Removes key and its value. Returns the value associated with key. If
key is not in the dictionary, a null is returned.
int size( ) the number of entries Returns entries in the dictionary.
StringTokenizer
The java.util.StringTokenizer class allows an application to break a string into tokens.
This class is a legacy class that is retained for compatibility reasons although its use is
discouraged in new code.
Its methods do not distinguish among identifiers, numbers, and quoted strings.
This class methods do not even recognize and skip comments.
Class declaration
Following is the declaration for java.util.StringTokenizer class:
public class StringTokenizer
extends Object
implements Enumeration<Object>
Class constructors
S.N. Constructor & Description
1 StringTokenizer(String str)
This constructor a string tokenizer for the specified string.
1 int countTokens()
This method calculates the number of times that this tokenizer's nextToken method can
be called before it generates an exception.
2 boolean hasMoreElements()
This method returns the same value as the hasMoreTokens method.
3 boolean hasMoreTokens()
This method tests if there are more tokens available from this tokenizer's string.
4 Object nextElement()
This method returns the same value as the nextToken method, except that its declared
return value is Object rather than String.
5 String nextToken()
This method returns the next token from this string tokenizer.
6 String nextToken(String delim)
This method returns the next token in this string tokenizer's string.
// Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java: The Complete Reference;" +
"author=Schildt;" +
"publisher=Osborne/McGraw-Hill;" +
"copyright=2007";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}
The output from this program is shown here:
title Java: The Complete Reference
author Schildt
publisher Osborne/McGraw-Hill
copyright 2007
BitSet
The BitSet class creates a special type of array that holds bit values. The BitSet array can
increase in size as needed. This makes it similar to a vector of bits. This is a legacy class but it
has been completely re-engineered in Java 2, version 1.4.
The BitSet defines the following two constructors.
Sr.No. Constructor & Description
BitSet( )
1
This constructor creates a default object.
BitSet(int size)
2 This constructor allows you to specify its initial size, i.e., the number of bits
that it can hold. All bits are initialized to zero.
BitSet implements the Cloneable interface and defines the methods listed in the following table −
Sr.No. Method & Description
3 int cardinality( )
Returns the number of set bits in the invoking object.
void clear( )
4
Zeros all bits.
Object clone( )
7
Duplicates the invoking BitSet object.
int hashCode( )
13
Returns the hash code for the invoking object.
boolean isEmpty( )
15
Returns true if all bits in the invoking object are zero.
int length( )
16 Returns the number of bits required to hold the contents of the invoking
BitSet. This value is determined by the location of the last 1 bit.
int size( )
24
Returns the number of bits in the invoking BitSet object.
String toString( )
25
Returns the string equivalent of the invoking BitSet object.
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
This will produce the following result −
Output
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Date
Java provides the Date class available in java.util package, this class encapsulates the current
date and time.
The Date class supports two constructors as shown in the following table.
Sr.No. Constructor & Description
Date( )
1
This constructor initializes the object with the current date and time.
Date(long millisec)
2 This constructor accepts an argument that equals the number of
milliseconds that have elapsed since midnight, January 1, 1970.
Following are the methods of the date class.
Sr.No. Method & Description
Object clone( )
3
Duplicates the invoking Date object.
long getTime( )
7
Returns the number of milliseconds that have elapsed since January 1, 1970.
int hashCode( )
8
Returns a hash code for the invoking object.
String toString( )
10
Converts the invoking Date object into a string and returns the result.
Getting Current Date and Time
This is a very easy method to get current date and time in Java. You can use a simple Date object
with toString() method to print the current date and time as follows −
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.println(date.toString());
}
}
Output
on May 04 09:51:52 CDT 2009
Calender
The java.util.calendar class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such as YEAR, MONTH,
DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting
the date of the next week.Following are the important points about Calendar:
This class also provides additional fields and methods for implementing a concrete
calendar system outside the package.
Calendar defines the range of values returned by certain calendar fields.
Class declaration
Following is the declaration for java.util.Calendar class:
public abstract class Calendar
extends Object
implements Serializable, Cloneable, Comparable<Calendar>
Field
Following are the fields for java.util.Calendar class:
static int ALL_STYLES -- This is the style specifier for getDisplayNames indicating
names in all styles, such as "January" and "Jan".
static int AM -- This is the value of the AM_PM field indicating the period of the day
from midnight to just before noon.
static int AM_PM -- This is the field number for get and set indicating whether the HOUR
is before or after noon.
static int APRIL -- This is the value of the MONTH field indicating the fourth month of
the year in the Gregorian and Julian calendars.
protected boolean areFieldsSet -- This is true if fields[] are in sync with the currently set
time.
static int AUGUST -- This is the value of the MONTH field indicating the eighth month
of the year in the Gregorian and Julian calendars.
static int DATE -- This is the field number for get and set indicating the day of the month.
static int DAY_OF_MONTH -- This is the field number for get and set indicating the day
of the month.
static int DAY_OF_WEEK -- This is the field number for get and set indicating the day of
the week.
static int DAY_OF_WEEK_IN_MONTH -- This is the field number for get and set
indicating the ordinal number of the day of the week within the current month.
static int DAY_OF_YEAR -- This is the field number for get and set indicating the day
number within the current year.
static int DECEMBER -- This is the value of the MONTH field indicating the twelfth
month of the year in the Gregorian and Julian calendars.
static int DST_OFFSET -- This is the field number for get and set indicating the daylight
savings offset in milliseconds.
static int ERA -- This is the field number for get and set indicating the era, e.g., AD or BC
in the Julian calendar.
static int FEBRUARY -- This is the value of the MONTH field indicating the second
month of the year in the Gregorian and Julian calendars.
static int FIELD_COUNT -- This is the number of distinct fields recognized by get and
set.
protected int[] fields -- This is the calendar field values for the currently set time for this
calendar.
static int FRIDAY -- This is the value of the DAY_OF_WEEK field indicating Friday.
static int HOUR -- This is the field number for get and set indicating the hour of the
morning or afternoon.
static int HOUR_OF_DAY -- This is the field number for get and set indicating the hour
of the day.
protected boolean[] isSet -- This is the flags which tell if a specified calendar field for the
calendar is set.
protected boolean isTimeSet -- This is true if then the value of time is valid.
static int JANUARY -- This is the value of the MONTH field indicating the first month of
the year in the Gregorian and Julian calendars.
static int JULY -- This is the value of the MONTH field indicating the seventh month of
the year in the Gregorian and Julian calendars.
static int JUNE -- This is the value of the MONTH field indicating the sixth month of the
year in the Gregorian and Julian calendars.
static int LONG -- This is the style specifier for getDisplayName and getDisplayNames
indicating a long name, such as "January".
static int MARCH -- This is the value of the MONTH field indicating the third month of
the year in the Gregorian and Julian calendars.
static int MAY -- This is the value of the MONTH field indicating the fifth month of the
year in the Gregorian and Julian calendars.
static int MILLISECOND -- This is the field number for get and set indicating the
millisecond within the second.
static int MINUTE -- This is the field number for get and set indicating the minute within
the hour.
static int MONDAY -- This is the value of the DAY_OF_WEEK field indicating
Monday.
static int MONTH -- This is the field number for get and set indicating the month.
static int NOVEMBER -- This is the value of the MONTH field indicating the eleventh
month of the year in the Gregorian and Julian calendars.
static int OCTOBER -- This is the value of the MONTH field indicating the tenth month
of the year in the Gregorian and Julian calendars.
static int PM -- This is the value of the AM_PM field indicating the period of the day
from noon to just before midnight.
static int SATURDAY -- This is the value of the DAY_OF_WEEK field indicating
Saturday.
static int SECOND -- This is the field number for get and set indicating the second within
the minute.
static int SEPTEMBER -- This is the value of the MONTH field indicating the ninth
month of the year in the Gregorian and Julian calendars.
static int SHORT -- This is the style specifier for getDisplayName and getDisplayNames
indicating a short name, such as "Jan".
static int SUNDAY -- This is the value of the DAY_OF_WEEK field indicating Sunday.
static int THURSDAY -- This is the value of the DAY_OF_WEEK field indicating
Thursday.
protected long time -- This is the the currently set time for this calendar, expressed in
milliseconds after January 1, 1970, 0:00:00 GMT.
static int TUESDAY -- This is the value of the DAY_OF_WEEK field indicating
Tuesday.
static int UNDECIMBER -- This is the value of the MONTH field indicating the
thirteenth month of the year.
static int WEDNESDAY -- This is the value of the DAY_OF_WEEK field indicating
Wednesday.
static int WEEK_OF_MONTH -- This is the field number for get and set indicating the
week number within the current month.
static int WEEK_OF_YEAR -- This is the Field number for get and set indicating the
week number within the current year. .
static int YEAR -- This is the field number for get and set indicating the year.
static int ZONE_OFFSET -- This is the field number for get and set indicating the raw
offset from GMT in milliseconds.
Class constructors
S.N. Constructor & Description
1 protected Calendar()
This constructor constructs a Calendar with the default time zone and locale.
4 void clear()
This method sets all the calendar field values and the time value (millisecond offset
from the Epoch) of this Calendar undefined.
6 Object clone()
This method creates and returns a copy of this object.
18 int getFirstDayOfWeek()
This method gets what the first day of the week is; e.g., SUNDAY in the U.S.,
MONDAY in France.
26 int getMinimalDaysInFirstWeek()
This method gets what the minimal days required in the first week of the year are; e.g.,
if the first week is defined as one that contains the first day of the first month of a year,
this method returns 1.
28 Date getTime()
This method returns a Date object representing this Calendar's time value (millisecond
offset from the Epoch").
29 long getTimeInMillis()
This method returns this Calendar's time value in milliseconds.
30 TimeZone getTimeZone()
This method gets the time zone.
31 int hashCode()
This method Returns a hash code for this calendar.
33 boolean isLenient()
This method tells whether date/time interpretation is to be lenient.
39 void set(int year, int month, int date, int hourOfDay, int minute)
This method sets the values for the calendar fields YEAR, MONTH,
DAY_OF_MONTH, HOUR_OF_DAY, and MINUTE.
40 void set(int year, int month, int date, int hourOfDay, int minute, int second)
This method sets the values for the fields YEAR, MONTH, DAY_OF_MONTH,
HOUR, MINUTE, and SECOND.
47 String toString()
This method return a string representation of this calendar.
Random
The java.util.Random class instance is used to generate a stream of pseudorandom
numbers.Following are the important points about Random:
The class uses a 48-bit seed, which is modified using a linear congruential formula.
The algorithms implemented by class Random use a protected utility method that on each
invocation can supply up to 32 pseudorandomly generated bits.
Class declaration
Following is the declaration for java.util.Random class:
public class Random
extends Object
implements Serializable
Class constructors
S.N. Constructor & Description
1 Random()
This creates a new random number generator.
2 Random(long seed)
This creates a new random number generator using a single long seed.
Class methods
S.N. Method & Description
2 boolean nextBoolean()
This method returns the next pseudorandom, uniformly distributed boolean value from
this random number generator's sequence.
4 double nextDouble()
This method returns the next pseudorandom, uniformly distributed double value
between 0.0 and 1.0 from this random number generator's sequence.
5 float nextFloat()
This method returns the next pseudorandom, uniformly distributed float value between
0.0 and 1.0 from this random number generator's sequence.
6 double nextGaussian()
This method returns the next pseudorandom, Gaussian ("normally") distributed double
value with mean 0.0 and standard deviation 1.0 from this random number generator's
sequence.
7 int nextInt()
This method returns the next pseudorandom, uniformly distributed int value from this
random number generator's sequence.
8 int nextInt(int n)
This method returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive), drawn from this random number
generator's sequence.
9 long nextLong()
This method returns the next pseudorandom, uniformly distributed long value from
this random number generator's sequence.
Formatter
The java.util.Formatter class provides support for layout justification and alignment, common
formats for numeric, string, and date/time data, and locale-specific output.Following are the
important points about Formatter:
Formatters are not necessarily safe for multithreaded access.Thread safety is optional and
is the responsibility of users of methods in this class.
Class declaration
Following is the declaration for java.util.Formatter class:
public final class Formatter
extends Object
implements Closeable, Flushable
Class constructors
S.N. Constructor & Description
1 Formatter()
This constructor constructs a new formatter.
2 Formatter(Appendable a)
This constructor constructs a new formatter with the specified destination.
3 Formatter(Appendable a, Locale l)
This constructor constructs a new formatter with the specified destination and locale.
4 Formatter(File file)
This constructor constructs a new formatter with the specified file.
7 Formatter(Locale l)
This constructor constructs a new formatter with the specified locale.
8 Formatter(OutputStream os)
This constructor constructs a new formatter with the specified output stream.
9 Formatter(OutputStream os, String csn)
This constructor constructs a new formatter with the specified output stream and charset.
11 Formatter(PrintStream ps)
This constructor constructs a new formatter with the specified print stream.
12 Formatter(String fileName)
This constructor constructs a new formatter with the specified file name.
1 void close()
This method closes this formatter.
2 void flush()
This method flushes this formatter.
5 IOException ioException()
This method returns the IOException last thrown by this formatter's Appendable.
6 Locale locale()
This method returns the locale set by the construction of this formatter.
7 Appendable out()
This method returns the destination for the output.
8 String toString()
This method returns the result of invoking toString() on the destination for the output.
Scanner
The java.util.Scanner class is a simple text scanner which can parse primitive types and strings
using regular expressions.Following are the important points about Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches
whitespace.
A scanning operation may block waiting for input.
A Scanner is not safe for multithreaded use without external synchronization.
Class declaration
Following is the declaration for java.util.Scanner class:
public final class Scanner
extends Object
implements Iterator<String>
Class constructors
S.N. Constructor & Description
1 Scanner(File source)
This constructs a new Scanner that produces values scanned from the specified file.
3 Scanner(InputStream source)
This constructs a new Scanner that produces values scanned from the specified input
stream.
5 Scanner(Readable source)
This constructs a new Scanner that produces values scanned from the specified source.
6 Scanner(ReadableByteChannel source)
This constructs a new Scanner that produces values scanned from the specified channel.
8 Scanner(String source)
This constructs a new Scanner that produces values scanned from the specified string.
Class methods
S.N. Method & Description
1 void close()
This method closes this scanner.
2 Pattern delimiter()
This method returns the Pattern this Scanner is currently using to match delimiters.
7 boolean hasNext()
This method returns true if this scanner has another token in its input.
10 boolean hasNextBigDecimal()
This method returns true if the next token in this scanner's input can be interpreted as a
BigDecimal using the nextBigDecimal() method.
11 boolean hasNextBigInteger()
This method returns true if the next token in this scanner's input can be interpreted as a
BigInteger in the default radix using the nextBigInteger() method.
13 boolean hasNextBoolean()
This method returns true if the next token in this scanner's input can be interpreted as a
boolean value using a case insensitive pattern created from the string "true|false".
14 boolean hasNextByte()
This method returns true if the next token in this scanner's input can be interpreted as a
byte value in the default radix using the nextByte() method.
16 boolean hasNextDouble()
This method returns true if the next token in this scanner's input can be interpreted as a
double value using the nextDouble() method.
17 boolean hasNextFloat()
This method Returns true if the next token in this scanner's input can be interpreted as a
float value using the nextFloat() method.
18 boolean hasNextInt()
This method returns true if the next token in this scanner's input can be interpreted as an
int value in the default radix using the nextInt() method.
20 boolean hasNextLine()
This method returns true if there is another line in the input of this scanner.
21 boolean hasNextLong()
This method returns true if the next token in this scanner's input can be interpreted as a
long value in the default radix using the nextLong() method.
23 boolean hasNextShort()
This method returns true if the next token in this scanner's input can be interpreted as a
short value in the default radix using the nextShort() method.
25 IOException ioException()
This method returns the IOException last thrown by this Scanner's underlying Readable.
26 Locale locale()
This method returns this scanner's locale.
27 MatchResult match()
This method returns the match result of the last scanning operation performed by this
scanner.
28 String next()
This method finds and returns the next complete token from this scanner.
31 BigDecimal nextBigDecimal()
This method scans the next token of the input as a BigDecimal.
32 BigInteger nextBigInteger()
This method Scans the next token of the input as a BigInteger.
33 BigInteger nextBigInteger(int radix)
This method scans the next token of the input as a BigInteger.
34 boolean nextBoolean()
This method scans the next token of the input into a boolean value and returns that value.
35 byte nextByte()
This method scans the next token of the input as a byte.
37 double nextDouble()
This method scans the next token of the input as a double.
38 float nextFloat()
This method scans the next token of the input as a float.
39 int nextInt()
This method scans the next token of the input as an int.
41 String nextLine()
This method advances this scanner past the current line and returns the input that was
skipped.
42 long nextLong()
This method scans the next token of the input as a long.
44 short nextShort()
This method scans the next token of the input as a short.
46 int radix()
This method returns this scanner's default radix.
47 void remove()
The remove operation is not supported by this implementation of Iterator.
48 Scanner reset()
This method resets this scanner.
51 String toString()
This method returns the string representation of this Scanner.