Download Java String Handling and Exception Handling: Constructors, Operations, Exceptions and more Assignments Compiler Design in PDF only on Docsity!
Unit 3- String Handling
and Exception Handling
Strings:
- Strings are objects that represent sequence of characters.
- Creating a String object is like creating a string that cannot be changed
- Strings are otherwise called as immutable strings
- The String class is defined in java.lang. Also they are ‘final’ which means it cannot be subclassed. String Constructors:
- String s=new String() // Creates an instance with no chars
- String(char chars[]) (e.g.) char chars[]={‘a’,’b’,’c’}; String s=new String(chars);
- String(char chars[], int startindex, int numchars) (e.g.) char chars[]={‘a’,’b’,’c’,’d’,’e’,’f’}; String s=new String(chars, 2,3);
- String Objects are stored in a special memory area known as string constant pool.
- No new objects are created if it exists already in string constant pool.
**Operations on Strings:
- String Length:** Returns the number of characters in a given string Syntax: int length() (e.g.) String s=new String(“java”); int m=s.length(); String s1=“abcde”; System.out.println(“abcde”.length()); 2) String Concatenation: use ‘+’ operator 3) charAt(): Extract a single character from a String Syntax: char charAt(int where) (e.g.) char ch; ch=“abc”.charAt(1);
indexOf(): Searches for the first occurrence of a character or substring Search for the first occurrence of a character: int indexOf(char ch) Search for the last occurrence of a character: int lastIndexOf(char ch) Search for the first occurrence of a substring: int indexOf(String str) Search for the last occurrence of a substring: int lastindexOf(String str) Specify the starting point for the search int indexOf(char ch, int startindex) int lastIndexOf(char ch, int startindex) int indexOf(String str, int startindex) int lastIndexOf(String str, int startindex)
Substring(): Extract a substring syntax: String substring(int startindex) String substring(int startindex, int endindex) concat(): Concatenates two strings syntax: String concat(String str) replace(): Replaces all occurrences of one character in the invoking string with another character. syntax: String replace(char original, char replacement) trim(): Removes all the leading and trailing whitespaces syntax: String trim() toLowerCase() and toUpperCase(): syntax: String toLowerCase() String toUpperCase()
getChars():
- To extract more than one character at a time void getChars(int sourceStart, int sourceEnd, char target[], int targetStart) (e.g.) String s=“This is a demo”; int start=5; int end=8; char buf[]=new char[end-start]; s.getChars(start,end,buf,0); System.out.println(buf); toCharArray():
- Converting all the characters in a String object into a character array char[] toCharArray()
startsWith() and endsWith():
- Determines whether a given String begins or ends with a specified string. boolean startsWith(String str) boolean endsWith(String str) boolean startsWith(String str, int startindex)
StringBuffer Methods:
- public StringBuffer append(String s)
- public StringBuffer reverse()
- public delete(int start, int end) public deleteCharAt(int loc)
- public insert(int offset, String s) public insert(int offset, char ch)
- StringBuffer replace(int start, int end, String str)
- int capacity()
- char charAt(int index)
- int indexOf(String str)
- int indexOf(String str, int fromindex)
- int lastIndexOf(String str)
- int lastIndexOf(String str, int fromIndex)
- int length()
- Void setLength(int len)
- void setCharAt(int index, char ch)
- String substring(int start)
- String substring(int start, int end)
- Void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)
Exception:
- An exception is a condition that is caused by run-time error in a program.
- When the Java interpreter encounters an error, it creates an exception object and throws it.
- If the exception object is not caught and handled properly, the interpreter will display an error message and will terminate the program.
- To continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display the appropriate message for taking corrective actions.
Exception Handling:
- An exception is an event that occurs during the execution of a program, which disrupts the normal flow of the program’s instructions.
- Java provides exception handling mechanism which can be used to trap this exception and run programs smoothly after catching the exception.
- When an error occurs within a method, the method creates an object and hands it off to the runtime system. (exception object)
- Creating an exception object and handing it to the runtime system is called throwing an exception. Tasks of Exception Handling:
- Find the exception (Hit the exception)
- Inform that error has occurred (Throw the exception)
- Receive the error information (Catch the exception)
- Take corrective results (Handle the exception)
Using try and catch:
- To handle a run-time error, enclose the code that has to be monitored inside a try block.
- Immediately following the try block, include a catch clause that specifies the exception type that has to be catched.
- Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.
- A try and catch statement form a unit. The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement.
- A catch statement cannot catch an exception thrown by another try statement.
(e.g) try { int num; num=Integer.parseInt(“ABC123”); System.out.println(“Control won’t reach here”); } catch(NumberFormatException e) { System.out.println(“Exception thrown”); System.out.println(e.getMessage()); // display internally generated msg e.printStackTrace(); // indicates types and exception occurred and // place and line number. } System.out.println(“out of try-catch block”);