SlideShare a Scribd company logo
1 of 26
PROGRAMMING IN JAVA
A. SIVASANKARI
ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER APPLICATION
SHANMUGA INDUSTRIES ARTS AND SCIENCE
COLLEGE,
TIRUVANNAMALAI. 606601.
Email: sivasankaridkm@gmail.com
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
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
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
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
• 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
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
STRING AND STRING BUFFER
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
STRING BUILDER
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
STRING AND STRING BUFFER AND STRING BUILDER
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
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
• 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
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
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
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
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
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
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
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
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
PROGRAMMING IN JAVA
THROW AND THROWS
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
TRY ,CATCH ,THROW AND THROWS
A. SIVASANKARI - SIASC-TVM
A. SIVASANKARI - SIASC-TVM

More Related Content

What's hot

Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentationdhananajay95
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSteve Fort
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programmingagorolabs
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Edureka!
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaEdureka!
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java ProgrammingRavi Kant Sahu
 
Java basic-tutorial for beginners
Java basic-tutorial for beginners Java basic-tutorial for beginners
Java basic-tutorial for beginners Muzammil Ali
 
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...Edureka!
 

What's hot (17)

Java essential notes
Java essential notesJava essential notes
Java essential notes
 
Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentation
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
 
Basic java part_ii
Basic java part_iiBasic java part_ii
Basic java part_ii
 
Letest
LetestLetest
Letest
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java basic-tutorial for beginners
Java basic-tutorial for beginners Java basic-tutorial for beginners
Java basic-tutorial for beginners
 
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
 
Java 101
Java 101Java 101
Java 101
 
Core Java
Core JavaCore Java
Core Java
 
Core Java
Core JavaCore Java
Core Java
 

Similar to PROGRAMMING IN JAVA

Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptxsonalipatil225940
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT studentsPartnered Health
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptxmadan r
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfFacultyAnupamaAlagan
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception HandlingMaqdamYasir
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 

Similar to PROGRAMMING IN JAVA (20)

Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptx
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 

More from SivaSankari36

DATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARIDATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARISivaSankari36
 
CLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARICLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARISivaSankari36
 
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARIMOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARISivaSankari36
 
MOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARIMOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARISivaSankari36
 
Functional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationFunctional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationSivaSankari36
 
Java unit1 b- Java Operators to Methods
Java  unit1 b- Java Operators to MethodsJava  unit1 b- Java Operators to Methods
Java unit1 b- Java Operators to MethodsSivaSankari36
 

More from SivaSankari36 (6)

DATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARIDATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARI
 
CLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARICLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARI
 
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARIMOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
 
MOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARIMOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARI
 
Functional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationFunctional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data Application
 
Java unit1 b- Java Operators to Methods
Java  unit1 b- Java Operators to MethodsJava  unit1 b- Java Operators to Methods
Java unit1 b- Java Operators to Methods
 

Recently uploaded

INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 

Recently uploaded (20)

INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
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
  • 4. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 5. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 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
  • 8. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 9. STRING AND STRING BUFFER PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 10. STRING BUILDER PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 11. STRING AND STRING BUFFER AND STRING BUILDER PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 12. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 13. 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
  • 24. PROGRAMMING IN JAVA THROW AND THROWS A. SIVASANKARI - SIASC-TVM
  • 25. PROGRAMMING IN JAVA TRY ,CATCH ,THROW AND THROWS A. SIVASANKARI - SIASC-TVM
  • 26. A. SIVASANKARI - SIASC-TVM