Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
PROGRAMMING IN JAVA
1. PROGRAMMING IN JAVA
A. SIVASANKARI
ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER APPLICATION
SHANMUGA INDUSTRIES ARTS AND SCIENCE
COLLEGE,
TIRUVANNAMALAI. 606601.
Email: sivasankaridkm@gmail.com
2. PROGRAMMING IN JAVA
UNIT - 3
PART-I
STRING
STRING HANDLING
STRING METHODS
STRING BUFFER CLASS
STRING BUILDER
STRING TOKENIZER
CLASS
EXCEPTION HANDLING
A. SIVASANKARI - SIASC-TVM UNIT-3
3. STRING
DEFINITION OF STRING CLASS
• Strings, which are widely used in Java programming, are a sequence of characters. In Java
programming language, strings are treated as objects.
• The Java platform provides the String class to create and manipulate strings.
• Creating Strings
• The most direct way to create a string is to write
• String greeting = "Hello world!";
• Whenever it encounters a string literal in your code, the compiler creates a String object with
its value in this case, "Hello world!'.
• EXAMPLE
• public class StringDemo
• {
• public static void main(String args[])
• {
• char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
• String helloString = new String(helloArray);
• System.out.println( helloString );
• }}
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
STRING REVERCE
6. Java toString() method
• If we want to represent any object as a string, toString() method comes into existence.
• The toString() method returns the string representation of the object.
• If you print any object, java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an object
etc. depends on your implementation.
Advantage of Java toString() method
• By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much code.
Understanding problem without toString() method
• class Student{
• int rollno;
• String name;
• String city;
• Student(int rollno, String name, String city){
• this.rollno=rollno;
• this.name=name;
• this.city=city;
• }
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
7. • public static void main(String args[]){
• Student s1=new Student(101,"Raj","lucknow");
• Student s2=new Student(102,"Vijay","ghaziabad");
• System.out.println(s1); //compiler writes here s1.toString()
• System.out.println(s2); //compiler writes here s2.toString()
• }
• }
OUTPUT:
• Student@1fee6fc
• Student@1eed786
Understanding problem toString() method
• public class Test {
• public static void main(String args[]) {
• Integer x = 5;
• System.out.println(x.toString());
• System.out.println(Integer.toString(12));
• }
• }
OUTPUT:
• 5
• 12
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
14. EXCEPTION HANDLING
• An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
• An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out
of memory.
• Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
• Based on these, we have three categories of Exceptions. We need to understand them to
know how exception handling works in Java.
• Checked exceptions − A checked exception is an exception that is checked (notified) by the
compiler at compilation-time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored, the programmer should take care of (handle) these
exceptions.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
15. • For example, if we use FileReader class in our program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
Example
• import java.io.File;
• import java.io.FileReader;
• public class FilenotFound_Demo {
• public static void main(String args[]) {
• File file = new File("E://file.txt");
• FileReader fr = new FileReader(file); }}
• If we try to compile the above program, you will get the following exceptions.
Output
• C:>javac FilenotFound_Demo.javaFilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown FileReader fr = new
FileReader(file); ^1 error
• Note − Since the methods read() and close() of FileReader class throws IOException, we can
observe that the compiler notifies to handle IOException, along with FileNotFoundException.
• Unchecked exceptions − An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions. These include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
16. EXCEPTION HIERARCHY
• All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass
called Error which is derived from the Throwable class.
• Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the Java programs. Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of memory. Normally, programs cannot recover from
errors.
• The Exception class has two main subclasses: IOException class and RuntimeException
Class
PROGRAMMING IN JAVA
1. TRY
2. CATCH
3. THROW
4. THROWS
5. FINALLY
A. SIVASANKARI - SIASC-TVM
17. Sr.No. EXCEPTIONS METHODS & DESCRIPTION
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the
Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3 public String toString() [Returns the name of the class concatenated with the result of
getMessage().
4 public void printStackTrace() [Prints the result of toString() along with the stack trace to
System.err, the error output stream.]
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the
top of the call stack, and the last element in the array represents the method at the bottom of the call
stack.
6 public Throwable fillInStackTrace() [Fills the stack trace of this Throwable object with the
current stack trace, adding to any previous information in the stack trace.]
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
18. 1. TRY -CATCHING EXCEPTIONS
• A method catches an exception using a combination of the try and catch keywords.
• A try/catch block is placed around the code that might generate an exception.
• Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following
SYNTAX
• try {
• // Protected code
• }
• catch (ExceptionName e1)
• { // Catch block
• }
• The code which is prone to exceptions is placed in the try block. When an exception occurs,
that exception occurred is handled by catch block associated with it. Every try block should
be immediately followed either by a catch block or finally block.
• A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
19. EXAMPLE
// File Name : ExcepTest.java
• import java.io.*;
• public class ExcepTest
• {
• public static void main(String args[]) {
• try {
• int a[] = new int[2];
• System.out.println("Access element three :" + a[3]);
• }
• catch (ArrayIndexOutOfBoundsException e)
• { System.out.println("Exception thrown :" + e);
• }
• System.out.println("Out of the block"); }}
OUTPUT
• Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3Out of the block
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
20. 2. MULTIPLE CATCH BLOCKS
• A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks
looks like the following
• Syntax
• try {
• // Protected code}
• catch (ExceptionType1 e1)
• { // Catch block}
• catch (ExceptionType2 e2)
• { // Catch block}
• catch (ExceptionType3 e3)
• { // Catch block}
EXAMPLE
• try {
• file = new FileInputStream(fileName);
• x = (byte) file.read();}
• catch (IOException i) {
• i.printStackTrace();
• return -1;}
• catch (FileNotFoundException f) // Not valid!
• { f.printStackTrace();
• return -1;}
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
21. 3. THE THROWS/THROW
• If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's
signature.
• You can throw an exception, either a newly instantiated one or an exception that
you just caught, by using the throw keyword.
• Try to understand the difference between throws and throw keywords, throws is
used to postpone the handling of a checked exception and throw is used to invoke
an exception explicitly.
• The following method declares that it throws a RemoteException
EXAMPLE
• import java.io.*;
• public class className {
• public void deposit(double amount) throws RemoteException
• { // Method implementation
• throw new RemoteException();
• } // Remainder of class definition
• }
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
22. 4. THE FINALLY BLOCK
• The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an Exception.
• Using a finally block allows you to run any clean-up-type statements that you want to
execute, no matter what happens in the protected code.
• A finally block appears at the end of the catch blocks and has the following syntax −
SYNTAX
• try { // Protected code}
• catch (ExceptionType1 e1)
• { // Catch block}
• catch (ExceptionType2 e2)
• {
• // Catch block} catch (ExceptionType3 e3)
• { // Catch block}
• finally
• { // The finally block always executes.
• }
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
23. EXAMPLE
• public class ExcepTest {
• public static void main(String args[]) {
• int a[] = new int[2];
• try {
• System.out.println("Access element three :" + a[3]);
• }
• catch (ArrayIndexOutOfBoundsException e) {
• System.out.println("Exception thrown :" + e); }
• finally { a[0] = 6;
• System.out.println("First element value: " + a[0]);
• System.out.println("The finally statement is
executed");}
• }}
OUTPUT
• Exception thrown
:java.lang.ArrayIndexOutOfBoundsException: 3
• First element value: 6
• The finally statement is executed
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM