Sie sind auf Seite 1von 25

Chapter 8 – Utility Classes

The topics covered under this chapter are:

a) Wrapper Classes
b) Vector Class
c) String Class
d) StringBuffer Class
e) Calendar Class
f) GregorianCalendar Class

Wrapper Classes
The java programming languages does not look at primitive data types as object. For example,
numerical, boolean, character data are treated in the primitive form for the sake of efficiency. The
Java Language provides wrapper classes to manipulate primitive data elements as objects. Such
data elements are wrapped in to an object created around them. Each Java primitive has a
corresponding wrapper classes in the java.lang package and each wrapper class encapsulates a
single primitive value.

Class Description
Boolean Object wrapper for the boolean data type
Character Object wrapper for the char data type
Double Object wrapper for double data type
Float Wrapper for float data type
Integer Wraps integer data type
Long Type wrapper for long data type
Number A superclass that defines methods of numeric type
wrappers

Number Class: Abstract Class – has 6 methods which returns byteValue() and so on – 6
Concrete subclasses

Double & Float: Float (String s) and Double (String s) throws a NumberFormatException.

static float parseFloat (String s) throws NumberFormatException

NaN (Not a Number) and +ve and –ve Infinity is possible

Character:

static boolean isDefined (char c) – True if c if defined by unicode or else false

static boolean isLetter ( char c)

Boolean : The two constructors are

Boolean (boolean value)


Boolean (String s) wherein it is True either in uppercase or lowercase.
Clone () generates a duplicate copy of the object on which it is called and only classes that
implement a Cloneable interface can be cloned. If u try to clone () a class that does not
implement Cloneable then CloneNotSupportedException is thrown

Class
The class Class encapsulates the runtime state of an object or interface. Objects of type Class
are created automatically when classes are loaded. You cannot explicitly declare a Class object.

Classloader is an abstract class

You can create wrappers in a variety of ways depending on the data type. You can create
instances of the Integer class in two ways:

Integer I1 = new Integer(6);


Integer I2 = new Integer("6");

Once created, you can apply a suite of methods. You can use some of these to convert the
internal value to a new data type. For example, the preceding code returns a double value for the
integer 6:

double dbl = I1.doubleValue();

As with the String class, you can employ class methods to perform operations on primitive data
types without creating an instance of a class. For example, the following code converts a string to
an integer:

int i = Integer.parseInt("6");

If the String cannot be converted to a number, a NumberFormatException object is thrown.


Exceptions are discussed later in the section "Introduction to Exception Handling."

Finally, the type wrappers provide public variables that give information about such things as the
upper and lower bounds of a data type. To get the maximum value a double primitive type can
have, you may call the following:

System.out.println("Max double value: " + Double.MAX_VALUE);

The MAX_VALUE public variable is a class variable of the Double class and is declared as static
as in class methods.

Converting Numbers to and from Strings

One of the most common programming chores is converting the string representation of a
number into its integral binary format. Fortunately, java provides an easy way to accomplish this.
The Byte, Short, Integer and Long classes provide the parseByte (), parseShort () and
respectively wherein these methods return the byte, short, int or long equivalent of the numeric
string with which they are called.

Collection API
A Collection (or a container) is a single object representing a group of objects, known as its
elements. Collections typically deal with many types of objects, all of which are of a particular kind
(that is they all descend from a common parent type). The Java programming language supports
collection classes Vector, Bits, Stack, Hashtable, BitSet, LinkedList and so on. As already seen,
Stack implements a LIFO sequence and Hashtable provides a associative array of objects.

Collections maintain references to objects of type Object. This allows any object to be stored in
the collection. It also necessitates the use of correct casting before you can use the object, after
retrieving it from the collection. The Collection API typically consists of interfaces that maintain
objects.

 Collections – A Group of objects with no specific ordering.


 Set – A group of objects with no duplication
 List – A group of ordered objects, duplicates are permitted

The API also contains classes, such as HashSet and ArrayList, which implements these
interfaces. The API also provides methods supporting some algorithms, such as sorting, binary
searching, evaluating the minimum and maximum out of lists and collections.

Map Interface

A map is an object that stores associations between keys and values or key / value pairs. given a
key, you can find its value. Both keys and values are objects. The key must be unique, but the
values may be duplicated. Some maps can accept null keyword and null values, but others
cannnot.

The Vector Class


A Vector is a class, which groups together objects of different data types. Each vector maintains a
capacity and capacityIncrement. As elements are added to a vector, storage for the vector
increases, in chunks to the size of the capacityIncrement variable. The capacity of a vector is
always atleast as large as the size of the vector.

Vector Constructors

The constructors for the Vector Class are:

a) Vector () –Constructs an empty vector so that its internal data array has size 10 and its
standard capacity increment is zero.

b) Vector (int initialCapacity) – Constructs a empty vector with the specified storage
capacity.

