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

Java essential notes
Java essential notesJava essential notes
Java essential notesHabitamu Asimare
 
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!
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on javashashi shekhar
 
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!
 
Java 101
Java 101Java 101
Java 101javafxpert
 

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
 
Exception
ExceptionException
ExceptionFraboni Ec
 
Exception
ExceptionException
ExceptionFraboni Ec
 
Exception
ExceptionException
ExceptionJames Wong
 
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
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
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
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
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
 

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

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 

Recently uploaded (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
CĂłdigo Creativo y Arte de Software | Unidad 1
CĂłdigo Creativo y Arte de Software | Unidad 1CĂłdigo Creativo y Arte de Software | Unidad 1
CĂłdigo Creativo y Arte de Software | Unidad 1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 

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