Anda di halaman 1dari 21

Class Class

- This encapsulates the runtime state of an object or an interface

- This is creates automatically and cannot be created explicitly.

- We can obtain a handle to the Class object with the method getClass ().

- The Reflection API uses this Class a lot and because of this Class only
Reflection API is possible.

- We have used the method String getName () – Returns the name of the
object as a String

Class Math
- All the methods of this class, which performs basic numeric operations, are
static.

The Important Methods of this class are:

1) static double ceil (double a) –

2) static double floor (double a) –

3) static double random() – This generates a number between 0.0 but


less than 1.0

4) static double sqrt (double a) – This returns the square root of the
double parameter.

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());
}
}
/*
(Friends , 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
*/

Class Runtime
- This class encapsulates the Runtime Environment

- This class also cannot be instantiated

- We can get a handle to the Runtime Class by the static method getRuntime
().

- The main use of this class is to create other processes by calling the exec ()
method.

Example:

class RuntimeExec
{
public static void main(String[] args)
{
Runtime r = Runtime.getRuntime();
Process p = null;

try
{
p = r.exec("notepad.exe");
}
catch(Exception e)
{
System.out.println("Error executing notepad");
}
System.out.println("This is after closing the notepad window");
}
}

- The exit (int i) method in this class terminates the JVM and the conventional
way of calling this method is through System.exit(0).

- The loadLibrary () method loads a native library and the conventional way of
using this is System.loadLibrary ().

- The other two methods are totalMemory () and freeMemory (), which will tell
us the memory available in the object heap.

Example:

class Memory
{
public static void main(String[] args)
{
Runtime r = Runtime.getRuntime();
long a,b;
Integer c[] = new Integer[1000];

System.out.println("Total Memory available is :" + r.totalMemory());

a = r.freeMemory();

System.out.println("Initial Free Memory is :" + a);


r.gc();

a = r.freeMemory ();

System.out.println("Free Memory after Garbage Collection is :" + a);

for (int i = 0;i<1000;i++)


{
c[i] = new Integer(i); // allocating Integers
}

b = r.freeMemory();
System.out.println("Free Memory after allocation :" + b);

System.out.println("Memory used by allocation :" + (a-b));

for (int i = 0;i<1000;i++)


{
c[i] = null; // discarding Integers
}

r.gc(); // only requesting Garbage Collection

b = r.freeMemory();

System.out.println("Free Memoryafter collection and discarding integers is :" + b);

}
}

Class Vector
- 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

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

- Vector (int initialCapacity) – Constructs a empty vector with the specified


storage capacity.

- 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 11th 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. – Same result as the add method.
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.
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.
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.
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.
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.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();
}
}

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.

boolean hasMoreElements()
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.

Random Class
- The Random class provides a template for the creation of random number
generators.

- It differs from the random () method of the java.lang.Math class in that it


allows any number of random number generators to be created as separate
objects.

- The Math. Random () method provides a static function for the generation of
random double values. This static method is shared by all program code.
- The Random class provides six access methods, five of which are used to
generate random values.

- The nextInt(), nextLong(), nextFloat(), and nextDouble() methods generate


values for the numeric data types. The values generated by nextFloat() and
nextDouble() are between 0.0 and 1.0.

Example:

import java.util.Random;

public class RandomApp


{
public static void main(String args[])
{
Random r = new Random();

for(int i=0;i<4;++i) System.out.println(r.nextInt()+" ");


System.out.println();

r = new Random(123456789);
for(int i=0;i<4;++i) System.out.println(r.nextDouble()+" ");
System.out.println();

r.setSeed(234567890);
for(int i=0;i<4;++i) System.out.println(r.nextGaussian()+" ");
System.out.println();
}
}

Class StringTokenizer
- The StringTokenizer class is used to create a parser for String objects.

- It parses strings according to a set of delimiter characters. It implements the


Enumeration interface in order to provide access to the tokens contained
within a string.

StringTokenizer provides three constructors.

1) StringTokenizer (String s) – This uses the default delimiter sets like


space, tab, carriage return characters etc.

2) StringTokenizer (String s, String delimiter) – This parses the String


object in the first parameter using the delimiter specified in the second
parameter.
3) StringTokenizer (String s, String delimiter, Boolean b) – This does the
same thing as the 2nd constructor, but determines whether the delimiter
specified should also be returned as a token or not.

The Important methods in this are:

1) boolean hasMoreTokens () – This will determine if there is any pending


token in the String which is being parsed.

2) String nextToken() – This will return the next token in the string,
separated by the specified or default delimiter.

3) int countTokens() – This returns the number of tokens being parsed in


the String.

Example

import java.util.*;
import java.io.*;

public class TokenApp


{
public static void main(String args[]) throws IOException
{
DataInputStream keyboardInput = new DataInputStream(System.in);
int numTokens;
do {
System.out.print("=> ");
System.out.flush();
StringTokenizer st = new StringTokenizer(keyboardInput.readLine());
numTokens = st.countTokens();
System.out.println(numTokens+" tokens");

while (st.hasMoreTokens())
System.out.println(" "+st.nextToken());
} while(numTokens!=0);
}
}

Class Object
- This is the super class of all java classes.

