0% found this document useful (0 votes)
3 views

Exceptions_Strings_Files

The document provides an overview of Strings and StringBuilder in Java, highlighting their characteristics, memory storage, and differences. It explains the immutability of Strings, the mutable nature of StringBuilder, and the importance of using appropriate methods for string manipulation. Additionally, it covers exception handling in Java, including try-catch blocks, checked and unchecked exceptions, and the use of finally blocks.

Uploaded by

gowthug018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Exceptions_Strings_Files

The document provides an overview of Strings and StringBuilder in Java, highlighting their characteristics, memory storage, and differences. It explains the immutability of Strings, the mutable nature of StringBuilder, and the importance of using appropriate methods for string manipulation. Additionally, it covers exception handling in Java, including try-catch blocks, checked and unchecked exceptions, and the use of finally blocks.

Uploaded by

gowthug018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

String/String object

def: anything which is with in “ ___“ is called as String


or String object or String constant in java
Eg: “google” String

⮚ a String can contain


only alpha characters🡪 ”abc”
(or)-only numerical characters🡪 ”123”
(or)-only special characters🡪 ”!@#”
(or)-only combination 🡪 ”[email protected]

⮚ a String can have multiple characters or a single


character or no character
as , ”abc” or “a” or “ ”(empty String) or “ “
Strings and memory sample

stack
s1 s2

0x100 String 0x200 String

heap
0x200
hello

0x100
hello

String constant pool


Strings and memory
⮚ String objects are stored either in heap
memory or in String constant pool memory,
based on your logic.
⮚ internally Strings are stored as character
arrays.
⮚ String objects are immutable.
[note : immutable means unchangeable].
String constant pool:-
⮚ it is a memory area in ram, which will store
String objects, which are created without new
operator
⮚ s.c pool will not create a new String object if the
same String object is already available in
== vs equals()
⮚ == operators for comparison address’s of 2 Strings.
⮚ equals() method compares content of 2 Strings.

public class test { Stack s4


0x300
public static void main(String[] args)
{ s1 s2 s3
0x100 0x200 0x300
String s1 = new String("palle");

String s2 = new String("palle"); HEAP


String s3="palle";
“ palle” “palle”
String s4=“palle”; false 0x100==0x200
system.out.println(s1 == s2);
true
system.out.println(s1.equals(s2)); “palle”.equals(“palle”)
false
system.out.println(s1==s3); 0x100==0x300 StringConstantPool
} true
} system.out.println(s1.equals(s3)); “palle”.equals(“palle”)

system.out.println(s3==s4); true
“palle”
0x300==0x300
Strings and immutability
Strings are considered as immutable entities(whose
content is not changeable).
lhs rhs
stack s
0X800
0X600 String

req:i want to add new String to existing


heap
String

0x600
P a l l e t e c h
0 1 2 3 4 5 6 7 8
0x800
p a l l e t e c h
0 1 2 3 4 5 6 7 8

String constant pool


String class methods
req: replace “la” with “na” in s

who has written code for replace() method?


⮚ sun micro system programmers has written code for replace method
⮚ we are just using the methodname,method parameters,
⮚ method return type
We have predefined methods available in the Java String class
Based on your requirement you can use them..

we can see
methodname,method
parameters,method return type

scroll it
String disadvantages
disadvantages:
⮚ String objects are immuatble. if you try to
modify a String object, it will create one more
String object.
note: programmer should not use String class
objects for modification purpose.
⮚ more you try to modify, more String objects
will be created and Strings are not meant for
modification more memory will be wasted
String builder
⮚ String builder is a built in class and its code is written by
sun microsystems programmers
⮚ using String builder we can modify the String data
hence it is considered as mutable.

package
- class1
StringBuilderClass Class 3

Method 1 Method 2 class2


-- ---- ---- ---- --- --- ---- --

---- - ------- ------ --- --


properties of StringBuilder
⮚ StringBuilder objects are stored in heap.
⮚ StringBuilder comes with a default capacity of 16.
⮚ StringBuilder objects are dynamically growable
growth factor=(previous capacity+1)*2
⮚ StringBuilder is “mutable”(changeable)
⮚ StringBuilder objects are not synchronized with multiple
threads
note:internally stored as arrays
StringBuilder sample

