String Exception IO Java - PowerPoint PPT Presentation

About This Presentation
Title:

String Exception IO Java

Description:

String Exception IO Java PPT s share by Mahika Tutorials. Visit our YouTube page – PowerPoint PPT presentation

Number of Views:214

less

Transcript and Presenter's Notes

Title: String Exception IO Java


1
  • String in java
  • An object that represents a sequence of
    characters.
  • java.lang.String class is used to create string
    object.
  • Ways to create String object
  • By string literal
  • By new keyword

2
  • String Literal
  • Created by using double quotes.
  • Stored in String Constant Pool(SCP).
  • Makes Java more memory efficient
  •  Example
  • String str" Hello "  
  • How it works?
  • Each time you create a string literal, the JVM
    checks the string constant pool first.
  • If the string already exists in the pool, a
    reference to the pooled instance is returned.
  • If string doesn't exist in the pool, a new
    string instance is created and placed in the
    pool. For example

3
String str1Hello"    
Stack
Heap
4
String str1Hello"   String str2"Hello"//will 
not create new instance  
Stack
Heap
5
  • By new keyword
  • A new object is always created in non pool area.
  • Example
  • String strnew String(Hello")//creates 2
    objects and 1 reference variable
  •   
  • How it works?
  • JVM will create a new string object in normal(non
    pool) heap memory.
  • JVM checks the string constant pool, if string
    doesn't exist in the pool ,then literal " Hello"
    will be placed in the string constant pool.
  • The variable str will refer to the object in
    heap(non pool).

6
(No Transcript)
7
(No Transcript)
8
Stack
Heap
9
String class Constructors-
String()-Initializes a newly created String object
so that it represents an empty character
sequence. String s new String() String(byte
bytes)  Construct a new String by decoding
the byte array. It uses the platforms default
character set for decoding. byte
b119,101,108,99,111,109,101 String snew
String(b) System.out.println(s)//welcome String
(char value)  Allocates a new String from the
given Character array. char value'w','e','l','
c','o','m','e' String s new
String(value) System.out.println(s)//welcome St
ring(char value, int offset int count) 
Allocates a new String that contains characters
from a subarray of the character array
argument. char value 'w','e','l','c','o','m','
e' String snew String(value,3,4) System.out.pr
intln(s)//come
10
String class Constructors-

String(String original)-Initializes a newly created String object so that it represents the same sequence of characters as the argument in other words, the newly created string is a copy of the argument string. String s new String("Hello") System.out.println(s)//Hello
String(StringBuffer buffer)-Allocates a new string that contains the sequence of characters currently contained in the string buffer argument. StringBuffer buffernew StringBuffer("welcome") String snew String(buffer) System.out.println(s)//welcome
String(StringBuilder  builder)-Allocates a new string that contains the sequence of characters currently contained in the string builder argument. StringBuilder buildernew StringBuilder("hello") String snew String(builder) System.out.println(s)//hello
11
Java String class methods
char charAt(int index) returns char value for the particular index
Example- String sWelcome System.out.println(s
.charAt(3))// c System.out.println(s.charAt(8))/
/ java.lang.StringIndexOutOfBoundsException
int length() returns string length
Example- String sWelcome System.out.println(s
.length())// 7
12
String substring(int beginIndex) returns substring for given begin index
Example- String sHello, How Are
You? System.out.println(s.substring(7))// How
Are You?
String substring(int beginIndex, int endIndex) returns substring for given begin index and end index
Example- String sHello, How Are
You? System.out.println(s.substring(7,10)//
How System.out.println(s.substring(7,20)//
java.lang.StringIndexOutOfBoundsException
13
String toUpperCase() returns string in uppercase.
Example- String shello System.out.println(s.t
oUpperCase()// HELLO
String toLowerCase() returns string in lowercase.
Example- String sHELLO System.out.println(s.t
oLowerCase()// hello
boolean contains(CharSequence s) returns true or false after matching the sequence of char value
Example- String sHello, How Are
You? System.out.println(s.contains(Are))//tru
e
14
String Handling
15
Java String class methods
int indexOf(int ch) returns specified char value index
Example- String sHello, How Are
You? System.out.println(s.indexOf (e)//1
String concat(String str) concatinates specified string
Example- String sMahika System.out.println(s.
concat ( Tutorials))//Mahika Tutorials
char toCharArray() Converts this string to a new character array.
Example- String sHello, How Are You? char
ars.toCharArray()
16
String replace(char old, char new) replaces all occurrences of specified char value
Example- String sHello, How Are
You? System.out.println(s. replace('e','i'))//
Hillo, How Ari you
String replace(CharSequence old, CharSequence new) replaces all occurrences of specified CharSequence
Example- String s"Bad-luck" System.out.println(s
.replace("Bad","Good"))// Good-luck
17
boolean startsWith(String prefix) Tests if this string starts with the specified prefix..
Example- String sHello, How Are
You? System.out.println(s.startsWith
(Hello))//true
boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
Example- String sHello, How Are
You? System.out.println(s.endsWith(We))//fals
e
18
Thank You
19
  • Java String class methods


No. Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 String substring(int beginIndex) returns substring for given begin index
4 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index
5 String toUpperCase() returns string in uppercase.
6 String trim() removes beginning and ending spaces of this string.
20
7 boolean contains(CharSequence s) returns true or false after matching the sequence of char value
8 boolean equals(Object another) checks the equality of string with object
9 boolean isEmpty() checks if string is empty
10 String concat(String str) concatinates specified string
11 String replace(char old, char new) replaces all occurrences of specified char value
12 String replace(CharSequence old, CharSequence new) replaces all occurrences of specified CharSequence
13 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
14 String toLowerCase() returns string in lowercase.

21
  • Immutable String in Java
  • In java, string objects are immutable.
  • Immutable simply means unmodifiable or
    unchangeable.
  • Once a string object is created its data or state
    can't be changed.
  • Example
  • class Test
  • public static void main(String args)
  • String strMahika"
  • str.concat(" Tutorials")//concat() method
    appends the string at the end
  • System.out.println(str)//will print
    Mahika because strings are immutable objects

22
String strMahika
23
String strMahika str.concat( Tutorials)
Since strings are immutable, what this method
really do, it creates and return a new string
that contains the result of the operation.
24
str str.concat( Tutorials) System.out.println
(str)//Mahika Tutorials
String Constant Pool
Mahika Tutorials
str
Mahika
Stack
Heap
25
Why String is immutable in Java?
1. Requirement of String Pool
String str1 Hello"String str2 Hello"
Stack
Heap
If string were mutable, changing the string with
one reference will lead to the wrong value for
the other references. Now if str1 changes the
object from Hello" to Welcome", str2 will also
get valueWelcome.
26
 2. Security
  • String is widely used as parameter for many Java
    classes, e.g. for reading files in Java you can
    pass path of files and directory as String and
    for opening database connection, you can pass
    database URL as String . In case, if String were
    not immutable, this would had lead to serious
    security threats . Someone could access any file
    for which he has authorization, and then could
    change the file name either deliberately or
    accidentally and gain access to another file,
    this could cause serious security issues.
  • Similarly, while connecting to database or any
    other machine in network, mutating String value
    can cause security threats. 
  • As the parameters are string in Reflection
    ,mutable strings could cause a security threat in
    Reflection too.
  • String is heavily used in class loading
    mechanism. 

27
3. Immutable objects are naturally thread-safe
Since immutable objects can not be changed, they
can be shared among multiple threads freely. This
eliminates the requirements of doing
synchronization.
4.Caching Hashcode The hashcode of a string is
frequently used in Java, for example, in a
HashMap or HashSet. Being immutable guarantees
that hashcode will always be the same so that it
can be cached without worrying about the
changes.That means, there is no need to calculate
hashcode every time it is used. This is more
efficient.
28
String is widely used as parameter for many Java
classes, e.g. for reading files in Java you can
pass path of files and directory as String and
for opening database connection, you can pass
database URL as String . In case, if String were
not immutable, this would had lead to serious
security threats . Someone could access any file
for which he has authorization, and then could
change the file name either deliberately or
accidentally and gain access to another file,
this could cause serious security issues.
  • String is widely used as parameter for many Java
    classes, e.g. for reading files in Java you can
    pass path of files and directory as String and
    for opening database connection, you can pass
    database URL as String . In case, if String were
    not immutable, this would had lead to serious
    security threats . Someone could access any file
    for which he has authorization, and then could
    change the file name either deliberately or
    accidentally and gain access to another file,
    this could cause serious security issues.

29
class Test    public static void main(String args
)      String s"Sachin"      ss.concat(" Ten
dulkar")      System.out.println(s)          W
hy string objects are immutable in java? Because
java uses the concept of string literal.Suppose
there are 5 reference variables,all referes to
one object "sachin".If one reference variable
changes the value of the object, it will be
affected to all the reference variables. That is
why string objects are immutable in java
30
String Handling
31
  • String comparison
  • By equals() or equlasIgnoreCase() method
  • By operator
  • By compareTo() or compareToIgnoreCase() method

32
  • equals() method
  • Compares values of string for equality.
  • Returns boolean value.
  • equals() is case sensitive.
  • If you want to check for equality with case
    insensitivity, then you can use equalsIgnoreCase()
     .

  
33
 Example String s1Hello"      String s2"
Hello "      String s3new String(" Hello
")      String s4Welcome"   String s5"
HELLO "      System.out.println(s1.equals(s2))//
true      System.out.println(s1.equals(s3))//true
      System.out.println(s1.equals(s4))//false  
System.out.println(s1.equalsIgnoreCase(s5))//t
rue    
SCP
HELLO
Welcome
Hello
s5
Hello
s4
s3
s2
s1
Stack
Heap
34
  • operator
  • Compares references.
  •  If two String variables point to the same object
    in memory, the comparison returns true.
    Otherwise, the comparison returns false.
  •  

35
Example   String s1" Hello "      String s2"
Hello "      String s3new String(" Hello ")  
String s4new String(" Hello ")      System.out
.println(s1s2)//true     System.out.println(s1
s3)//false System.out.println(s4s3)//false

SCP
Hello
Hello
Hello
s4
s3
s2
s1
Stack
Heap
36
  • compareTo() method
  • Compares values lexicographically
  • Returns an integer value.
  • Each character of both the strings is converted
    into a Unicode value for comparison.
  • Suppose s1 and s2 are two string variables. If
  • s1 s2 0
  • s1 gt s2   positive value
  • s1 lt s2   negative value
  • compareToIgnoreCase() is case insensitive.
  • Example
  •    String s1"Hello"  
  •    String s2"Hello"  
  •    String s3Welcome"  
  • String s4"Hi"
  •    System.out.println(s1.compareTo(s2))//0  
  •    System.out.println(s1.compareTo(s3))//-15
  •    System.out.println(s3.compareTo(s1))//15

37
Thank You
38
String Handling
39
  • StringBuffer class
  • Used to created mutable (modifiable) string.
  • Thread-safe i.e. multiple threads cannot access
    it simultaneously.
  • StringBuilder class
  • Used to create mutable (modifiable) string.
  • Same as StringBuffer class except that it is
    non-synchronized.
  • It is available since JDK 1.5.

Important methods
  • public synchronized StringBuffer append(String s)
  • public synchronized StringBuffer insert(int
    offset, String s)
  • public synchronized StringBuffer replace(int
    startIndex, int endIndex, String str)
  • public synchronized StringBuffer delete(int
    startIndex, int endIndex)
  • public synchronized StringBuffer reverse()
  • public char charAt(int index)
  • public int length()
  • public String substring(int beginIndex)
  • public String substring(int beginIndex, int
    endIndex)

40
StringBuffer append(String str)-The append()
method concatenates the given argument with this
string. Example- StringBuffer sbnew
StringBuffer(Mahika") sb.append(Tutorials")
//now original string is changed
System.out.println(sb)//Mahika
Tutorials StringBuffer insert(int offset,
String str)-Inserts the string into this
character sequence. Example- StringBuffer
sbnew StringBuffer("Hello ")
sb.insert(2,Welcome")//now original string is
changed System.out.println(sb)//HeWlecomello

41
StringBuffer replace(int start, int end,
String str)-Replaces the characters in a
substring of this sequence with characters in the
specified String. Example- StringBuffer sbnew
StringBuffer("Hello, How is You?")
sb.replace(11,13,Are)//now original string is
changed System.out.println(sb)//Hello, How
AreYou?  StringBuffer delete(int start,
int end)-Removes the characters in a substring of
this sequence. Example- StringBuffer sbnew
StringBuffer("Hello, How Are You?")
sb.delete(0, 7)//now original string is changed
System.out.println(sb)//How AreYou?
42
StringBuffer reverse()-Causes this character
sequence to be replaced by the reverse of the
sequence. Example- StringBuffer sbnew
StringBuffer("Hello, How Are You?")
sb.reverse() System.out.println(sb)//?uoy erA
woH ,olleH char charAt(int index)- Returns
the char value in this sequence at the specified
index. Example- StringBuffer sbnew
StringBuffer("Hello, How Are You?")
System.out.println(sb.charAt(1))//e  
43
int length()-Returns the length (character
count). Example- StringBuffer sbnew
StringBuffer("Hello") System.out.println(sb.le
ngth()) //5 String substring(int start)-Returns
a new String that contains a subsequence of
characters currently contained in this character
sequence. The substring begins at the specified
index and extends to the end of this
sequence. Example- StringBuffer sbnew
StringBuffer("Hello, How Are you?")
System.out.println(sb.substring(7))//How Are
you? String substring(int start,
int end)-Returns a new String that contains a
subsequence of characters currently contained in
this sequence. The substring begins at the
specified start and extends to the character at
index end - 1. Example- StringBuffer sbnew
StringBuffer("Hello, How Are you?")
System.out.println(sb.substring(7,10))//How

44
Thank You
45
  • StringBuilder class
  • Used to create mutable (modifiable) string.
  • Same as StringBuffer class except that it is
    non-synchronized.
  • It is available since JDK 1.5.

46
Difference between StringBuffer and StringBuilder
No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffersimultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuildersimultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
47
Exception Handling
48
  • Exception
  • An event that disrupts the normal flow of the
    program.
  • Exception Handling
  • Mechanism to handle the runtime events so that
    normal flow of the application can be maintained.
  • Advantage of Exception Handling
  • Maintains the normal flow of the application.

49
Hierarchy of Java Exception classes
50
  • Types of Exception
  • Checked Exception
  • Unchecked Exception
  • Checked Exception
  • Classes that extend Throwable class except
    RuntimeException and Error e.g.IOException,
    SQLException etc.
  • Checked at compile-time.
  • Unchecked Exception
  • Classes that extend RuntimeException e.g.
    ArithmeticException, NullPointerException,
    ArrayIndexOutOfBoundsException etc.
  • Not checked at compile-time rather they are
    checked at runtime.
  • Error
  • Error is irrecoverable e.g. OutOfMemoryError,
    VirtualMachineError, etc.

51
  • Common scenarios causing exceptions
  • int a50/0//ArithmeticException
  • 2) int arnew int5
  • ar1050 //ArrayIndexOutOfBoundsException
  • 3) String snull
  • System.out.println(s.length())//NullPointer
    Exception
  • 4) String shello"
  • int iInteger.parseInt(s)//NumberFormatExc
    eption

52
  • Exception Handling Keywords
  • try
  • catch
  • finally
  • throw
  • throws

53
  • try block
  • Used to enclose the code that might throw an
    exception.
  • Must be followed by either catch or finally
    block.
  • Syntax of try-catch
  • try  
  • //code that may throw exception  
  • catch(Exception_class_Name ref)   
  • Syntax of try-finally block
  • try  
  • //code that may throw exception  
  • finally   

Syntax of try-catch-finally try   //code that ma
y throw exception   catch(Exception_class_Name r
ef) finally      
54
  • catch block
  • Used to handle the Exception.
  • Must follow the try block only.
  • Multiple catch block can be given with a single
    try.
  • Multiple catch block
  • Used to perform different tasks at the occurrence
    of different Exceptions.
  • At a time only one catch block is executed.
  • Catch blocks must be ordered from most specific
    to most general

55
(No Transcript)
56
Java Multi catch block If you have to perform
different tasks at the occurrence of different
Exceptions, use java multi catch
block.   public static void main(String args)  
   try       int anew int5       a530/0
            catch(ArithmeticException e)
System.out.println("task1 is completed")
      catch(ArrayIndexOutOfBoundsException e)
System.out.println("task 2 completed")      cat
ch(Exception e) System.out.println("common tas
k completed")         System.out.println("rest o
f the code...")          Output task1
completed rest of the code...
57
Nested try block The try block within a try block
is known as nested try block in java. Why use
nested try block Sometimes a situation may arise
where a part of a block may cause one error and
the entire block itself may cause another error.
In such cases, exception handlers have to be
nested. Syntax ....   try          statement 1 
      statement 2       try                  sta
tement 1           statement 2              cat
ch(Exception e)                    catch(Except
ion e)         ....  
58
class Excep6 public static void main(String
args) try try
System.out.println("going to divide") int
b 39/0 catch(ArithmeticException e)
System.out.println(e)
try int anew int5 a54
catch(ArrayIndexOutOfBoundsException
e)System.out.println(e)
System.out.println("other statement)
catch(Exception e)System.out.println("handeled")
System.out.println("normal flow..")

59
  • finally block
  • Always executed whether exception occurs or not
    and whether exception is handled or not.
  • Follows try or catch block.
  • Used to put "cleanup" code such as closing
    connection, file etc.
  • For each try block there can be zero or more
    catch blocks, but only one finally block.
  • Not executed if program exits(either by calling
    System.exit() or by causing a fatal error that
    causes the process to abort).

60
(No Transcript)
61
Let's see the java finally example
where exception doesn't occur. class TestFinallyB
lock     public static void main(String args) 
    try      int data25/5      System.out.print
ln(data)          catch(NullPointerException e)
System.out.println(e)     finallySystem.out.pri
ntln("finally block is always executed")     Sys
tem.out.println("rest of the code...")         
  Output 5 finally block is always executed
rest of the code...
62
Let's see the java finally example
where exception occurs and not handled. class Test
FinallyBlock1     public static void main(String 
args)     try      int data25/0      System.
out.println(data)          catch(NullPointerExce
ption e)System.out.println(e)     finallySyste
m.out.println("finally block is always executed")
     System.out.println("rest of the code...")  
        Output finally block is always
executed Exception in thread main
java.lang.ArithmeticException/ by zero
63
Let's see the java finally example
where exception occurs and handled. public class T
estFinallyBlock2     public static void main(Stri
ng args)     try      int data25/0      Syst
em.out.println(data)          catch(ArithmeticEx
ception e)System.out.println(e)     finallySys
tem.out.println("finally block is always executed"
)     System.out.println("rest of the code...")
           OutputException in thread main
java.lang.ArithmeticException/ by zero finally
block is always executed rest of the code...
64
Rule For each try block there can be zero or
more catch blocks, but only one finally
block. Note The finally block will not be
executed if program exits(either by calling
System.exit() or by causing a fatal error that
causes the process to abort).
65
  • throw keyword
  • Used to explicitly throw an exception.
  • Can be used to throw either checked or uncheked
    exception .
  • Mainly used to throw custom exception.
  • Syntax
  • throw exception

66
public class TestThrow1 static void
validate(int age) if(agelt18)
throw new ArithmeticException("not valid")
else System.out.println("welcome to
vote") public static void
main(String args) validate(13)
System.out.println("rest of the code...")
Output Exception in thread main
java.lang.ArithmeticExceptionnot valid
67
Exception Handling
68
  • throws keyword
  • used to declare an exception.
  • throws keyword can be followed by one more
    exception class, separated by commas.
  • throws keyword is required only for checked
    exception and usage of throws keyword for
    unchecked exception is meaningless.
  • Syntax
  • return_type method_name() throws
    exception_class_name
  • //method code

69
public class FileWriteExample void create()
throws IOException FileWriter fw new
FileWriter("d/xyz.txt") fw.write("Hello How are
You?") fw.close() System.out.println("File
Created") public static void main(String
args) throws IOException FileWriteExample
objnew FileWriteExample() obj.create() System.o
ut.println("Rest of the code")
70
Difference between throw and throws
throw throws
Used to explicitly throw an exception. Used to declare an exception
An instance follows throw keyword. Class follows throws keyword.
Used within the method body. Used with the method signature.
Multiple exceptions cannot be thrown using it. Multiple exceptions can be declared using it
71
Constructors
File Class
  • An abstract representation of file and directory
    pathname. 
  • A pathname can be either absolute or relative.
  • Instances of the File class are immutable that
    is, once created, the abstract pathname
    represented by a File object will never change.
  • File class is used to retrieve metadata of a file
    like the size and permissions for read and write
    etc.
  •  File class gives you access to the underlying
    file system. Using the File class you can
  • Check if a file or directory exists.
  • Create a directory if it does not exist.
  • Read the length of a file.
  • Rename or move a file.
  • Delete a file.
  • Check if path is file or directory.
  • Read list of files in a directory.

72
Constructors
Constructor Description
File(File parent, String child) It creates a new File instance from a parent abstract pathname and a child pathname string.
File(String pathname) It creates a new File instance by converting the given pathname string into an abstract pathname.
File(String parent, String child) It creates a new File instance from a parent pathname string and a child pathname string.
File(URI uri) It creates a new File instance by converting the given file URI into an abstract pathname.
73
Commonly Used Methods of File Class
Type Method Description
boolean createNewFile() It atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
boolean canWrite() It tests whether the application can modify the file denoted by this abstract pathname.String
boolean canExecute() It tests whether the application can execute the file denoted by this abstract pathname.
boolean canRead() It tests whether the application can read the file denoted by this abstract pathname.
boolean isAbsolute() It tests whether this abstract pathname is absolute.
boolean isDirectory() It tests whether the file denoted by this abstract pathname is a directory.
74
Commonly Used Methods of File Class
boolean isFile() It tests whether the file denoted by this abstract pathname is a normal file.
String getName() It returns the name of the file or directory denoted by this abstract pathname.
String getParent() It returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
File listFiles() It returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname
String list(FilenameFilter filter) It returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
boolean mkdir() It creates the directory named by this abstract pathname.
75
mahika.tutorials_at_gmail.com
Write a Comment
User Comments (0)
About PowerShow.com