c) Vector (int initialCapacity, int capacityIncrement) – Constructs a empty vector with the
specified storage capacity and the specified increment.

For Eg. Vector (10,5) – Will construct a Vector with a initial capacity of 10 and a increment
capacity of 5 elements and when the 11 th element is added the capacity would increase to 15
directly and so on.

Vector Methods

The access methods provided by the Vector class support array-like operations and operations
related to the size of Vector objects. The array-like operations allow elements to be added,
deleted, and inserted into vectors. They also allow tests to be performed on the contents of
vectors and specific elements to be retrieved. The size-related operations allow the byte size and
number of elements of the vector to be determined and the vector size to be increased to a
certain capacity or trimmed to the minimum capacity needed.

Method Summary
void add(int index, Object element)
Inserts the specified element at the specified position in this Vector.
boolean add(Object o)
Appends the specified element to the end of this Vector.
boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of
this Vector, in the order that they are returned by the specified Collection's
Iterator.
boolean addAll(int index, Collection c)
Inserts all of the elements in in the specified Collection into this Vector
at the specified position.
void addElement(Object obj)
Adds the specified component to the end of this vector, increasing its
size by one.
int capacity()
Returns the current capacity of this vector.
void clear()
Removes all of the elements from this Vector.
boolean contains(Object elem)
Tests if the specified object is a component in this vector.
boolean containsAll(Collection c)
Returns true if this Vector contains all of the elements in the specified
Collection.
void copyInto(Object[] anArray)
Copies the components of this vector into the specified array.
Object elementAt(int index)
Returns the component at the specified index.
void ensureCapacity(int minCapacity)
Increases the capacity of this vector, if necessary, to ensure that it can
hold at least the number of components specified by the minimum capacity
argument.
boolean equals(Object o)
Compares the specified Object with this Vector for equality.
Compares the specified Object with this Vector for equality. Returns
true if and only if the specified Object is also a List, both Lists have
the same size, and all corresponding pairs of elements in the two Lists
are equal. (Two elements e1 and e2 are equal if (e1==null ?
e2==null : e1.equals(e2)).) In other words, two Lists are defined to
be equal if they contain the same elements in the same order.

Object firstElement()
Returns the first component (the item at index 0) of this vector.
Object get(int index)
Returns the element at the specified position in this Vector.
int hashCode()
Returns the hash code value for this Vector.
int indexOf(Object elem)
Searches for the first occurence of the given argument, testing for
equality using the Object’s equals method, which compares only the object
references and not object contents. It will return -1 if the element is not found.
int indexOf(Object elem, int index)
Searches for the first occurence of the given argument, beginning the
search at index, and testing for equality using the equals method.
void insertElementAt(Object obj, int index)
Inserts the specified object as a component in this vector at the
specified index.
boolean isEmpty()
Tests if this vector has no components.
Object lastElement()
Returns the last component of the vector.
int lastIndexOf(Object elem)
Returns the index of the last occurrence of the specified object in this
vector.
int lastIndexOf(Object elem, int index)
Searches backwards for the specified object, starting from the specified
index, and returns an index to it.
Object remove(int index)
Removes the element at the specified position in this Vector.
boolean remove(Object o)
Removes the first occurrence of the specified element in this Vector If
the Vector does not contain the element, it is unchanged.
boolean removeAll(Collection c)
Removes from this Vector all of its elements that are contained in the
specified Collection.
void removeAllElements()
Removes all components from this vector and sets its size to zero.
boolean removeElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from
this vector.
void removeElementAt(int index)
Deletes the component at the specified index.
protected removeRange(int fromIndex, int toIndex)
void Removes from this List all of the elements whose index is between
fromIndex, inclusive and toIndex, exclusive.
boolean retainAll(Collection c)
Retains only the elements in this Vector that are contained in the
specified Collection.
Object set(int index, Object element)
Replaces the element at the specified position in this Vector with the
specified element.
void setElementAt(Object obj, int index)
Sets the component at the specified index of this vector to be the
specified object.
void setSize(int newSize)
Sets the size of this vector.
int size()
Returns the number of components in this vector. This is not the same
as the Vector’s Capacity.
List subList(int fromIndex, int toIndex)
Returns a view of the portion of this List between fromIndex, inclusive,
and toIndex, exclusive.
Object[] toArray()
Returns an array containing all of the elements in this Vector in the
correct order.
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this Vector in the
correct order.
String toString()
Returns a string representation of this Vector, containing the String
representation of each element.
void trimToSize()
Trims the capacity of this vector to be the vector's current size.

Example of using Vector:

Example 1:

import java.util.*;