//5(no of characters)
//21(total 16+5 characters)
Stack s
0x100 StringBuilder

Heap
0x100 -

p a l l e
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Object of StringBuilder
StringBuilder internals
lhs rhs

stack sb
0x100 StringBuilder

heap
0x100
output: -
palletech
p a l l et e c h
0 1 2 3 4 5 6 7 8
advantage:
⮚using sb we can modify String data
⮚since sb are mutable, new Strings are not
created in heap and hence memory object of StringBuilder
wastage is reduced
difference between String and StringBuilder
String StringBuilder
⮚ String objects are immutable(not ⮚ StringBuilder objects are
modifiable in same location) mutable(Modifiable in same location)
⮚ String objects are stored either in ⮚ StringBuilder objects are stored in
heap or SC pool heap always
⮚ String objects are fixed sized ⮚ StringBuilder objects are dynamically
entities .Not growable once growable,in same location.
created. ⮚ Internally stored as arrays.
⮚ Internally stored as arrays.
arrays ⮚ Not synchronized.not thread
⮚ Thread safe . you can use String safe.Dont use StringBuilder objects
objects with multiple threads. with multiple threads.it is not safe.your
⮚ use String objects if you don’t data may get corrupted.
want to do many modifications ⮚ Use StringBuilder for modification
purpose.(if you want to do too many
modifications)
String Builder class methods
StringBuilder class methods:
⮚ all methods will modify the data in same location.
⮚ new objects will not be created unlike String class.
*Based on your requirement you can use predefined String Builder class methods

we can see
methodname,method
parameters,method return type

scroll it
StringBuffer
⮚ it is a predefined class of java.
⮚ StringBuffer is exactly same as StringBuilder ,but with only
one difference.
⮚ StringBuilder is not synchronized for multiple threads.
⮚ StringBuffer is synchronized for multiple threads.

use this if your application has multiple threads


properties of StringBuffer
⮚ mutable
⮚ stored in heap
⮚ dynamically growable
⮚ synchronized for multiple threads
synchronized=applying locking techniques
non- synchronized= no locking techniques
exceptions
def: exception is an abnormal event which occurs at run time,
which will disturb the normal flow of program execution and
terminates your program abruptly.
errors

compile time errors run time errors


(syntax errors) (exceptions/logical errors)

Test.java java Test.class


jvm
compiler (byte code)

exceptions/run
compile time errors are runs your program time errors
detected by compiler and displays o/p detected by jvm
while running
your applications
exception internals

compilation error as semicolon is missing

logical error given at runtime by jvm/


also called as exception

once exception occurs it will not execute next lines it terminates the
program
how to handle exceptions

an exception can be caught/ handled using two ways


 by using “try - catch” block.
 by using “throws” clause.
handling exceptions with “try-catch” block
syntax :
try
{
-----------------------------
code that might throw an exception
}
catch ( <exception name> variable)
{
----------------------------
code to handle the exception thrown by above code…
}
note : when programmer catches /handles an exception
successfully by using a try catch block, then your program
will not be terminated and jvm will execute further.
example for try – catch block

ArthimaticException

Here We are handling ArthimaticException by using try-catch block


properties of try-catch block
 every try block should contain at least one catch
block (or) one finally block
 a try block(or) a catch block (or) a finally block,
alone can’t exist.
 a try block can be associated with a series of
multiple catch blocks, each handling different
exceptions.
 we can declare only one finally block for a given try
block.
try catch finally rules

------ ------
------
------ ------ ------
------

------ ------
------ ------
------
------

------
------
------ ------
------ ------

------  you are allowed to write 0 or 1 finally


------
block for given try.
------
------  you are allowed to write 0 or more
catch blocks for a given try block.
------
------
nested try catch blocks part2
------
------

------
------

------
------
types of exceptions
exceptions

checked exceptions unchecked exceptions

 programmer should  programmer need not


