Vous êtes sur la page 1sur 119

EXCEPTION HANDLING

OR
ERROR HANDLING
1

What is Error?
- Error means mistakes or buggs
- Error is classified into types
Error

Compile Time
Error
All syntax errors will be detected
And displayed by the Java compi
ler and therefore these errors
Are known as compile time
errors

1. Missing Semicolon
2. Missing brackets in classes
and methods
3. Use of undeclared variables

Run Time
Error
A program may compile success
fully creating the .exe file but
not run properly. Such programs
may produce wrong results due
to wrong loaic or may terminate
due to errors

1. Dividing an integer by zero


2. Accessing an element that is out of
2
the bounds of an array

Some Example of Runtime Errors


class Error_Handling
{
public static void main(String args[])
{
int a,b,c;
a = 10;
b = 0;
c = a / b;
System.out.println("The Value of the C Value is:" + c);
}
}
Output:
/ by zero
3

Exception Types
1. All Exception types are subclasses of the built in class Throwable. Throwable is at
the top of the exception class hierarchy

Throwable

Exception
(or)
RuntimeException

This class is used for exceptional conditions that


user programs should catch. This is also the class
That you will subclass to create your own custom
exception types

Error

Which defines exceptions that are not


Expected to be caught under normal
Circumstances by our program.
Ex. Stack overflow

Uncaught Exception
class Error_Handling
{
public static void main(String args[])
{
int i,j,k1,k2;
i = 10;
j = 0;
k1 = i / j;
k2 = i + j;
System.out.println("The Division of the K1 Value is: " + k1);
System.out.println("The addition of the K2 Value is: " + k2);
}
}
Output:
java.lang.ArithmeticException: / by zero
at Error_Handling.main(Error_Handling.java:4)
In this example, we havent supplied any exception handlers of our own, so5 the
exception is caught by the default handler provided by the java run time system

What is Exceptions?
An Exception is condition that is caused by a run time error in the program.
What is Exception Handling?
If the exception object is not caught and handled properly, the compiler will
display an error message and will terminate the program. If we want the program to
continue with the execution of the remaining appropriate message for taking
corrective actions. This task is known as exception handling.
Exceptions Types
Exception
Synchronous
Exception

1. Division by Zero

Asynchronous
Exception

1. Keyboard Interrupt
2. Mouse Interrupt
6

Exception Handling Mechanism


The purpose of the exception handling mechanism is to provide means to
detect and report an exceptional circumstance, so that appropriate action can be
taken.
The Error Handling code that performs the following tasks:
1. Find the problem (Hit the Exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
try block
Detects and throws an
exception

catch block
Exception object

Catches and handles the


exception

Using try and catch


----------------------------------try
{
-------------------------------------

//Block of statements which detects and


//throws an exception

}
catch(Exception_Type e)

//Catches exception

{
---------------------------

//Block of statements that handles the


//exception

}
-----------------------------------

Example Program for Exception Handling Mechanism


class Error_Handling
{
public static void main(String args[])
{
int i,j,k1,k2;
i = 10;
j = 0;
try
{

There is an Exception
k1 = i / j;
System.out.println("The Division of the K1 Value is: " + k1);

}
catch(ArithmeticException e)
Catches the exception
{
System.out.println("Division by Zero");
}
k2 = i + j;
System.out.println("The addition of the K2 Value is: " + k2);
}
}

Output: Division by Zero, The addition of the K2 Value is:10

Multiple Catch Statements


It is possible that a program segment has more than one condition to throw
an exception.
try
{
//statements
}
catch(Exception-Type-1 e)
{
//statements
}
catch(Exception-Type-2 e)
{
//statements
}
--------------------catch(Exception-Type-N e)
{
//statements
}

10

class Error_Handling
{
public static void main(String args[])
{
int a[ ] = {5,10};
int b = 5;
try
{
int x = a[2] / b - a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
int y = a[1] / a[0];
System.out.println("Y = " + y);
}
}

11

COMMAN EXCEPTION HANDLER


class Error_Handling
{
public static void main(String args[])
{
int a[ ] = {5,10};
int b = 5;
try
{
int x = a[2] / b - a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
}
/*catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Error");
}*/
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}

12

catch(Exception e)
{
System.out.println("The Producing any Runtime Error" +
e.getMessage());
}
int y = a[1] / a[0];
System.out.println("Y = " + y);
}
}

13

EXCEPTION HIERARCHY
class Error_Handling
{
public static void main(String args[])
{
int a[ ] = {5,10};
int b = 5;
try
{
int x = a[2] / b - a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
}

catch(Exception e)
{
System.out.println("The Producing any Runtime Error" +
e.getMessage());
}
/*catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Error");
}*/

14

catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
int y = a[1] / a[0];
System.out.println("Y = " + y);
}
}

15

Nested try Statements


class Error_Handling
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 42 / a; //If no command - line args are
present, //the following statement will generate a divide - by - zero exception
System.out.println("a = " + a);
// nested try bloack
// If one command - line arg is used, then a divide by //- zero exception will be generated by the following code.

16

try
{
if ( a == 1)
a = a / (a - a); //division by zero
if(a == 2)
{
int c[] = {1};
c[42] = 99; //generate an out - of - bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out - of - bounds: " + e);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by Zero: " + e);
}
}
}
17

Nested try Statements using Subroutine