class VectorDemo
{
public static void main(String args[])
{
// Create a vector and its elements

Vector v = new Vector();

v.addElement(new Integer(5));
v.addElement(new Float(-14.14f));
v.addElement(new String("Hello"));
v.addElement(new Long(120000000));
v.addElement(new Double(-23.45e-11));

// Display the vector elements


System.out.println(v);

// Insert an element into the vector


String s = new String("String to be inserted");

v.insertElementAt(s, 1);
System.out.println(v);

// Remove an element from the vector


v.removeElementAt(3);

System.out.println(v);

// Elements in a Vector
System.out.println(v.size());
}
}

Example 2:

import java.util.Vector;

class Vect1
{
String ename;
Integer sal;

public static void main(String as[])


{
Vector v = new Vector(2,0);

Vect1 v1 = new Vect1();


v1.ename = "raman";
v1.sal = new Integer(8000);

Vect1 v2 = new Vect1();


v2.ename = "gopal";
v2.sal = new Integer(18000);

v.addElement(v1.ename);
v.addElement(v1.sal);
v.addElement(v2.ename);
v.addElement(v2.sal);

System.out.println(v.capacity());

System.out.println(v.elementAt(0));
System.out.println(v.elementAt(1));
System.out.println(v.elementAt(2));
System.out.println(v.elementAt(3));

v.removeElementAt(1);

System.out.println(v.elementAt(0));
System.out.println(v.elementAt(1));
System.out.println(v.elementAt(2));
// System.out.println(v.elementAt(3));

// System.out.println(v.indexOf("Gopal"));
v.setElementAt("Gopal",1);
System.out.println(v.elementAt(1));

}
}

Example 3:

import java.lang.System;
import java.util.Vector;
import java.util.Enumeration;

public class VectorApp {


public static void main(String args[]){
Vector v = new Vector();
v.addElement("one");
v.addElement("two");
v.addElement("three");
v.insertElementAt("zero",0);
v.insertElementAt("oops",3);
v.insertElementAt("four",5);
System.out.println("Size: "+v.size());
Enumeration enum = v.elements();
while (enum.hasMoreElements())
System.out.print(enum.nextElement()+" ");
System.out.println();
v.removeElement("oops");
System.out.println("Size: "+v.size());
for(int i=0;i<v.size();++i)
System.out.print(v.elementAt(i)+" ");
System.out.println();
}
}

The program creates a Vector object using the default constructor and uses the addElement()
method to add the strings, "one", "two", and "three" to the vector. It then uses the
insertElementAt() method to insert the strings "zero", "oops", and "four" at locations 0, 3, and 5
within the vector. The size() method is used to retrieve the vector size for display to the console
window.

The elements() method of the Vector class is used to retrieve an enumeration of the elements
that were added to the vector. A while loop is then used to cycle through and print the elements
contained in the enumeration. The hasMoreElements() method is used to determine whether the
enumeration contains more elements. If it does, the nextElement() method is used to retrieve the
object for printing.

The removeElement() of the Vector class is used to remove the vector element containing the
string "oops". The new size of the vector is displayed and the elements of the vector are
redisplayed. The for loop indexes each element in the vector using the elementAt() method.

The output of the VectorApp program is as follows:

Size: 6
zero one two oops three four
Size: 5
zero one two three four

String Handling
In Java, a string in a sequence of characters, but unlike many other languages that implement
strings as character arrays, java implements strings as objects of type String. Strings are
immutable, that is when you create a String object, and you cannot change the characters that
comprise that string. At first, this may seem to be a serious restriction, however that is not the
case. You can still perform all types of string operations. The difference is that each time you
need an altered version of an existing string, a new String object is created that contains the
modification. The original string is left unchanged. For those cases in which a modifiable string is
desired, there is a companion class to String called StringBuffer, whose objects contain strings
that can be modified after they are created.

Both the String and StringBuffer classes are defined in java.lang. Thus they are available to
programs automatically. Both are declared as final, which means that neither of these classes can
be subclassed. The important point to remember is that when we say strings within objects of
type String are unchangeable means that the contents of the String instance cannot be changed
after it has been created. However, a variable declared as a String reference can be changed to
point at some other String object at any time.

Constructor Summary
String()
Initializes a newly created String object so that it represents an empty character
sequence.

Eg. String s = new String();


String(char[] value)
Allocates a new String so that it represents the sequence of characters currently
contained in the character array argument.

char c[] = {‘s’, ‘t’, ‘n’, ’m’};


String s = new String(c);
String(char[] value, int startindex, int numberofchars)
Allocates a new String that contains characters from a sub array of the character
array argument, starting from the int startindex till int numberof chars.

Eg. char c[] = {‘s’, ‘t’, ‘n’, ’m’, ‘o’, ‘p’};


String s = new String(2,3); // which means it will start from index 2 that is ‘n’ having 3
characters till o and s will contain characters nmo.

String(String value)
Initializes a newly created String object so that it represents the same sequence of
characters as the argument; in other words, the newly created string is a copy of the
argument string.