handle checked exceptions, handle unchecked exception
else, compiler will throw , compiler will not throw
error. error
eg: filenotfoundexception eg:
io exception indexoutofboundsexception
sql exception nullpointerexception
outofmemoryerror
checked exceptions

unchecked exceptions
FileNotFoundExceptions

 it comes under the io exceptions and is a part of


checked exceptions.
 this means we have to handle these types of
exceptions.
 “if the file doesn’t exist in the given path” then
filenotfoundexception occurs.
 to handle the checked exceptions we are having two
ways, one is by using try-catch block and the other is
by using throws clause.
example for filenotfoundexception
handling checked exceptions – using
throws clause
if we don’t know how to catch the exception with the help of try-
catch block, then we can throw that exception to parent method by
using throws clause.
we can use throws clause after writing the signature of the
function, before starting the body after that we have to write that
exception name.
if we are throwing multiple exceptions then we can specify them
by using comma(,).

 in parent function, we have to use try-catch block in the


corresponding lines, i.e., the lines that causing exception.
class CheckExep
example for throws clause
{
public void readMe(String path) throws FileNotFoundException
{
FileReader fr= new FileReader(path);

}
} if you use throws clause in main() ,your program will
crash
public static void main(String[] args)
{
CheckExep ce=new CheckExep();
try
{
ce.readMe("C:/Users/Admin/Desktop/read.txt");
}
catch (FileNotFoundException e)
{
System.out.println("File Doesnt exit");
e.printStackTrace();
}
}
order of exceptions to handle

 always handle most specific exceptions first and generic


exceptions last. (most child class first and most parent class last)
 lets see the class hierarchy diagram for better understanding.
class hierarchy diagram

most generic
object throwable exception

ioexception
error - filenotfoundexception
- socketexception

sql exception
most specific
example for order of exceptions to handle
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class ExmTrow
{
public static void main(String[] args)
{
try
{
FileWriter fw = new FileWriter("C:/Users/Admin/Desktop/read.txt");
}
catch(FileNotFoundException f)
{
System.out.println("File Not Found"); Correct Order
f.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
finally block

finally block is used to clean important system


resources like

a. file connections
b. database connections .. etc
public class FinallyBlock
finally block example
{
public static void main(String[] args)
{
opening connection
FileWriter out = null;
try
{
out = new FileWriter("C:/Users/Admin/Desktop/write.txt");
}
catch (FileNotFoundException e)
{ caching FileNotFoundExpectation
e.printStackTrace();
}
catch (IOException e)
{ caching IOExpectation
e.printStackTrace();
}

finally In finally block we are closing connections.


{ Note: finally block always executed Exceptions
out.close(); occurs or not
}
}
}
finally block - properties
 finally block should be placed only after all catch blocks.
 finally block will be definitely called by jvm whether an exception
occurs or doesn’t occur.
 try-finally block without catch block is also possible.[imp]

note :-
finally block will be executed even if programmer uses
break/continue/return statements.
files – important classes

File: used to create a file in the given path

FileWriter: used to write data into file, character by character

BufferWriter: used to write data into file, line by line

FileReader: used to read data from file, character by character

BufferReader: used to read data from file, line by line


files – writing data

creates a file if it doesn’t


File f = null; exists
FileWriter fw = null;
BufferedWriter bw = null;
f = new File("d:/palle.txt"); opening bufferedwriter
to write data
fw = new FileWriter(f);
bw = new BufferedWriter(fw); writing data into file

bw.write("hello we are writing into files\n");


bw.write("we are learning files\n");

bw.close();
closing connections
fw.close();
files – reading data
File f = null;
FileReader fr = null; Creates a file if it doesn’t exists
BufferedReader br = null;
f = new File("d:/palle.txt");
opening BufferReader to read the data
from file
fr = new FileReader(f);
br = new BufferedReader(fr); reading data line bye line
String str = br.readLine();
while (str != null)
printing data from file by using while
{ loop
System.out.println(str);
str = br.readLine();
}

br.close(); closing connections


fr.close();

You might also like