java unit3

Upload: arunchinnathambi

Post on 08-Mar-2016

255 views

Category:

Documents


1 download

DESCRIPTION

Exception handling, Packaging, Files

TRANSCRIPT

  • *EXCEPTION HANDLING OR ERROR HANDLING

  • *What is Error?- Error means mistakes or buggs- Error is classified into typesErrorCompile Time ErrorRun Time ErrorMissing Semicolon Missing brackets in classes and methods3. Use of undeclared variablesDividing an integer by zeroAccessing an element that is out of the bounds of an arrayAll syntax errors will be detectedAnd displayed by the Java compiler and therefore these errors Are known as compile time errorsA program may compile successfully creating the .exe file butnot run properly. Such programsmay produce wrong results dueto wrong loaic or may terminatedue to 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 zeroSome Example of Runtime Errors

  • *Exception Types1. All Exception types are subclasses of the built in class Throwable. Throwable is at the top of the exception class hierarchy ThrowableException (or) RuntimeExceptionErrorThis 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 typesWhich defines exceptions that are not Expected to be caught under normal Circumstances by our program. Ex. Stack overflow

  • *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, so the exception is caught by the default handler provided by the java run time systemUncaught Exception

  • *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 TypesExceptionSynchronous ExceptionAsynchronous ExceptionDivision by Zero

    Keyboard InterruptMouse Interrupt

  • *Exception Handling MechanismThe 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

    Catches and handles theexceptionException object

  • *Using try and catch------------------------------------try{---------------------------------------}catch(Exception_Type e){----------------------------}------------------------------------//Block of statements which detects and//throws an exception//Catches exception//Block of statements that handles the //exception

  • *Example Program for Exception Handling Mechanismclass Error_Handling{public static void main(String args[]){int i,j,k1,k2;

    i = 10;j = 0;try{k1 = i / j;System.out.println("The Division of the K1 Value is: " + k1);}catch(ArithmeticException e){System.out.println("Division by Zero");}k2 = i + j;

    System.out.println("The addition of the K2 Value is: " + k2);}}There is an ExceptionCatches the exceptionOutput: Division by Zero, The addition of the K2 Value is:10

  • *Multiple Catch StatementsIt 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}

  • *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);}}

  • *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");}COMMAN EXCEPTION HANDLER

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

  • *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");}*/

  • *catch(ArrayStoreException e){System.out.println("Wrong data type");}

    int y = a[1] / a[0];System.out.println("Y = " + y);}}

  • *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.

  • *try{if ( a == 1)a = a / (a - a); //division by zeroif(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);} }}

  • *Nested try Statements using Subroutine

    class Error_Handling{static void nesttry(int a){try{if ( a == 1)a = a / (a - a); //division by zeroif(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);}}

  • *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);}}}

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

  • *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);}}}

  • *throws 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. 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. 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. 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

  • *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);}}}

  • *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. finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch block.Using finally Statementtry{//statements}catch(Exception-Type-1 e){//statements}catch(Exception-Type-2 e){//statements}----------------------catch(Exception-Type-N e){//statements}finally {--------------------------------------}try{//statements}finally {--------------------------------------}

  • *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");}}

  • *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();} }

  • *Javas Built in ExceptionsThe standard package java.lang, Java defines several exception classes. A few have been used by the preceding examples.

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

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

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

    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.

    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.

  • *Javas Unchecked RuntimeException Subclasses

    ExceptionMeaningArithmeticExceptionArithmetic error, such as divde by zeroArrayIndexOutOfBoundsExceptionArray index is out of bounds.ArrayStoreExceptionAssignment to an array element of an incompatible type.ClassCastExceptionInvalid Cast.IllegalArgumentExceptionIllegal argument used to invoke a methodIllegalMonitoStateExceptionIllegal Monitor Operation, such as waiting on an unlocked thread.IllegalStateExceptionEnvironment or application is in incorrect state.IllegalThreadStateExceptionRequested operation not compatible with current thread state.IndexOutOfBoundsExceptionSome type of index is out of boundsNegativeArraySizeExceptionArray Created with a negative size.

  • *

    ExceptionMeaningNullPointerExceptionInvalid use of a null reference.NumberFormatExceptionInvalid conversion of a string to a numeric format.SecurityExceptionAttempt to violate securityStringIndexOutOfBoundsAttempt to index outside the bounds of a string.UnsupportedOperationExceptionAn unsupported Operation was encountered.

  • *Javas Checked Exception Defined in java.lang

    ExceptionMeaningClassNotFoundExceptionClass not foundCloneNotSupportedExceptionAttempt to clone an object that does not implement the cloneable interface.IllegalAccessExceptionAccess to a class is deniedInstantiationExceptionAttempt to create an object of an abstract class or interfaceInterruptedExceptionOne thread has been interrupted by another thread.NoSuchFieldExceptionA requested field does not exist.NoSuchMethodExceptionA requested method does not exist.

  • *Throwing our own ExceptionsThere 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:Exception is subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught

  • *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");}}

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

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

  • 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: abc1. 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);O/P: JAVASystem.out.println(s2);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: ABCDEFString 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. Conversion of other data types to a string representation.String LiteralsAssigning 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";//Use String Literals, Java automatically //constructs a String objectSystem.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());}}

  • 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;// Concatenate Box object

    System.out.println(b);

    System.out.println(s);}}

  • CHARACTER EXTRACTION

    The String class provides a number of ways in which characters can be extracted form a String object. That is Character Extraction.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 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 -> trueHello equals Good-Bye -> falseHello equals HELLO -> falseHello 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 str1StartIndex, String str2, int str2StartIndex, int numChars)

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

  • 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 : trueclass 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

  • 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 returnedclass 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);}}

  • 4. equals() Versus ==

    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 type is Boolean.class String_Operation{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 zeroThe invoking string is less than str. Greater than zero The invoking string greater than str. 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
  • MODIFYING A STRING 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 & technologyString After Upper Case Change: CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGYString After Lower Case Change: chettinad college of engineering & technology

  • StringBuffer Functions 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 ConstructorsStringBuffer defined these three constructors:

    1. StringBuffer()2. StringBuffer(int size)3. StringBuffer(String str)

  • StringBuilder functions in Java

  • StringBuilder functions in Java

  • (1) The default constructor reserves room for 16 characters without 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 reallocation.length() and capacity()

    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 objectsb.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);

    For setCharAt(), where specifies the index of the character being set, and ch specifies the new value of that character.

    For both methods, where must be nonnegative and must not specify a 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 : HellocharAt(1) before : eBuffer after : HicharAt(1) after: i

  • 5. getChars() 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); Output: Hello World!}}

  • 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);}}Output: After delete: This a TestAfter deleteCharAt: his a Test

  • 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: nadThe Substring is: ett

  • Streams in javaStream: 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 destinationInput stream: a stream that provides input to a program System.in is an input streamOutput stream: a stream that accepts output from a programSystem.out is an output streamA stream connects a program to an I/O objectSystem.out connects a program to the screenSystem.in connects a program to the keyboard

    *

  • *THE CHARACTER STREAMS

  • *The character StreamsWhile the byte stream classes provide sufficient functionality to handle any type of I/O operation, they cannot work directly with Unicode characters. 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. At the top of the character stream hierarchies are the Reader and Writer abstract classes.ReaderReader 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.

    WriterWriter 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.

  • *The Methods Defined by Reader

    MethodDescriptionabstract void close()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 readboolean markSupported()Returns true if mark() / reset() are supported on this streamint 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.

  • *

    MethodDescriptionboolean 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 marklong skip( long numChars)Skips over numChars characters of input , returning the number of characters actually skipped.

  • *The Methods Defined by Writer

    MethodDescriptionabstract 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.

  • *FileReaderThe 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.

  • *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();}}

  • *FileWriterThe 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.

  • *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 streamout.close();}catch (Exception e){//Catch exception if anySystem.err.println("Error: " + e.getMessage());}}}

  • *CharArrayReaderCharArrayReader 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.

  • *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(); } }

  • *CharArrayWriterCharArrayWriter 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.

  • *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
  • *BufferedReaderBufferedReader 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.

  • *import java.io.*;

    class BufferedReaderDemo{ public static void main(String args[]) throws IOException{ String s = "This is a 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);}} }

  • *BufferedWriterA 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.

  • *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();}}

  • *PushbackReaderThe 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 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("
  • *PrintWriterPrintWriter 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.

  • *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); } }

  • *Java Collection Classes:

    Class DescriptionAbstractCollection Implements most of the Collection interface.

    AbstractList Extends AbstractCollection and implements most of the List interface.

    LinkedList Implements a linked list by extending AbstractSequentialList.

    ArrayList Implements a dynamic array by extending AbstractList.

    AbstractSet Extends AbstractCollection and implements most of the Set interface.

    HashSet Extends AbstractSet for use with a hash table.

    LinkedHashSet Extends HashSet to allow insertion-order iterations.

    TreeSet Implements a set stored in a tree. Extends AbstractSet.

  • ArrayListJava ArrayList class uses a dynamic array for storing theJava 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 obj1=new ArrayList();*

  • ArrayList - Exampleimport java.util.*; class TestCollection1{ public static void main(String args[]){ ArrayList al=new ArrayList();//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()); } } } *

  • ArrayListAdding elements to the list1. 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 list1. 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);*

  • Getting elements from the list1. 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 element1. Replaces the element at the specified position with the specified element.E set(int index, E element)obj.set(3,13);Searching elements1. 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 -1.

    *

  • ArrayListChecking if the list is emptyboolean isEmpty()Returns true if the list does not contain any element.Getting the size of the listint size()Returns the length of the list (the number of elements contained in the list).*

  • import java.util.*;class ArrayListDemo {public static void main(String args[]) {// create an array listArrayList al = new ArrayList();System.out.println("Initial size of al: " + al.size());// add elements to the array listal.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 listSystem.out.println("Contents of al: " + al);// Remove elements from the array listal.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

    The LinkedList class extends AbstractSequentialList and implements the List interface. 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 listLinkedList ll = new LinkedList();// add elements to the linked listll.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 listll.remove("F");ll.remove(2);System.out.println("Contents of ll after deletion: + ll);// remove first and last elementsll.removeFirst();ll.removeLast();System.out.println("ll after deleting first and last: + ll);// get and set a valueObject val = ll.get(2);ll.set(2, (String) val + " Changed");System.out.println("ll after change: " + ll);}}

  • The Legacy Classes and InterfacesThe legacy classes defined by java.util are shown here:Dictionary Hashtable Properties Stack VectorVectorVector implements a dynamic array. 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. 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. 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 2Vector v = new Vector(3, 2);

    System.out.println("Initial size: " + v.size());System.out.println("Initial capacity: " + v.capacity());

    v.addElement(new Integer(1));v.addElement(new Integer(2));v.addElement(new Integer(3));v.addElement(new 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();}}

  • StackStack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own. To put an object on the top of the stack, call push( ). To remove and return the top element, call pop( ). 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. The empty( ) method returns true if nothing is on the stack. The search( ) method determines whether an object exists on the stack, and returns the number of pops that are required to bring it to the top of the stack.import java.util.*;class StackDemo{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");}}}

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