Eg. String s = new String(“Hello”);


String s1 = new String (s);

Here both s and s1 will both have Hello.

String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained
in the string buffer argument.

String Length

The length of a String is the number of characters that it contains. To obtain this value, call the
length () method.

Example

String s = new String (“Hello”);

int a = s.length(); // which will give a output of 5

Ways of Creating String

String is the only object, which can also be created without the new keyword. The two different
ways of creating String are as under:

a) String s = “Hello”; // which will also create a String object stored in the String pool in
stack.
b) String s = new String(“Hello”) // which will create a String object stored in the heap.

String Concatenation

In general, java does not allow operators to be applied to String objects. The one exception to this
rule is the + operator, which concatenates two strings, producing a String object as a result. This
allows you to chain together a series of + operations.

String Concatenation with out Data Types


You can concatenate strings with other types of data, in which case the other data types are
converted into string objects and then added.

Example:

int a = 10;

String s = “Hello” + a; // The result will be Hello10.

Example

int a = 10;
int b = 20;
String s = “Hello”

System.out.println (a+b+s);// The output would be 30Hello, because it would add int a and b and
then concatenate, however the result would change if

System.out.println (s+a+b);// Here the output would be Hello1020.

Methods of String relating to Character Extraction

cha charAt(int index)


r Returns the character at the specified index.

To extract a single character from a String, you can directly refer to an individual chacater via the
charAt(). For eg.

char ch;
ch = “abc”.charAt(1) // here we assign the value of b to ch.

voi getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


d Copies characters from this string into the destination character array.

If you need to extract more than one character at a time, you can use the getChar() method. The
general form of it is:

void getChars (int start, int end, char target [], int target);

Here the start specifies the index of the beginning of the substring and end specifies an index that
is one past the end of the desired substring. Thus the substring contains characters from start
through end –1. The array that will receive the characters is specified by target. The index within
target at which the substring will be copied is passed in target. Care must be taken to assure that
the target array is large enough to hold the number of characters in specified substring.

String s = “This is a demo of the getChars methods”;


int start = 10;
int end = 14;

char b[] = new char (end – start);

s.getChars(start,end,b,0);
System.out.println(b);
getBytes ()

This method is an alternative to getChars () that stores the characters in an array of bytes. This
method is used the character-to-byte conversions provided by the platform. The simplest form of
it is:

b[] getBytes();

toCharArray ()

If you want to convert all the characters in a String object into a Character array, the easiest way
is to call toCharArray (). It returns an array of characters for the entire string. It has this general
form

c[] toCharArray().

String Comparisons

The String class includes several methods that compare strings or substrings within strings and
the methods are

equals () and equalsIgnoreCase ()

The general form of equals method is

boolean equals (Object str) – Here the str is the String object compared with the invoking String
object.

To perform a comparison that ignores case difference, call equalsIgnoreCase () which consider A-
Z the same as a-z.

regionMatches ()

The regionMatches method compares a specific region inside a string with another specific region
in another string. There is an overloaded form that allows you to ignore case in such
comparisons. The general form for these methods is:

boolean regionMatches ( int startindex, String str2, int str2startindex, int numchars)

Here the startindex specifies the index at which the region begins within the invoking String
object. The String being compared is specified by str2 and the index at which the comparison
must start is specified in str2startindex and the length is specified by numchars.

startWith () and endsWith ()

The String class has methods for checking the start or end of a string and the general form is

boolean startWith (String s)


boolean endsWith (String s)

There is a second form of startWith () which specifies the starting point and is

boolean startWith (String s, int index)

Eg. “Foobar”.startsWith (“bar”,3) // will return true


equals() versus == operator

The == operator checks for the memory location (or whether they are the same object) and does
not provide a indepth comparison inside the two string objects, whereas the equals () provides
indepth comparison of the string objects.

Eg.

String s = “Hello”;
String t = new String(”Hello”);

s == t // will return false since they are two different objects


s.equals (t) // will return true since the contents of the string objects are the same.

Searching Strings

The methods are used for searching a specified character in a string.

indexOf () - Searches for the first occurrence of a character or substring

lastIndexOf () – Searches for the last occurrence of a character or substring

Both of the above methods are overloaded in several ways and in all cases the methods return
the index at which the character of substring is found or –1 on failure.

int indexOf (ch) – where ch is the character being sought or


int indexOf (“the”) - a complete word.

Modifying a String

Because String objects are immutable, whenever you want to modify a String, you must either
copy it into a StringBuffer or use one of the following String methods, which will construct a new
copy of the string with your modifications complete.

substring ()

You can extract a part of the string using substring. The two forms of substring method are:

String substring (int start) – where start is the starting index

String substring (int start, int end) – where start is the start index and end is the ending index.

replace ()

The replace () method will replace all occurrences of one character in the invoking string with
another character. The general form is