class Error_Handling
{
static void nesttry(int a)
{
try
{
if ( a == 1)
a = a / (a - a); //division by zero
if(a == 2)
{
int c[] = {1};
c[42] = 99; //generate an out - of - bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out - of - bounds: " + e);
}
}
18

public static void main(String args[])


{
try
{
int a = args.length;
int b = 42 / a; //If no command - line args are present, the
//following statement will generate a divide - by - zero exception
System.out.println("a = " + a);
// nested try bloack
// If one command - line arg is used, then a divide - by //zero exception will be generated by the following code.
nesttry(a);

// Calling Static Method

}
catch(ArithmeticException e)
{
System.out.println("Divide by Zero: " + e);
}
}
}

19

throw
1. You have only been catching exceptions that are thrown by the java run time
system.
2. However, it is possible for your program to throw an exception explicitly. Using
throw statement.
Syntax:
throw ThrowableInstance;
1. Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
2. Simple types, such as int or char, as well as non Throwable classes, such as
String and Object, cannot be used as exception.
3. There are two ways you can obtain a Throwable object: using a parameter into a
catch clause, or creating one with the new operator.

20

class Error_Handling
{
static void display()
{
try
{
throw new NullPointerException("Demo");
}
catch(NullPointerException e)
{
throw e;
}
}
public static void main(String args[])
{
try
{
display();
}
catch(NullPointerException e)
{
System.out.println("Recaught : " + e);
}
}
}

21

throws
1. If a method is capable of causing an exception that it does not handle, it must
specify this behavior so that callers of the method can guard themselves against
that exception.
2. You do this by including a throws clause in the methods declaration. A throws
clause list the types of exceptions that a method might throw.
3. This is necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses. All other exceptions that a method
can throw must be declared in the throws clause.
4. If they are not, a compile time error will result.

type method-name (parameter-list) throws exception-list


{
//body of method
}
Here, exception list is comma separated list of the exceptions that a method
can throw
22

class Error_Handling
{
static void throwdemo() throws IllegalAccessException
{
System.out.println("Inside throwdemo");
}
public static void main(String args[])
{
try
{
throwdemo();
}
catch(IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}

23

Using finally Statement


1. Java supports another statement known as finally statement that can be used to handle
an exception that is not caught by any of the previous catch statements.
2. finally block can be used to handle any exception generated within a try block.
3. It may be added immediately after the try block or after the last catch block.
try
{

try
{
//statements
}
finally
{
------------------------------------}

//statements
}
catch(Exception-Type-1 e)
{
//statements
}
catch(Exception-Type-2 e)
{
//statements
}
--------------------catch(Exception-Type-N e)
{
//statements
}
finally
{
------------------------------------}

24

class Error_Handling
{
static void procA()
{
try
{
System.out.println("Inside ProcA");
throw new RuntimeException("demo");
}
finally
{
System.out.println("ProcA's finally");
}
}
static void procB()
{
try
{
System.out.println("inside ProcB");
//return;
}
finally
{
System.out.println("ProcB's finally");
}
}

25

static void procC()


{
try
{
System.out.println("inside ProcC");
}
finally
{
System.out.println("ProcC's finally");
}
}
public static void main(String args[])
{
try
{
procA();
}
catch(Exception e)
{
System.out.println("Exception Caught");
}
finally
{
System.out.println("Procedure A is Wind up");
}
procB();
procC();
} }

26

Javas Built in Exceptions


1. The standard package java.lang, Java defines several exception classes. A few have
been used by the preceding examples.

2. The most general of these exceptions are subclasses of the standard type
RuntimeException.

3. Since java.lang is implicitly imported into all java programs, most exceptions
derived from RuntimeException are automatically available.

4. Furthermore, they need not be included in any methods throws list.

5. In the language of Java, these are called unchecked exceptions because the
compiler does not check to see if a method handles or throws these exceptions.

6. The other exceptions defined by java.lang that must be included in a methods


throws list if that method can generate one of these exceptions and does not
handle it itself. These are called checked exceptions.
27

Javas Unchecked RuntimeException Subclasses


Exception

Meaning

ArithmeticException

Arithmetic error, such as divde by


zero

ArrayIndexOutOfBoundsException

Array index is out of bounds.

ArrayStoreException

Assignment to an array element of an


incompatible type.

ClassCastException

Invalid Cast.

IllegalArgumentException

Illegal argument used to invoke a


method

IllegalMonitoStateException

Illegal Monitor Operation, such as


waiting on an unlocked thread.

IllegalStateException

Environment or
incorrect state.

IllegalThreadStateException

Requested operation not compatible


with current thread state.

IndexOutOfBoundsException

Some type of index is out of


bounds

NegativeArraySizeException

Array Created with a negative size.

application

is

in

28

Exception

Meaning

NullPointerException

Invalid use of a null reference.

NumberFormatException

Invalid conversion of a string to a


numeric format.

SecurityException

Attempt to violate security

StringIndexOutOfBounds

Attempt to index outside the bounds of


a string.

UnsupportedOperationException

An unsupported
encountered.

Operation

was

29

Javas Checked Exception Defined in java.lang


Exception

Meaning

ClassNotFoundException

Class not found

CloneNotSupportedException

Attempt to clone an object that does


not implement the cloneable interface.

IllegalAccessException

Access to a class is denied

InstantiationException

Attempt to create an object of an


abstract class or interface

InterruptedException

One thread has been interrupted by


another thread.

NoSuchFieldException

A requested field does not exist.

NoSuchMethodException

A requested method does not exist.

30

Throwing our own Exceptions


There may be times when we would like to throw our own exceptions. We can do this
by using the keyword throw as follows:

throw new Throwable_subclass;

Example:
throw new ArithmeticException();
throw new NumberFormatException();

Note:
1. Exception is subclass of Throwable and therefore MyException is a subclass
of Throwable class.
2. An object of a class that extends Throwable can be thrown and caught
31

import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class Exception_Handling
{
public static void main(String args[])
{
int x = 5, y = 1000;
try
{
float z = (float) x / (float) y;
if (z < 0.01)
{
throw new MyException("Number is too small");
32
}

catch(MyException e)
{
System.out.println("Caught my exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am always here");
}
}
}

33

Using Exceptions
1. Exception handling provides a powerful mechanism for controlling complex programs
that have many dynamic run time characteristics.
2. It is important to think of try, throw and catch as clean ways to handle errors and
unusual boundary conditions in your programs logic.
3. If you are like most programmers, then you probably are used to returning an error
code when a method fails.
4. When you are programming in Java, you should break this habit. When a method can
fail, have it throw an exception.
5. This is a cleaner way to handle failure modes.
6. One last point: Javas Exception handling statements should not be considered a
general mechanism for nonlocal branching.
7. If you do so, it will only confuse your code and make it hard to maintain.

34

String in Java

String:
Javas String type called String, is not a Simple Type, nor is it simply an
array of characters. Rather String defines an Object.
The String type is used to declare string variable.
Java Strings are sequences of Unicode Characters.
Use an object of type string as an argument to println();
String str = Welcome to JAVA;
System.out.println(str);
Implementing strings as built-in objects allows java to provide a full
complement of features that make string handling convenient.
Java has methods to compare two strings, search for a substring,
concatenate two strings, and change the case of letters within a String.
String object has been created, you cannot change the characters that
comprise that string.
String Constructors:
The String class supports several constructors. To create an empty string call
the default constructor.
String str = new String();
Initialize the values through array of characters.
char ch[] = {a,b,c};
String str = new String(ch);
o/p: abc
1. Subrange:
String(char ch[], int start,int numchar);
char ch[] = {a,b,c,d,e,f};
String s = new String(ch,2,3);
o/p: cde

String in Java

String functions in Java

String functions in Java

String functions in Java

String functions in Java

String functions in Java

2. String copy:
String(String strobj);
char ch[] ={J,A,V,A};
String s1 = new String(ch);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);

O/P: JAVA
O/P: JAVA

3. ASCII char:
String (byte asciichars[]);
String(byte asciichars[], int start, int numchars);
byte ascii[] ={65,66,67,68,69,70};
String s1 = new String(ascii);
System.out.println(s1);
O/P: ABCDEF
String s2 = new String(ascii,2,3);
System.out.println(s2);
O/P: CDE

SPECIAL STRING OPERATIONS


1. Automatic creation of new String instances from string literals.
2. Concatenation of multiple String object by used of the + operators
3. Literals
Conversion of other data types to a string representation.
1. String
Assigning values to the object.
Syntax:
String obj = value;
class String_Operation
{
public static void main(String args[])
{
char chars [ ] = {'a', 'b', 'c'};
String s1 = new String(chars);
String s2 = "Chettinad";
automatically

//Use

String

Literals,

//constructs a String object


System.out.println("The Displayed String_1 is:" + s1);
System.out.println("The Displayed String_2 is:" + s2);
System.out.println("The Length of the String is: " +
"Chettinad".length());
}

Java

2. String Concatenation
class String_Operation
{
public static void main(String args[])
{
String age = " 9 ";
String s = "He is" + age + "Years old."; //Java does allow ( +
// )operators to be
// applied to String
// objects.
System.out.println(s);
}
}

3. String Concatenation with Other Data Types


class String_Operation
{
public static void main(String args[])
{
int age = 9;
String s1 = "He is " + age + " Years old. ";
/* The int value in age is automatically converted into its string
representation within a String object. */
System.out.println(s1);
String s2 = "four: " + 2 + 2;
System.out.println(s2);
String s3 = "four: " + (2 + 2);
System.out.println(s3);
}
}

4. String Conversion and toString()


To implement toString(), simply return a String object that contains the
human readable string.
class Box
{
double width;
double height;
double depth;
Box(double w,double h,double d)
{
width = w;
height = h;
depth = d;
}
public String toString()
{
return "Dimensions are " + width + " by " + depth + " by " +
height + ".";
}
}

class String_Operation
{
public static void main(String args[])
{
Box b = new Box(10, 12, 14);
String s = "Box b: " + b;
object
System.out.println(b);
System.out.println(s);
}
}

// Concatenate Box

CHARACTER EXTRACTION
The String class provides a number of ways in which characters can
be extracted form a String object. That is Character Extraction.
1. charAt()
Syntax:
char charAt(int where)
class String_Operation
{
public static void main(String args[ ])
{
char ch;
ch = "Chettinad".charAt(4);
System.out.println("The 4 Character is:" + ch);
}
}

2. getChars()
If you need to extract more than one character at a time, you
can use the getChars() method.
Syntax:
void getChars(int sourceStart,int sourceEnd,char target [ ],int
targetStart)
class String_Operation
{
public static void main(String args[])
{
String s = "This is a demo of the getChars method.";
char buf [ ] = new char[20];
s.getChars(start,end,buf,0);
String chrs = new String(buf);
System.out.println(chrs);
}
}

3. getBytes()
There is an alternative to getChars() that stores the character in an
array of bytes. This method is called getBytes(), and it uses the default
character-to-byte conversions provided by the platform.
Here is its simplest form:
byte [] getBytes();
Other forms of getBytes are also available. getBytes is most useful
when you are exporting a String value into an environment that does not
support 16 - bit unicode character. For example, most Internet protocols and
text file formats use 8 - bit ASCII for all text interchange.
class String_Operation
{
public static void main(String args[])
{
String msg="HelloWorld";
byte b[ ]=msg.getBytes();
for(int i:b)
System.out.println("The Array of Bytes is: " + i);
}
}

4. 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:
char [ ] toCharArray()
This function is provided as a convenience, since it is possible to use
getChars() to achieve the same result.
class String_Operation
{
public static void main(String args[])
{
String str = Chettinad College of Engg & Tech";
char heram[ ] = str.toCharArray();
System.out.print("Converted value from String to char array
is: ");
for(char c:heram)
System.out.println(c);
}
}

STRING COMPARISON
1. equals() and equalsIgnoreCase()
To compare two strings for equality, use equals()
Syntax:
boolean equals(String str)
Here, str is the String object being compared with the
invoking String object. It returns true if the strings contain the same
characters in the same order, and false otherwise. The comparison is case
- sensitive.
To perform a comparison that ignores case differences, call
equalsIgnoreCase(). When it compares two string, it considers A - Z to be
the same as a - z.
Syntax:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the
invoking String object. It, too, returns true if the strings contain the same
characters in the same order, and false otherwise.

class String_Operation
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good - Bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> "
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> "
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> "
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> "
s1.equalsIgnoreCase(s4));
}
}
Output:
Hello equals Hello -> true
Hello equals Good-Bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true

+
+
+
+

2. 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.
Syntax:
boolean regionMatches(int
str2StartIndex,

str1StartIndex, String str2, int


int numChars)

boolean
regionMatches(boolean
str1StartIndex,
String
str2,
str2StartIndex, int numChars)

ignorCase,

int
int

class String_Operation
{
public static void main(String args[])
{
String str1 = new String("Java is a wonderful language");
String str2 = new String("It is an object-oriented language");
boolean result = str1.regionMatches(20, str2, 25, 8);
System.out.println(result);
}
}
Output: true
class String_Operation
{
public static void main(String args[])
{
String str1 = new String("Java is a wonderful language");
String str2 = new String("It is an object-oriented Language");
boolean result = str1.regionMatches(true, 20, str2, 25, 8);
System.out.println(result);
}
}
Output : true

3. startsWith() and endsWith()


The startsWith() method determines whether a given String begins
with a specified string.
The endsWith() method determines whether the String in ends
with a specified string.
Syntax:
boolean startsWith(String str)
boolean endsWith(String str)
str is the String object being tested. If the string matches,
true is returned. Otherwise false is returned
class String_Operation
{
public static void main(String args[])
{
boolean a, b;
a = "Chettinad".startsWith("Chi");
b = "Chettinad".endsWith("nad");
System.out.println("The Start of the String is: " + a);
System.out.println("The Ends of the String is:" + b);
}
}

The equals function and == operator are perform two different


operations
The equals() method compares the characters inside a String
object.
The == operator compares two object references to see whether
they refer to the same instance.
Syntax:
obj1.equals(obj2);
(obj1 == obj2); return
class
String_Operation
type is Boolean.
{
public static void main(String args[])
{
String s1 = "Hello1234";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
The Contents of the two String objects are identical, but they are distinct
object, This means that s1 and s2 do not refer to the same objects.

5. compareTo()
Syntax:
int compareTo(String str);
Value

Meaning

Less than zero


than str.

The invoking string is less

Greater than zero


than str.

The invoking string greater

Zero

The two strings are equal.

class String_Operation
{
public static void main(String args[])
{
String s1 = "Chettinad";
String s2 = Chettinad";
int n = s1.compareTo(s2);
System.out.println(The comparison of the String is: + n);
if (n==0)
System.out.println("The Two String are Equal");
else if(n>0)
System.out.println("The First Strings is Greater than
the
Second String");
else if(n<0)
System.out.println("The First String is Smaller
than the
Second String");
}
}

MODIFYING A STRING
1. substring()
substring() has two forms.
1. String substring(int startIndex)
2. String substring(int startIndex,int endIndex)

class String_Operation
{
public static void main(String args[ ])
{
String s1 = "This is a test. This is, too.";
String s2 = s1.substring(5);
String s3 = s1.substring(5,8);
System.out.println("The Sub String of S2 is: " + s2);
System.out.println("The Sub String of S3 is: " + s3);
}
}

2. concat()
You can concatenate two strings using concat()
Syntax:
String concat(String str);

class String_Operation
{
public static void main(String args[ ])
{
String s1 = Chettinad";
String s2 = s1.concat(" Tech");
System.out.println("The Concatenation of Two String is: " +
s2);
}
}

3. replace()
The replace() method replaces all occurrences of one
character in the invoking string with another character.
Syntax:
String replace(char original, char replacement)
class String_Operation
{
public static void main(String args[ ])
{
String s = "Hello".replace('l','w');
System.out.println("The Replacement of the String is:" + s);
}
}
4. trim()
The trim() method returns a copy of the invoking string from which
any leading and trailing whitespace has been removed.
Syntax:
String trim()
class String_Operation
{
public static void main(String args[ ])
{
String s = " Hello world
".trim();
System.out.println("The Removable Whitspace of the String is: " + s);
}
}

5. toUpperCase() and toLowerCase():


Syntax:
String toUpperCase();
String toLowerCase();
class Case
{
public static void main(String args[])
{
String lcase ="chettinad College of engineering & technology";
System.out.println("String Before Case Change: "+lcase);
String ucase =lcase.toUpperCase();
System.out.println("String After Upper Case Change: "+ucase);
lcase=ucase.toLowerCase();
System.out.println("String After Lower Case Change: "+lcase);
}
}
Output:
String Before Case Change: chettinad college of engineering & technology
String After Upper Case Change: CHETTINAD COLLEGE OF ENGINEERING &
TECHNOLOGY
String After Lower Case Change: chettinad college of engineering &
technology

StringBuffer Functions

1. StringBuffer is a peer class of String that provides much of the


functionality of strings.
2. String Buffer represents growable and writeable character sequences.
3. String Buffer may have characters and substrings inserted in the middle
or appended
to the end.
4. String Buffer will automatically grow to make room for such additions
and often has
more characters preallocated than are actually needed, to allow room for
growth.
StringBuffer Constructors
StringBuffer defined these three constructors:
1. StringBuffer()
2. StringBuffer(int size)
3. StringBuffer(String str)

StringBuilder functions in Java

StringBuilder functions in Java

reallocation.
(2) The second version accepts an integer argument that explicitly sets
the size of the
buffer.
(3) The third version accepts a String argument that sets the initial
contents of the
StringBuffer object and reserves room for 16 more characters without
1.
length() and capacity()
reallocation.
Syntax:
int length()
int capacity()
class String_Operation
{
public static void main(String args[ ])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Buffer = " + sb);
System.out.println("Length = " + sb.length());
System.out.println("Capacity = " + sb.capacity());
//Its
capacity is 21
//because room for 16 additional characters is
automatically added.
}

2. ensureCapacity()
1. If you want to preallocate room for a certain number of
characters after a StringBuffer has been constructed, you can use
ensureCapacity() to set the size of the
buffer.
2. This is useful if you know in advance that you will be appending a
large number of small strings to a StringBuffer.ensureCapacity() has this
general form:
void ensureCapacity(int capacity);
Here, capacity specifies the size of the buffer.
class String_Operation
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer(JAVA");
//Returns the current capacity of the String buffer.
System.out.println("Buffer : "+sb+"\nCapacity : " +
sb.capacity());
//Increases the capacity, as needed, to the specified amount in the
//given string buffer object
sb.ensureCapacity(27);
System.out.println("New Capacity = " + sb.capacity());
}
}

3. setLength()
To set the length of the buffer within a StringBuffer object,
use setLength().
Syntax:
void setLength(int len);
Here, len specifies the length of the buffer. This value must be non negative.
when you increase the size of the buffer, null characters are added to
the end of the existing buffer.
class String_Operation
{
public static void main(String[ ] args)
{
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer("Hello world!");
// Change the length of buffer to 5 characters:
s.setLength(5);
System.out.println(s);
}
}

4. charAt() and setCharAt()


1. The value of a single character can be obtained from a StringBuffer via the
charAt() method.
Syntax:
char charAt(int where);
For charAt(), where specifies the index of the character being
obtained.
2. You can set the value of a character within a StringBuffer using
setCharAt().
Syntax:
void setCharAt(int where,char ch);
being set,

For setCharAt(), where specifies the index of the character


and ch specifies the new value of that character.

not specify a

For both methods, where must be nonnegative and must


location beyond the end of the buffer.

class String_Operation
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Buffer before = " + sb);
System.out.println("charAt (1) before = " + sb.charAt(1));
sb.setCharAt(1,'i');
sb.setLength(2);
System.out.println("Buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
Output:
Buffer before : Hello
charAt(1) before : e
Buffer after : Hi
charAt(1) after: i

To copy a substring of a StringBuffer into an array, use the getChars()


method.
Syntax:
void

getChars(int

sourceStart,int

sourceEnd,char

target[],int
targetStart);
class String_Operation
{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer src = new StringBuffer("To learn JAVA, start with
keywords.");
// Declare a new char array:
char[] dst = new char[10];
// Copy the chars #9 and #13 to dst:
src.getChars(9,13,dst,0);
// Display dst:
System.out.println(dst);

6. append()
1. The append() method concatenates the string representation of
any other type of data to the end of the invoking StringBuffer object.
2. It has overloaded versions for all the built - in types and for
Object.
3. Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
4. String.valueOf() is called for each parameter to obtain its string
representation.
5. The result is appended to the current StringBuffer object. The
buffer itself is returned by each version of append().
StringBuffer append(String str)
public class String_Operation
{
public static void main(String[] args)
{
// Construct a String object:
String s1 = new String("3.14");
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer("The ratio is: ");
// Append the string and display the buffer:
System.out.println(s.append(s1) + ".");
}
Output: The ratio is:
3.14
}

StringBuffer append(int num)


class String_Operation
{
public static void main(String args[])
{
String s;
int a = 42;
StringBuffer sb = new StringBuffer();
sb = sb.append("a = ").append(a).append("!").toString();
System.out.println(sb);
}
}
Output: a = 42!
StringBuffer append(Object obj)
/*class String_Operation
{
public static void main(String[] args)
{
// Declare and initialize an object:
Object d = new Double(3.14);
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer("The ratio is: ");
// Append the object and display the buffer:
System.out.println(s.append(d) + ".");
}
Output: The ratio
is:3.14
}

7. insert()
1. The insert() method inserts one string into another.
2. It is overloaded to accept values of all the simple types, plus
Strings and Objects.
3. Like append(), it calls String.valueOf() to obtain the string
representation of the value it is called with.
4. These are a few of its forms:
StringBuffer insert(int index,String str)
StringBuffer insert(int index,char ch)
StringBuffer insert(int index, object obj)
Here, index specifies the index at which point the string will be
inserted into the invoking StringBuffer object.
StringBuffer insert(int index,String str)
class String_Operation
{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer buf = new StringBuffer("Hello !");
// Construct a String object:
String s = new String(World");
// Insert the string "s" at offset 6:
buf = buf.insert(6,s);
// Display the buffer:
System.out.println(buf);
World!

Output:

Hello

StringBuffer insert(int index,char ch)


public class String_Operation
{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer buf = new StringBuffer("Hello #!");
// Insert 'J' at the offset 6:
buf = buf.insert(6,'J');
// Display the buffer:
System.out.println(buf);
Output: Hello J # !
}
}
StringBuffer insert(int index, object obj)
class String_Operation
{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer buf = new StringBuffer("Hello !");
// Construct an object:
Object d = new Double(3.45);
// Insert d at the offset 6:
buf = buf.insert(6,d);
// Display the buffer:
System.out.println(buf);
Output: Hello
3.45 !
}
}

8. reverse()
You can reverse the character within s StringBuffer object
using reversed().
Syntax:
StringBuffer reverse();
class String_Operation
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Output: fedcba

9. delete() and deleteCharAt()


StringBuffer the ability to delete characters using the methods
delete() and deleteCharAt().
Syntax:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
class String_Operation
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a Test.");
sb.delete(4,7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
Test

Output: After delete: This a Test


After deleteCharAt: his a

10. replace()
It replace one set of character with another set inside a StringBuffer
object.
StringBuffer

replace(int

startIndex,

int

endIndex,

String str);

class String_Operation
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5,7, "was");
System.out.println("After Replace: " + sb);
}
}
Output:
After Replace : This was a test

11. substring()
Syntax:
String substring(int startIndex)
String substring(int startIndex,int endIndex)
class String_Operation
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Chettinad");
String r;
r =sb.substring(6);
System.out.println("The Substring is: " + r);
r= sb.substring(2,5);
System.out.println("The Substring is: " + r);
}
}
Output:
The Substring is: nad
The Substring is: ett

Streams in java
Stream: an object that either delivers data to its

destination (screen, file, etc.) or that takes data from a


source (keyboard, file, etc.) it acts as a buffer between
the data source and destination
Input stream: a stream that provides input to a program
System.in is an input stream
Output stream: a stream that accepts output from a

program
System.out is an output stream
A stream connects a program to an I/O object
System.out connects a program to the screen
System.in connects a program to the keyboard

82

THE
CHARACTER
STREAMS
83

The character Streams


1. While the byte stream classes provide sufficient functionality to handle any type of I/O
operation, they cannot work directly with Unicode characters.
2. Since one of the main purposes of Java is to support the write once, run anywhere
philosophy, it was necessary to include direct I/O support for characters.
3. At the top of the character stream hierarchies are the Reader and Writer abstract classes.

Reader
Reader is an abstract class that defines javas model of streaming character input. All of
the methods in this class will throw an IOException on error conditions.

Writer
Writer is an abstract class that defines streaming character output . All of the methods
in this class return a void value and throw an IOException in the case of errors.

84

The Methods Defined by Reader


Method
abstract void close()

Description
Closes the input source. Further read attempts will generate
an IOException.

void mark(int numChars) Places a mark at the current point in the input stream that
will remain valid until numChars characters are read
boolean markSupported() Returns true if mark() / reset() are supported on this stream
int read()

Returns an integer representation of the next available


character from the invoking input stream. -1 is returned
when the end of the file is encountered.

int read(char buffer[])

Attempts to read up to buffer.length characters into buffer


and returns the actual number of character that were
successfully read. -1 is returned when the end of the file
encountered.

abstract int read(


char buffer[],
int offset,
int numChars)

Attempts to read up to numChars characters into buffer


starting at buffer[offset], returning the number of characters
successfully read. -1 is returned when the end of the file is
encountered.
85

Method

Description

boolean ready()

Returns true if the next input request will not wait.


Otherwise, it returns false.

void reset()

Resets the input pointer to the previously set mark

long skip(
Skips over numChars characters of input , returning the
long numChars) number of characters actually skipped.

86

The Methods Defined by Writer


Method

Description

abstract void close()

Closes the output stream. Further write attempts will generate an


IOException.

abstract void flush()

Finalizes the output state so that any buffers are cleared. That is, it
flushes the output buffers.

void write (int ch)

Writes a single character to the invoking output stream. Note that


the parameter is an int, which allows you to call write with
expressions without having to cast them back to char.

void write(char buffer[])

Writes a complete array of characters to the invoking output


stream.

abstract void write(


char buffer[],
int numChars)

Writes a subrange of numChars characters from the array buffer,


beginning at buffer[offset] to the invoking output stream.

void write(String str)

Writes str to the invoking output stream.

void write(String str,


int offset,
int numChars)

Writes a subrange of numChars characters from the array str,


beginning at the specified offset.
87

FileReader
The FileReader class creates a Reader that you can use to read the contents of a file.
Its most commonly used constructors are shown here:
FileReader (String filePath)
FileReader (File filObj)

Note:
Either can throw a FileNotFoundException. Here, filePath is the full path name of a
file and fileobj is a File object that describes the file.

88

import java.io.*;
class FileReaderDemo
{
public static void main(String args[]) throws IOException
{
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null)
{
System.out.println(s);
}
fr.close();
}
}
89

FileWriter
The FileWriter class creates a Writer that you can use to writet to a file. Its most
commonly used constructors are shown here:

FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)

They can throw an IOException. Here, filePath is the full path name of a file, and fileObj is a
File Object that describes the file. If append is true, then output is appended to the end fo the
file.

90

import java.io.*;
class FileWriterDemo
{
public static void main(String args[])
{
try
{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

91

CharArrayReader
CharArrayReader is an implementation of an input stram that uses a character array as the
source. The class has two constructos, each of which requires a character array to provide the
data source:
CharArrayReader(char arrray[])
CharArrayReader(char array[],int start,int numChars)

Here, array is the input source. The second constructor creates a Reader from a subset of
your character array that begins with the character at the index specified by start and is
numChars long.

92

import java.io.*;
class CharArrayReaderDemo
{
public static void main(String args[]) throws IOException
{
String tmp = "abcdefghijklmnopqrstuvwxyz";
int length = tmp.length();
char c[] = new char[length];
tmp.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 0, 5);
int i;
System.out.println("input1 is:");
while((i = input1.read()) != -1)
{
System.out.print((char)i);
}
System.out.println();
System.out.println("input2 is:");
while((i = input2.read()) != -1)
{
System.out.print((char)i);
}
System.out.println();
}
}

93

CharArrayWriter
CharArrayWriter is an implementation of an output stram that uses a character array as the
destination. The class has two constructos, each of which requires a character array to provide
the data destination:
CharArrayWriter()
CharArrayWriter(int numChars)

In the first form, a buffer with a default size is created. In the second, a buffer is created with
a size equal to that specified by numChars. The buffer is held in the buf field of
CharArrayWriter. The buffer size will be increased automatically, if needed. The number of
characters held by the buffer is contained in the count field of CharArrayWriter. Both buf
and count are protected fields.

94

import java.io.*;
class CharArrayWriterDemo
{
public static void main(String args[]) throws IOException
{
CharArrayWriter f = new CharArrayWriter();
String s = "This should end up in the array";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
f.write(buf);
System.out.println("Buffer as a string");
System.out.println(f.toString());
System.out.println("Into array");
char c[] = f.toCharArray();
for (int i=0; i<c.length; i++)
{
System.out.print(c[i]);
}
System.out.println("\nTo a FileWriter()");
FileWriter f2 = new FileWriter("test.txt");
f.writeTo(f2);
f2.close();
System.out.println("Doing a reset");
f.reset();
for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}}

95

BufferedReader
BufferedReader improves performance by buffering input. It has two constructors:

BufferedReader(Reader inputStream)
BufferedReader(Reader inputStream,int bufsize)
The first form creates a buffered character stream using a default buffer size. In the second,
the size of the buffer is passed in bufsize.

96

import java.io.*;
class BufferedReaderDemo
{
public static void main(String args[]) throws IOException
{
String s = "This is a &copy; copyright symbol " + "but this is &copy not.\n";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
CharArrayReader in = new CharArrayReader(buf);
BufferedReader f = new BufferedReader(in);
int c;
while((c = f.read()) != -1)
{
System.out.print((char)c);
}
}
}
97

BufferedWriter
A BufferedWriter is a Writer that adds a flush() method that can be used to ensure that data
buffers are physically wirtten to the actual output stream. Using a BufferedWriter can increase
performance by reducing the number of times data is actually physically written to the output
stream. A BufferedWriter has these two constructors:

BufferedWriter(Writer outputStream)
BufferedWriter(Writer outputStream,int bufsize)
The first form creates a buffered character stream using a default buffer size. In the second,
the size of the buffer is passed in bufsize.

98

import java.io.*;
class BufferedWriterDemo
{
public static void main(String args[]) throws Exception
{
// Create a new instance of a BufferedWriter object using a StringWriter.
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw);
// Write to the underlying StringWriter.
String str = new String("This is the string being written.");
// Print out the 6 characters.
bw.write(str, 12, 6);
bw.flush();
System.out.println(sw.getBuffer());
// Close the BufferedWriter object and the underlying StringWriter object.
sw.close();
bw.close();
}

99

PushbackReader
The PushbackReader class allows one or more characters to be returned to the input stream.
This allows you to look ahead in the input stream. Here are its two constructors:
PushbackReader(Reader inputStream)
PushbackReader(Reader inputStream,int bufSize)
The first form creates a buffered stream that allows one character to be pushed back.
In the second, the size of the pushback buffer is passed in bufSize.
PushbackReader provides unread(), which returns one or more characters to the
invoking input stream. It has the three forms shown here:
void unread(int ch)
void unread(char buffer[])
void unread(char buffer[], int offset, int numChars)
The first form pushes back the character passed in ch. This will be the next character returned by
a subsequent call to read(). The second form returns the characters in buffer. The third form
pushes back numChars characters beginning at offset from buffer. An IOException 100
will be
thrown if there is an attempt to return a character when the pushback buffer is full.

import java.io.*;
class PushbackReaderDemo
{
public static void main(String args[]) throws IOException
{
String s = "if (a == 4) a = 0 ; \\n";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
CharArrayReader in = new CharArrayReader(buf);
PushbackReader f = new PushbackReader(in);
int c;
while ((c = f.read()) != -1)
{
switch(c)
{
case '=':
if ((c = f.read()) == '=')
System.out.print(".eq.");
else
{
System.out.print("<-");
f.unread(c);
}
break;
default:
System.out.print((char) c);
break;
}
}
}
}

101

PrintWriter
PrintWriter is essentially a character oriented version of PrintStream. It provides the
formatted output methods print() and println(). PrintWriter has four constructors:
PrintWriter(OutputStream outputStream)
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
PrintWriter(Writer outputStream)
PrintWriter(Writer outputStream, boolean flushOnNewline)
Where flushOnNewline controls whether Java flushes the output stream every time println() is
called. If flushOnNewline is true, flushing automatically takes place. If false, flushing is not
automatic. The first and third constructors do not automatically flush.

102

import java.io.*;
class PrintWriterDemo
{
public static void main(String args[])
{
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}

103

Java Collection Classes:


Class
AbstractCollection
AbstractList

Description
Implements most of the Collection interface.
Extends AbstractCollection and implements most
of the List interface.

LinkedList
Implements a linked list by extending
AbstractSequentialList.
ArrayList
AbstractList.
AbstractSet
of the Set
HashSet
table.

Implements a dynamic array by extending

Extends AbstractCollection and implements most


interface.
Extends AbstractSet for use with a hash
104

LinkedHashSet

Extends HashSet to allow insertion-order iterations.

ArrayList
Java ArrayList class uses a dynamic array for storing the
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList allows random access because array works at the
index basis.
In Java ArrayList class, manipulation is slow because a lot of
shifting needs to be occurred if any element is removed from the
array list.

Example:
ArrayList obj = new ArrayList();
ArrayList<String> obj1=new ArrayList<String>();
105

ArrayList - Example
import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();//creating arraylist
al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator itr=al.iterator();//getting Iterator from arraylist to traverse
elements
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

106

ArrayList
Adding elements to the list
1. Adds the specified element to the end of this list.
boolean add(Element e)
obj.add(10);
2. Adds the specified element at the specified position in
the list.
void add(int index, Element e)
obj.add(2,123);
Removing elements from the list
1. Removes all the elements from the list.
void clear()
obj.clear();
2. Removes the element at the specified position in the
list.
E remove(int index)
obj.remove(10);
3. Removes from the list all the elements starting from
index start included)

until index end (not included).

protected void removeRange(int start, int end)


obj.remove(3,5);

107

Getting elements from the list


1. Returns the element at the specified position.
E get(int index)
obj.get(4);
2. Returns an array containing all the elements of the list
in proper
sequence.
Object[] toArray()
obj.toArray();
Setting an element
1. Replaces the element at the specified position with the
specified
element.
E set(int index, E element)
obj.set(3,13);
Searching elements
1. boolean contains(Object o)
Returns true if the specified element is found in the list.
2. int indexOf(Object o)
Returns the index of the first occurrence of the specified element
in
the list. If this element is not in the list, the method returns -1.
3. int lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element
in
the list. If this element is not in the list, the method returns 108
-1.

ArrayList
Checking if the list is empty
boolean isEmpty()
Returns true if the list does not contain any element.
Getting the size of the list
int size()
Returns the length of the list (the number of elements
contained in
the list).

109

import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
// create an array list
ArrayList al = new ArrayList();
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 LinkedList Class


1. The LinkedList class extends AbstractSequentialList and implements
the List interface.
2. It provides a linked-list data structure. It has the two constructors, shown
here:
LinkedList( )
LinkedList(Collection c)
3. The first constructor builds an empty linked list.
4. The second constructor builds a linked list that is initialized with the
elements of the collection c.
5. In addition to the methods that it inherits, the LinkedList class defines
some useful methods of its own for manipulating and accessing lists.
6. To add elements to the start of the list, use addFirst( ); to add elements
to the end, use addLast( ).
7. Their signatures are shown here:
void addFirst(Object obj)
void addLast(Object obj)
Here, obj is the item being added. To obtain the first element, call
getFirst( ). To retrieve the last element, call getLast( ). Their signatures are
shown here:

Object getFirst( )
Object getLast( )
To remove the first element, use removeFirst( ); to remove the last
element, call removeLast( ). They are shown here:
Object removeFirst( )
Object removeLast( )
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
// create a linked list
LinkedList ll = new LinkedList();
// 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
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}

The Legacy Classes and Interfaces


The legacy classes defined by java.util are shown here:
Dictionary

Hashtable

Properties

Stack

Vector

Vector
1. Vector implements a dynamic array.
2. It is similar to ArrayList, but with two differences: Vector is synchronized,
and it contains many legacy methods that are not part of the collections
framework.
3. With the release of Java 2, Vector was reengineered to extend
AbstractList and implement the List interface, so it now is fully
compatible with collections.
4. Here are the Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)

5. The first form creates a default vector, which has an initial size of 10.
6. The second form creates a vector whose initial capacity is specified by
size.
7. The third form creates a vector whose initial capacity is specified by size
and whose increment is specified by incr.
8. The increment specifies the number of elements to allocate each time that
a vector is resized upward. The fourth form creates a vector that contains the
elements of collection c.
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new
v.addElement(new
v.addElement(new
v.addElement(new

Integer(1));
Integer(2));
Integer(3));
Integer(4));

System.out.println("Capacity after four additions: " + v.capacity());

v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Integer)v.lastElement());
if(v.contains(new Integer(10)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}

Stack
1. Stack is a subclass of Vector that implements a standard last-in, first-out
stack.
2. Stack only defines the default constructor, which creates an empty stack.
3. Stack includes all the methods defined by Vector, and adds several of its
own.
4. To put an object on the top of the stack, call push( ).
5. To remove and return the top element, call pop( ).
6. An EmptyStackException is thrown if you call pop( ) when the invoking
stack is empty. You can use peek( ) to return, but not remove, the top
object.
7. The empty( ) method returns true if nothing is on the stack.
import
8. Thejava.util.*;
search( ) method determines whether an object exists on the stack,
class StackDemo
{ and returns the number of pops that are required to bring it to the top of
the stack.
static void showpush(Stack st, int a)
{
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st)
{
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}

public static void main(String args[])


{
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try
{
showpop(st);
}
catch (EmptyStackException e)
{
System.out.println("empty stack");
}
}
}

Dictionary
1. Dictionary is an abstract class that represents a key/value storage repository and
operates much like Map.
2. Given a key and value, you can store the value in a Dictionary object.
3. Once the value is stored, you can retrieve it by using its key.
4. Thus, like a map, a dictionary can be thought of as a list of key/value pairs.
5. To add a key and a value, use the put( ) method.
6. Use get( ) to retrieve the value of a given key.
7. The keys and values can each be returned as an Enumeration by the keys( ) and
elements( ) methods, respectively.
8. The size( ) method returns the number of key/ value pairs stored in a dictionary.
9. isEmpty( ) returns true when the dictionary is empty.
10. You can use the remove( ) method to delete a key/value pair.

Vous aimerez peut-être aussi