The Important Methods in this class are:


1) clone () – This generates a duplicate copy of the object and only
classes which implement the Cloneable interface can be cloned,
otherwise a CloneNotSupportedException will be thrown. Also since
this is a compile time exception, even after implementing the
Cloneable interface, we will have to put it in a try and catch block.

2) equals () – This compares the memory location of both objects.

3) hashcode() – This will give the memory location of the object and the
equals () method uses this method for comparison.

4) protected void finalize () – called by the Garbage Collector.

Class Date
- The class Date represents the specific date with millisecond precision.

The two Constructors are

1) Date () – gives u the current date


2) Date (long date) – allows u to initialize a date object with a specified
number of milliseconds since the base date i.e., 1st January 1970
00:00:00 GMT

The Important methods are:-

1) long getTime() – gives u the milliseconds passed since the base


period. This can be used for calculation purposes between dates.

2) String toString () –

3) boolean after(Date d) – This will return true if the invoking date is later
than the Date in the parameter.

4) boolean before(Date d) –

5) int compareTo (Date d) - the value 0 if the argument Date is equal to


this Date; a value less than 0 if this Date is before the Date argument;
and a value greater than 0 if this Date is after the Date argument.

Class DateFormat
- This is the abstract class for formatting and parsing dates and times.
- The static getDateInstance (int style, Locale locale) method returns a handle
to the DateFormat class by which we can format dates. The options for style
are DEFAULT, SHORT, MEDIUM, LONG AND FULL. The locale gives u a
static reference defined in the Locale class.

- If no parameters are passed, the defaults are used.

- The most common method in this class is the String format(Date d).

Example:

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

class DateFormat1
{
public static void main(String[] args)
{
Date d = new Date();
DateFormat df;

df = DateFormat.getDateInstance(DateFormat.SHORT);
System.out.println("The day in India is now :"+df.format(d));

df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.FRANCE);
System.out.println("The day in Japan is now :"+df.format(d));

df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.UK);
System.out.println("The day in UK is now :"+df.format(d));

df = DateFormat.getDateInstance(DateFormat.LONG, Locale.KOREA);
System.out.println("The day in KOREA is now :"+df.format(d));
}
}

The getTimeInstance () method returns an instance of DateFormat that can


format time information. It also has the same parameters like the
getDateInstance () method.

Class SimpleDateFormat
- This is the concrete class for formatting dates. This extends the DateFormat
class.
- First of all u will have to create a instance of SimpleDateFormat giving in the
parameters how u want to format the date or time and then use the format ()
for this purpose.

Example:

class SimpleDateFormat1
{
public static void main(String[] args)
{
Date d = new Date();
SimpleDateFormat sdf;

sdf = new SimpleDateFormat("hh:mm:ss");


System.out.println(sdf.format(d));

sdf = new SimpleDateFormat("dd MMM yyyy hh:mm zzz");


System.out.println(sdf.format(d));

sdf = new SimpleDateFormat("E MMM dd yyyy");


System.out.println(sdf.format(d));
}
}

Another Example

// Trying date formatting


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

public class TryDateFormats


{
public static void main(String[] args)
{
Date today = new Date();
Locale[] locales = {Locale.US, Locale.UK,
Locale.GERMANY, Locale.FRANCE };

int[] styles = { DateFormat.FULL,DateFormat.LONG,


DateFormat.MEDIUM,DateFormat.SHORT, DateFormat.DEFAULT};
DateFormat fmt;
String[] styleText = { "FULL", "LONG", "MEDIUM", "SHORT","DEFAULT",};

// Output the date for each local in four styles


for(int i = 0; i < locales.length; i++)
{
System.out.println("\nThe Date for " +
locales[i].getDisplayCountry() + ":");
for(int j = 0; j < styles.length; j++)
{
fmt = DateFormat.getDateInstance(styles[j], locales[i]);
System.out.println( "\tIn " + styleText[j] +
" is " + fmt.format(today));
}
}
}
}

Class Calender
- 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.

- The most important method is the int get(field), which will return the various
fields. The GregorianCalender uses this the most.

Class GregorianCalender
- We have 7 constructors, which create a GregorianCalender with the current
date and time and default locale etc.

- Once we have a GregorianCalender object, we can get the various fields


defined in the Calender Class. For Example.

GregorianCalender gc = new GregorianCalender ().

Date d = gc.getTime () // this will get us the current instant in time. We can also
use the setTime ().

int day = gc.get (gc.DAY_OF_WEEK); // the DAY_OF_WEEK is a constant in the


Calender class.

Incase we want to alter the current instant in the calendar we can use the add ()
method which has 2 parameters int field and int amount. so

gc.add(gc.YEAR, 14) // we will be 14 years in future.

If we want to increment or decrement a field of the Calender by 1, we can use the


roll () method, which will also have two parameters, int field and boolean value,
so we can go back one month like third.

gc.roll(gc.MONTH,false) // go back one month.


Class Arrays
This class is mostly used for sorting and searching. It has methods used for
sorting most of the primitive data types. The most common method for sort is

sort (datatype []) – sorts in a ascending numerical order


sort (datatype [], int fromindex, int toindex)

Anda mungkin juga menyukai