String replace (char original, char replacement)

Changing Case of characters within a String

The two methods used for this purpose are:

String toLowerCase ()
String toUpperCase()

StringBuffer class
StringBuffer is a peer class of String that provides much of the functionality of strings. As you
know, String represents fixed-length, immutable character sequences. In contrast, StringBuffer
represents growable and writeable character sequence. StringBuffer may have characters
inserted into middle or appended to the end.

StringBuffer Constructors

StringBuffer () – This reserved room for 16 characters without reallocation.

StringBuffer (int size) – Here the size of the buffer is specified

StringBuffer (String s) – Here the size is the size of the String specified and reserves room for 16
more characters without reallocation.

Method Summary
StringBuffer append(char c)
Appends the string representation of the char argument to this string buffer.
StringBuffer append(int i)
Appends the string representation of the int argument to this string buffer.
StringBuffer append(Object obj)
Appends the string representation of the Object argument to this string buffer.
StringBuffer append(String str)
Appends the string to this string buffer.
int capacity()
Returns the current capacity of the String buffer. This gives you the number of
characters, which can be stored in the StringBuffer. In a simple constructor, this is
usually 16 characters.
char charAt(int index)
The specified character of the sequence currently represented by the string
buffer, as indicated by the index argument, is returned.
StringBuffer delete(int start, int end)
Removes the characters in a substring of this StringBuffer.
StringBuffer deleteCharAt(int index)
Removes the character at the specified position in this StringBuffer
(shortening the StringBuffer by one character).
void ensureCapacity(int minimumCapacity)
Ensures that the capacity of the buffer is at least equal to the specified
minimum. This is used when we want a minimum capacity and not the default 16
characters as specified.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this string buffer into the destination character
array dst.
StringBuffer insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
StringBuffer insert(int offset, Object obj)
Inserts the string representation of the Object argument into this string buffer.
StringBuffer insert(int offset, String str)
Inserts the string into this string buffer.
int length()
Returns the length (character count) of this string buffer. This gives only the
present length of the StringBuffer and this is no similar to capacity.
StringBuffer replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters in
the specified String.
StringBuffer reverse()
The character sequence contained in this string buffer is replaced by the
reverse of the sequence.
void setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch.
void setLength(int newLength)
Sets the length of this String buffer. This value is non-negative. It is important
to note here that if u set a length using setLength () less than what would have been
returned by length (), then the additional character will be lost.
String substring(int start)
Returns a new String that contains a subsequence of characters currently
contained in this StringBuffer.The substring begins at the specified index and
extends to the end of the StringBuffer.
String substring(int start, int end)
Returns a new String that contains a subsequence of characters currently
contained in this StringBuffer.

Math Class
The Math class contains all the functions that are used for geometry and trigonometry as well as
general-purpose methods.

Method Summary
static int abs(int a)
Returns the absolute value of an int value.
static long abs(long a)
Returns the absolute value of a long value.
static double acos(double a)
Returns the arc cosine of an angle, in the range of 0.0 through pi.
static double asin(double a)
Returns the arc sine of an angle, in the range of -pi/2 through pi/2.
static double atan(double a)
Returns the arc tangent of an angle, in the range of -pi/2 through pi/2.
static double atan2(double a, double b)
Converts rectangular coordinates (b, a) to polar (r, theta).
static double ceil(double a)
Returns the smallest (closest to negative infinity) double value that is not less
than the argument and is equal to a mathematical integer.
static double cos(double a)
Returns the trigonometric cosine of an angle.
static double exp(double a)
Returns the exponential number e (i.e., 2.718...) raised to the power of a
double value.
static double floor(double a)
Returns the largest (closest to positive infinity) double value that is not greater
than the argument and is equal to a mathematical integer.
static double log(double a)
Returns the natural logarithm (base e) of a double value.
static int max(int a, int b)
Returns the greater of two int values.
static double pow(double a, double b)
Returns of value of the first argument raised to the power of the second
argument.
static double random()
Returns a random number greater than or equal to 0.0 and less than 1.0.
static long round(double a)
Returns the closest long to the argument.
static double sin(double a)
Returns the trigonometric sine of an angle.
static double sqrt(double a)
Returns the square root of a double value.
static double tan(double a)
Returns the trigonometric tangent of an angle.

Example:

class MathExample {

public static void main(String args[]) {

int i = 7;
int j = -9;
double x = 72.3;
double y = 0.34;

System.out.println("i is " + i);


System.out.println("j is " + j);
System.out.println("x is " + x);
System.out.println("y is " + y);
/* The absolute value of a number is equal to the number if the number is positive or
zero and equal to the negative of the number if the number is negative.*/

System.out.println("|" + i + "| is " +


Math.abs(i));
System.out.println("|" + j + "| is " +
Math.abs(j));
System.out.println("|" + x + "| is " +
Math.abs(x));
System.out.println("|" + y + "| is " +
Math.abs(y));

/* You can round off a floating point number to the nearest integer
with round() */

System.out.println(x + " is approximately " +


Math.round(x));
System.out.println(y + " is approximately " +
Math.round(y));

/* The "ceiling" of a number is the smallest integer greater than or equal to


the number. Every integer is its own ceiling.*/

System.out.println("The ceiling of " + i +


" is " + Math.ceil(i));
System.out.println("The ceiling of " + j +
" is " + Math.ceil(j));
System.out.println("The ceiling of " + x +
" is " + Math.ceil(x));
System.out.println("The ceiling of " + y +
" is " + Math.ceil(y));

/* The "floor" of a number is the largest integer less than or equal


to the number. Every integer is its own floor.*/

System.out.println("The floor of " + i +


" is " + Math.floor(i));
System.out.println("The floor of " + j +
" is " + Math.floor(j));
System.out.println("The floor of " + x +
" is " + Math.floor(x));
System.out.println("The floor of " + y +
" is " + Math.floor(y));

// min() returns the smaller of the two arguments you pass it

System.out.println("min(" + i + "," + j +
") is " + Math.min(i,j));
System.out.println("min(" + x + "," + y +
") is " + Math.min(x,y));
System.out.println("min(" + i + "," + x +
") is " + Math.min(i,x));
System.out.println("min(" + y + "," + j +
") is " + Math.min(y,j));
/* There's a corresponding max() method that returns the
larger of two numbers */

System.out.println("max(" + i + "," + j +
") is " + Math.max(i,j));
System.out.println("max(" + x + "," + y +
") is " + Math.max(x,y));
System.out.println("max(" + i + "," + x +
") is " + Math.max(i,x));
System.out.println("max(" + y + "," + j +
") is " + Math.max(y,j));

// The Math library defines a couple of useful constants:

System.out.println("Pi is " + Math.PI);


System.out.println("e is " + Math.E);

// Trigonometric methods - All arguments are given in radians

// Convert a 45 degree angle to radians

double angle = 45.0 * 2.0 * Math.PI/360.0;

System.out.println("cos(" + angle +
") is " + Math.cos(angle));
System.out.println("sin(" + angle +
") is " + Math.sin(angle));

// Inverse Trigonometric methods - All values are returned as radians

double value = 0.707;

System.out.println("acos(" + value +
") is " + Math.acos(value));
System.out.println("asin(" + value +
") is " + Math.asin(value));
System.out.println("atan(" + value +
") is " + Math.atan(value));

// Exponential and Logarithmic Methods

// exp(a) returns e (2.71828...) raised to the power of a.

System.out.println("exp(1.0) is " +
Math.exp(1.0));
System.out.println("exp(10.0) is " +
Math.exp(10.0));
System.out.println("exp(0.0) is " +
Math.exp(0.0));

// log(a) returns the natural logarithm (base e) of a.

System.out.println("log(1.0) is " +
Math.log(1.0));
System.out.println("log(10.0) is " +
Math.log(10.0));
System.out.println("log(Math.E) is " +
Math.log(Math.E));

// pow(x, y) returns the x raised to the yth power.

System.out.println("pow(2.0, 2.0) is " +


Math.pow(2.0,2.0));
System.out.println("pow(10.0, 3.5) is " +
Math.pow(10.0,3.5));
System.out.println("pow(8, -1) is " +
Math.pow(8,-1));

// sqrt(x) returns the square root of x.

for (i=0; i < 10; i++)


{
System.out.println("The square root of " +
i + " is " + Math.sqrt(i));
}

/*Finally there's one Random method that returns a random number


between 0.0 and 1.0 */

System.out.println(
"Here's one random number: " + Math.random());

System.out.println(
"Here's another random number: " +
Math.random());
}
}
/*
(Dev, i have cut and pasted the output for your reference)

Here's the output.

i is 7
j is -9
x is 72.3
y is 0.34
|7| is 7
|-9| is 9
|72.3| is 72.3
|0.34| is 0.34
72.3 is approximately 72
0.34 is approximately 0
The ceiling of 7 is 7
The ceiling of -9 is -9
The ceiling of 72.3 is 73
The ceiling of 0.34 is 1
The floor of 7 is 7
The floor of -9 is -9
The floor of 72.3 is 72
The floor of 0.34 is 0
min(7,-9) is -9
min(72.3,0.34) is 0.34
min(7,72.3) is 7
min(0.34,-9) is -9
max(7,-9) is 7
max(72.3,0.34) is 72.3
max(7,72.3) is 72.3
max(0.34,-9) is 0.34
Pi is 3.14159
e is 2.71828
cos(0.785398) is 0.707107
sin(0.785398) is 0.707107
acos(0.707) is 0.785549
asin(0.707) is 0.785247
atan(0.707) is 0.615409
exp(1.0) is 2.71828
exp(10.0) is 22026.5
exp(0.0) is 1
log(1.0) is 0
log(10.0) is 2.30259
log(Math.E) is 1
pow(2.0, 2.0) is 4
pow(10.0, 3.5) is 3162.28
pow(8, -1) is 0.125
The square root of 0 is 0
The square root of 1 is 1
The square root of 2 is 1.41421
The square root of 3 is 1.73205
The square root of 4 is 2
The square root of 5 is 2.23607
The square root of 6 is 2.44949
The square root of 7 is 2.64575
The square root of 8 is 2.82843
The square root of 9 is 3
Here's one random number: 0.820582
Here's another random number: 0.866157
*/

Calendar Class
The abstract Calendar class provides a set of methods that allows you to convert a time in
milliseconds to a number of useful components. Calendar is an abstract base class for converting
between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so
on. (A Date object represents a specific instant in time with millisecond precision.

Subclasses of Calendar interpret a Date according to the rules of a specific calendar system. The
JDK provides one concrete subclass of Calendar: GregorianCalendar. Future subclasses could
represent the various types of lunar calendars in use in many parts of the world.

It is intended that the subclasses of Calendar will provide the specific functionality to interpret
time information according to their own rules. This is one aspect of the java class library that
enables you to write programs that can operate in several international environments. An
example of such a class is GregorianCalender. Calendar has no public constructors and has
several protected instance variables.
GregorianCalender Class
GregorianCalender is a concrete implementation of a Calendar that implements the normal
Gregorian calendar with which you are familiar. The getInstance () method of the Calendar
returns a GregorianCalendar initialised with the current date and time in the default locale and
time zone.

The default constructor initializes the object with the current date and time in the default locale
and time zone. The other constructors are

GregorianCalendar (int year, int month, int dayofmonth)

GregorianCalendar (int year, int month, int dayofmonth, int minutes)

GregorianCalendar (int year, int month, int dayofmonth, int minutes, int seconds)

Here the year specifies the number of years that have elapsed since 1900 and the month starts
with 0 indicating January.

The Object and Class Class


Object and Class are two of the most important classes in the Java API. The Object class is at the
top of the Java class hierarchy. All classes are subclasses of Object and therefore inherit its
methods. The Class class is used to provide class descriptors for all objects created during Java
program execution.

Object

The Object class does not have any variables and has only one constructor. However, it provides
11 methods that are inherited by all Java classes and that support general operations that are
used with all objects. For example, the equals() and hashCode() methods are used to construct
hash tables of Java objects.

Hash tables are like arrays, but they are indexed by key values and dynamically grow in size.
They make use of hash functions to quickly access the data that they contain. The hashCode()
method creates a hash code for an object. Hash codes are used to quickly determine whether
two objects are different.

The clone() method creates an identical copy of an object. The object must implement the
Cloneable interface. This interface is defined within the java.lang package. It contains no methods
and is used only to differentiate cloneable from noncloneable classes.

The getClass() method identifies the class of an object by returning an object of Class. You'll
learn how to use this method in the next programming example.

The toString() method creates a String representation of the value of an object. This method is
handy for quickly displaying the contents of an object. When an object is displayed, using print()
or println(), the toString() method of its class is automatically called to convert the object into a
string before printing. Classes that override the toString() method can easily provide a custom
display for their objects.

The finalize() method of an object is executed when an object is garbage-collected. The method
performs no action, by default, and needs to be overridden by any class that requires specialized
finalization processing.
The Object class provides three wait() and two notify() methods that support thread control.
These methods are implemented by the Object class so that they can be made available to
threads that are not created from subclasses of class Thread. The wait() methods cause a thread
to wait until it is notified or until a specified amount of time has elapsed. The notify() methods are
used to notify waiting threads that their wait is over.

Class

The Class class provides eight methods that support the runtime processing of an object's class
and interface information. This class does not have a constructor. Objects of this class, referred to
as class descriptors, are automatically created and associated with the objects to which they
refer. Despite their name, class descriptors are used for interfaces as well as classes.

The getName() and toString() methods return the String containing the name of a class or
interface.

The getSuperclass() method returns the class descriptor of the superclass of a class. The
isInterface() method identifies whether a class descriptor applies to a class or an interface. The
getInterface() method returns an array of Class objects that specify the interfaces of a class, if
any.

The newInstance() method creates an object that is a new instance of the specified class. It can
be used in lieu of a class's constructor, although it is generally safer and clearer to use a
constructor rather than newInstance().

The getClassLoader() method returns the class loader of a class, if one exists. Classes are not
usually loaded by a class loader. However, when a class is loaded from outside the CLASSPATH,
such as over a network, a class loader is used to convert the class byte stream into a class
descriptor.

The ClassLoader, SecurityManager, and Runtime Classes

The ClassLoader, SecurityManager, and Runtime classes provide a fine level of control over the
operation of the Java runtime system. However, most of the time you will not need or want to
exercise this control because Java is set up to perform optimally for a variety of applications. The
ClassLoader class allows you to define custom loaders for classes that you load outside of your
CLASSPATH-for example, over a network. The SecurityManager class allows you to define a
variety of security policies that govern the accesses that classes may make to threads,
executable programs, your network, and your file system. The Runtime class provides you with
the capability to control and monitor the Java runtime system. It also allows you to execute
external programs.

ClassLoader

Classes that are loaded from outside CLASSPATH require a class loader to convert the class
byte stream into a class descriptor. ClassLoader is an abstract class that is used to define class
loaders. It uses the defineClass() method to convert an array of bytes into a class descriptor. The
loadClass() method is used to load a class from its source, usually a network. The resolveClass()
method resolves all the classes referenced by a particular class by loading and defining those
classes. The findSystemClass() method is used to load classes that are located within
CLASSPATH and, therefore, do not require a class loader.

SecurityManager
The SecurityManager class is an abstract class that works with class loaders to implement a
security policy. It contains several methods that can be overridden to implement customized
security policies. For right now, just be aware that it is in java.lang.

Runtime

The Runtime class provides access to the Java runtime system. It consists of a number of
methods that implement system-level services.

The getRuntime() method is a static method that is used to obtain access to an object of class
Runtime.

The totalMemory(), freeMemory(), and gc() methods are used to obtain information about and
control the memory used by the runtime system. The totalMemory() method identifies the total
memory available to the runtime system. The freeMemory() method identifies the amount of free
(unused) memory. The gc() method is used to run the garbage collector to free up memory
allocated to objects that are no longer being used. In general, you should not use the gc()
method, but rather let Java perform its own automated garbage collection.

The getLocalizedInputStream() and getLocalizedOutputStream() methods are used to convert


local (usually ASCII) input and output streams to Unicode-based streams. The load() and
loadLibrary() methods are used to load dynamic link libraries. This is usually performed in
conjunction with native methods.

The runFinalization() method causes the finalize() method of each object awaiting finalization to
be invoked. The traceInstructions() and traceMethodCalls() methods are used to enable or
disable instruction and method tracing. You will most likely never need to use any of these
methods in your programs. They are used in programs such as the debugger to trace through the
execution of Java methods and instructions.

Using Runtime

Most of the methods provided by Runtime are not typically used in application
programs. However, some methods are pretty useful. The program shows how the
Runtime methods can be used to display memory status information.

The source code of the RuntimeMemApp program.


import java.lang.System;
import java.lang.Runtime;
import java.io.IOException;

public class RuntimeMemApp {


public static void main(String args[]) throws IOException {
Runtime r = Runtime.getRuntime();
System.out.println(r.totalMemory());
System.out.println(r.freeMemory());
}
}
This program uses the static getRuntime() method to get an instance of Runtime that
represents the current Java runtime system. The totalMemory() method is used to
display the total number of bytes of runtime system memory. The freeMemory()
method is used to display the number of bytes of memory that are unallocated and
currently available.
When you run the program, you should get results that are similar to the following:

3145720
3135888

The System Class

You are no stranger to the System class because you have used it in several previous
programming examples. It is one of the most important and useful classes provided by java.lang.
It provides a standard interface to common system resources and functions. It implements the
standard input, output, and error streams, and supplies a set of methods that provide control over
the Java runtime system. Some of these methods duplicate those provided by the Runtime class.

Security Manager-Related Methods

The getSecurityManager() and setSecurityManager() methods provide access to the security


manager that is currently in effect.

Runtime-Related Methods

Several of the methods defined for the Runtime class are made available through the System
class. These methods are exit(), gc(), load(), loadLibrary(), and runFinalization().

Enumeration Interface

The Enumeration Interface facilitates a standard mechanism to retrieve elements across the
different data structures in the util package. The Enumeration Interface defines the method by
which you can enumerate (obtain one at a time) the elements in a collection of objects.

boolea hasMoreElements()
n Tests if this enumeration contains more elements.
Object nextElement()
Returns the next element of this enumeration if this enumeration object has
at least one more element to provide.

TimeZone

TimeZone represents a time zone offset, and also figures out daylight savings. Typically,
you get a TimeZone using getDefault which creates a TimeZone based on the time zone
where the program is running. For example, for a program running in Japan, getDefault
creates a TimeZone object based on Japanese Standard Time.

static TimeZon getDefault()


e Gets the default TimeZone for this host.

static voi setDefault(TimeZone zone)


d Sets the TimeZone that is returned by the getDefault method.
Simple Time Zone

SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use
with a Gregorian calendar. This class does not handle historical changes.

Das könnte Ihnen auch gefallen