0% found this document useful (0 votes)
4 views36 pages

UNIT 4

Unit 4 of CS3391-OOP covers Exception Handling and I/O in Java, explaining the basics of input and output operations using streams, including InputStream and OutputStream classes. It details file handling with FileOutputStream and FileInputStream, along with examples for reading and writing data to files and the console. Additionally, it introduces the BufferedReader class for reading text from character-based input streams and the FileReader class for reading data from files.

Uploaded by

adchuthan.cs22
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)
4 views36 pages

UNIT 4

Unit 4 of CS3391-OOP covers Exception Handling and I/O in Java, explaining the basics of input and output operations using streams, including InputStream and OutputStream classes. It details file handling with FileOutputStream and FileInputStream, along with examples for reading and writing data to files and the console. Additionally, it introduces the BufferedReader class for reading text from character-based input streams and the FileReader class for reading data from files.

Uploaded by

adchuthan.cs22
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/ 36

UNIT-4 CS3391-OOP

UNIT IV EXCEPTION HANDLING AND I/O


I/O Basics – Reading and Writing Console I/O – Reading and Writing Files. Generics: Generic
Programming – Generic classes – Generic Methods – Bounded Types – Restrictions and
Limitations. Strings: Basic String class, methods and String Buffer Class.
4.1 INPUT / OUTPUT BASICS
➢ Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations. We can
perform file handling in java by Java I/O API.
4.1.1 STREAM
A stream can be defined as a sequence of data. There are two kinds of Streams −
• InputStream − The InputStream is used to read data from a source.
• OutputStream − The OutputStream is used for writing data to a destination.
In java, 3 streams are created for us automatically. All these streams are attached with console.

1) System.out: standard output stream


2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.
System.out.println("simple message");
System.err.println("error message");
Let's see the code to get input from console.
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i); //will print the character
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
➢ Java application uses an output stream to write data to a destination, it may be a file,
an array, peripheral device or socket.

1 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

InputStream
➢ Java application uses an input stream to read data from a source, it may be a file, an
array, peripheral device or socket.
OutputStream class
➢ OutputStream class is an abstract class. It is the super class of all classes
representing an output stream of bytes. An output stream accepts output bytes and
sends them to some sink.

Useful Methods of OutputStream

Method Description

1)public void write(int)throws is used to write a byte to the current output


IOException stream.

2) public void write(byte[])throws is used to write an array of byte to the


IOException current output stream.

3) public void flush()throws flushes the current output stream.


IOException

4) public void close()throws is used to close the current output stream.


IOException

OutputStream Hierarchy

2 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

InputStream class
➢ InputStream class is an abstract class. It is the super class of all classes representing
an input stream of bytes.
Useful Methods of InputStream

Method Description

1) public abstract int reads the next byte of data from the input stream.
read()throws IOException It returns -1 at the end of file.

2) public int available()throws returns an estimate of the number of bytes that


IOException can be read from the current input stream.

3) public void close()throws is used to close the current input stream.


IOException

InputStream Hierarchy

4.1.2 Java FileOutputStream Class


➢ Java FileOutputStream is an output stream used for writing data to a file. If you
have to write primitive values into a file, use FileOutputStream class.
➢ You can write byte-oriented as well as character-oriented data through
FileOutputStream class. But, for character-oriented data, it is preferred to use
FileWriter than FileOutputStream.
FileOutputStream Class Declaration
Let's see the declaration for Java.io.FileOutputStream class:
public class FileOutputStream extends OutputStream

3 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

FileOutputStream Class Methods

Method Description

protected void finalize() It is used to clean up the connection with the


file output stream.

void write(byte[] ary) It is used to write ary.length bytes from the


byte array to the file output stream.

void write(byte[] ary, int off, int len) It is used to write len bytes from the byte
array starting at offset off to the file output
stream.

void write(int b) It is used to write the specified byte to the


file output stream.

FileChannel getChannel() It is used to return the file channel object


associated with the file output stream.

FileDescriptor getFD() It is used to return the file descriptor


associated with the stream.

void close() It is used to closes the file output stream.

Java FileOutputStream Example : write byte


import java.io.* ;
class File1
{
public static void main(String args[])
{
FileOutputStream fout=null;
byte b1[]={'A','B'};
try{
fout=new FileOutputStream("testout.txt");

4 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

fout.write(b1);
fout.close();
System.out.println("success...");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:
Success...
The content of a text file testout.txt is set with the data AB.
testout.txt
AB

4.1.3 Java FileInputStream Class


➢ Java FileInputStream class obtains input bytes from a file. It is used for reading
byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You
can also read character-stream data. But, for reading streams of characters, it is
recommended to use FileReader class.
Java FileInputStream Class Declaration
Let's see the declaration for java.io.FileInputStream class:
public class FileInputStream extends InputStream
Java FileInputStream Class Methods

Method Description

int available() It is used to return the estimated number of bytes that can
be read from the input stream.

int read() It is used to read the byte of data from the input stream.

int read(byte[] b) It is used to read up to b.length bytes of data from the input
stream.

5 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

int read(byte[] b, int It is used to read up to len bytes of data from the input
off, int len) stream.

long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.

FileChannel It is used to return the unique FileChannel object


getChannel() associated with the file input stream.

FileDescriptor It is used to return the FileDescriptor object.


getFD()

protected void It is used to ensure that the close method is call when there
finalize() is no more reference to the file input stream.

void close() It is used to closes the stream.

4.1.4 Java FileInputStream example: read all characters


import java.io.* ;
class File2
{
public static void main(String args[])
{
FileInputStream fin=null;
try
{
fin=new FileInputStream("testout.txt");
int b;
while((b=fin.read())!=-1)
{
System.out.println((char)b);
}
fin.close();
}
catch(Exception e)

6 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

{
System.out.println(e);
}
}
}
Output:
Contents in testout.txt will be displayed
4.1.4 BYTE STREAMS AND CHARACTER STREAMS
BYTE STREAMS
Java ByteArrayOutputStream Class
➢ Java ByteArrayOutputStream class is used to write common data into multiple files.
In this stream, the data is written into a byte array which can be written to multiple
streams later.
➢ The ByteArrayOutputStream holds a copy of data and forwards it to multiple
streams. The buffer of ByteArrayOutputStream automatically grows according to
data.
Java ByteArrayOutputStream Class Declaration
Let's see the declaration for Java.io.ByteArrayOutputStream class:
public class ByteArrayOutputStream extends OutputStream
Java ByteArrayOutputStream Class Constructors

Constructor Description

ByteArrayOutputStream() Creates a new byte array output stream with the initial
capacity of 32 bytes, though its size increases if
necessary.

ByteArrayOutputStream(int Creates a new byte array output stream, with a buffer


size) capacity of the specified size, in bytes.

Java ByteArrayOutputStream class methods

Method Description

int size() It is used to returns the current size of a buffer.

7 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

byte[] toByteArray() It is used to create a newly allocated byte array.

String toString() It is used for converting the content into a string decoding
bytes using a platform default character set.

String toString(String It is used for converting the content into a string decoding
charsetName) bytes using a specified charsetName.

void write(int b) It is used for writing the byte specified to the byte array
output stream.

void write(byte[] b, int off, It is used for writing len bytes from specified byte array
int len starting from the offset off to the byte array output stream.

void writeTo(OutputStream It is used for writing the complete content of a byte array
out) output stream to the specified output stream.

void reset() It is used to reset the count field of a byte array output
stream to zero value.

void close() It is used to close the ByteArrayOutputStream.

Example of Java ByteArrayOutputStream


➢ Let's see a simple example of java ByteArrayOutputStream class to write common
data into 2 files: f1.txt and f2.txt.
Example Program
import java.io.*;
public class DataStreamExample
{
public static void main(String args[])throws Exception
{
FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");
FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");
ByteArrayOutputStream bout=new ByteArrayOutputStream();
bout.write(65);
bout.writeTo(fout1);

8 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

bout.writeTo(fout2);
bout.flush();
bout.close();//has no effect
System.out.println("Success...");
}
}
Output:
Success...
f1.txt:
A
f2.txt:
A

4.2 READING AND WRITING CONSOLE I/O


4.2.1 Java Console Class
➢ The Java Console is a predefined class that is available in io package, it is used to
get user input at run time. It provides methods to read texts and passwords. If you
read password using Console class, it will not be displayed to the user.
➢ The java.io.Console class is attached with system console internally.
➢ Let's see a simple example to read text from console.
String text=System.console().readLine();
System.out.println("Text is: "+text);

9 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

Java Console Class Declaration


Let's see the declaration for Java.io.Console class:
public final class Console extends Object implements Flushable

Java Console Class Methods

Method Description

Reader reader() It is used to retrieve the reader object


associated with the console

String readLine() It is used to read a single line of text from the


console.

String readLine(String fmt, It provides a formatted prompt then reads the


Object... args) single line of text from the console.

char[] readPassword() It is used to read password that is not being


displayed on the console.

char[] readPassword(String It provides a formatted prompt then reads the


fmt, Object... args) password that is not being displayed on the
console.

Console format(String fmt, It is used to write a formatted string to the


Object... args) console output stream.

Console printf(String format, It is used to write a string to the console output


Object... args) stream.

PrintWriter writer() It is used to retrieve the PrintWriter object


associated with the console.

void flush() It is used to flushes the console.

10 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

How to get the object of Console


System class provides a static method console() that returns the singleton instance of Console
class.
public static Console console()
{}
Let's see the code to get the instance of Console class.
Console c=System.console();
Java Console Example to Read Username and Password

import java.io.*;

class Consoleexp

public static void main(String arg[])

String str ; char ch[];

Console C=System.console();

System.out.println("Enter UserName:");

str=C.readLine();

System.out.println("Enter Password:");

ch=C.readPassword();

String S=String.valueOf(ch);

System.out.println("UserName:" +str);

System.out.println("Password:" +S);

11 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

Output

4.2.2 Using Buffered Reader Class


➢ Java BufferedReader class is used to read the text from a character-based input stream.
It can be used to read data line by line by readLine() method.
➢ InputStreamReader class performs two tasks
• Read input stream of keyboard.
• Convert byte streams to character streams.
ExampleProgram: Reading data from console by InputStreamReader and
BufferedReader
import java.io.*;
class Bufferreader
{
public static void main(String arg[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter UserName:");
String name=br.readLine();
System.out.println("Welcome " +name);
}
}

12 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

Output

4.3 READING AND WRITING FILES


4.3.1 Java Reader
The FileReader class of the java.io package can be used to read data (in characters)
from files.
Fields

Modifier and Type Field Description

protected Object lock The object used to synchronize operations on


this stream.

Constructor

Modifier Constructor Description

Protected Reader() It creates a new character-stream reader


whose critical sections will synchronize on
the reader itself.

Protected Reader(Object It creates a new character-stream reader


lock) whose critical sections will synchronize on
the given object.

Methods
➢ read() - reads a single character from the reader
➢ read(char[] array) - reads the characters from the reader and stores in the specified array
➢ read(char[] array, int start, int length) - reads the number of characters equal to length
from the reader and stores in the specified array starting from the position start

13 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

Example
import java.io.*;
class Reader
{
public static void main(String[] args)
{
File infile=new File("a2.txt");
FileReader fr=null;
try
{
fr=new FileReader(infile);
int ch;
while ((ch=fr.read())!= -1)
{
System.out.print((char)ch);
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}

OUTPUT

4.3.2 JAVA FILEWRITER CLASS


Java FileWriter class is used to write character-oriented data to a file. It is character-
oriented class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array because it
provides method to write string directly.
14 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE
UNIT-4 CS3391-OOP

Java FileWriter class declaration


Let's see the declaration for Java.io.FileWriter class:
public class FileWriter extends OutputStreamWriter
Constructors of FileWriter Class

Constructor Description

FileWriter(String file) Creates a new file. It gets file name in string.

FileWriter(File file) Creates a new file. It gets file name in File object.

Methods of FileWriter Class

Method Description

void write(String text) It is used to write the string into FileWriter.

void write(char c) It is used to write the char into FileWriter.

void write(char[] c) It is used to write char array into FileWriter.

void flush() It is used to flushes the data of FileWriter.

void close() It is used to close the FileWriter.

Java FileWriter Example


In this example, we are writing the data in the file testout.txt using Java FileWriter class.
import java.io.*;
class Writer
{
public static void main(String args[])
{
File outfile=new File("A2.txt");
FileWriter fout=null;
try
{

15 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

fout=new FileWriter(outfile);
String s="WELCOME TO JAVA";
fout.write(s);
fout.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Success...");
}
}
Output:
Success...
A2.txt:
WELCOME TO JAVA
4.4 Generic programming

➢ Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of
related types, respectively.
➢ Generics also provide compile-time type safety that allows programmers to catch
invalid types at compile time.
➢ Using Java Generic concept, we might write a generic method for sorting an array of
objects, then invoke the generic method with Integer arrays, Double arrays, String
arrays and so on, to sort the array elements.

4.4.1 Generic Methods

➢ We can write a single generic method declaration that can be called with arguments of
different types. Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately. Following are the rules to define
Generic Methods −

16 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

• All generic method declarations have a type parameter section delimited by


angle brackets (< and >) that precedes the method's return type ( < E > in the
next example).
• Each type parameter section contains one or more type parameters separated by
commas. A type parameter, also known as a type variable, is an identifier that
specifies a generic type name.
• The type parameters can be used to declare the return type and act as
placeholders for the types of the arguments passed to the generic method, which
are known as actual type arguments.
• A generic method's body is declared like that of any other method. Note that
type parameters can represent only reference types, not primitive types (like int,
double and char).
Example

➢ Following example illustrates how we can print an array of different type using a single
Generic method −
public class GenericMethod
{
public static < E > void printArray(E[] elements)
{
for ( E element : elements)
{
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] )
{
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'W','E','L','C','O','M','E' };
Double[] doubleArray={5.10,8.10,76.89,45.67,2.87};
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );

17 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

printArray( charArray );
System.out.println( "Printing Double Array" );
printArray( doubleArray );
}
}

Output

18 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

4.4.2 Bounded Type Parameters

➢ Whenever you want to restrict the type parameter to subtypes of a particular class you
can use the bounded type parameter.
➢ If you just specify a type (class) as bounded parameter, only sub types of that particular
class are accepted by the current generic class. These are known as bounded-types in
generics in Java.
➢ For example, a method that operates on numbers might only want to accept instances
of Number or its subclasses. This is what bounded type parameters are for.
4.4.2.1 Defining bounded-types for class
➢ You can declare a bound parameter just by extending the required class with the type-
parameter, within the angular braces as
➢ Syntax
class Sample <T extends Number>
Example

➢ In the following Java example, the generic class Sample restricts the type parameter to
the sub classes of the Number classes using the bounded parameter.
class Sample <T extends Number>
{
T data;
Sample(T data)
{
this.data = data;
}
public void display()
{
System.out.println("Data value is: "+this.data);
}
}
public class BoundsExample
{
public static void main(String args[])

19 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

{
Sample<Integer> obj1 = new Sample<Integer>(20);
obj1.display();
Sample<Double> obj2 = new Sample<Double>(20.22d);
obj2.display();
Sample<Float> obj3 = new Sample<Float>(125.332f);
obj3.display();
}
}
Output

4.4.3 Generic Classes


➢ A Generic class simply means that the items or functions in that class can be generalized
with the parameter(example T) to specify that we can add any type as a parameter in
place of T like Integer, Character, String, Double or any other user-defined type.
Example Program

public class Area<T>


{
// T is the Datatype like String,
// Integer of which Parameter type,
// the class Area is of
private T t;
public void add(T t)
{
// this.t specify the t variable inside
// the Area Class whereas the right hand
// side t simply specify the value as the
// parameter of the function add()
this.t = t;

20 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

}
public T get()
{
return t;
}
public void getArea()
{
}
public static void main(String[] args)
{
// Object of generic class Area with parameter Type
// as Integer
Area<Integer> rectangle = new Area<Integer>();
// Object of generic class Area with parameter Type
// as Double
Area<Double> circle = new Area<Double>();
rectangle.add(10);
circle.add(2.5);
System.out.println(rectangle.get());
System.out.println(circle.get());
}
}
Output

4.4.5 Restrictions and limitations


To use Java generics effectively, we must consider the following restrictions:
• Cannot Instantiate Generic Types with Primitive Types
• Cannot Create Instances of Type Parameters
• Cannot Declare Static Fields Whose Types are Type Parameters
• Cannot Use Casts or instanceof With Parameterized Types
• Cannot Create Arrays of Parameterized Types

21 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

• Cannot Create, Catch, or Throw Objects of Parameterized Types


• Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase
to the Same Raw Type

4.9.1 Cannot Instantiate Generic Types with Primitive Types


Consider the following parameterized type:
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
// ...
}
When creating a Pair object, you cannot substitute a primitive type for the type parameter K or
V:
Pair<int, char> p = new Pair<>(8, 'a'); // compile-time error
You can substitute only non-primitive types for the type parameters K and V:
Pair<Integer, Character> p = new Pair<>(8, 'a');
Note that the Java compiler autoboxes 8 to Integer.valueOf(8) and 'a' to Character('a'):
Pair<Integer, Character> p = new Pair<>(Integer.valueOf(8), new Character('a'));

4.9.2 Cannot Create Instances of Type Parameters


We cannot create an instance of a type parameter. For example, the following code causes a
compile-time error:
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error
list.add(elem);
}
As a workaround, you can create an object of a type parameter through reflection:
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
E elem = cls.newInstance(); // OK
list.add(elem);
}

22 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

We can invoke the append method as follows:


List<String> ls = new ArrayList<>();
append(ls, String.class);

4.9.3 Cannot Declare Static Fields Whose Types are Type Parameters
A class's static field is a class-level variable shared by all non-static objects of the class. Hence,
static fields of type parameters are not allowed. Consider the following class:
public class MobileDevice<T> {
private static T os;

// ...
}
If static fields of type parameters were allowed, then the following code would be confused:
MobileDevice<Smartphone> phone = new MobileDevice<>();
MobileDevice<Pager> pager = new MobileDevice<>();
MobileDevice<TabletPC> pc = new MobileDevice<>();
Because the static field os is shared by phone, pager, and pc, what is the actual type of os? It
cannot be Smartphone, Pager, and TabletPC at the same time. You cannot, therefore, create
static fields of type parameters.

4.9.4 Cannot Use Casts or instanceof with Parameterized Types


Because the Java compiler erases all type parameters in generic code, you cannot verify which
parameterized type for a generic type is being used at runtime:
public static <E> void rtti(List<E> list) {
if (list instanceof ArrayList<Integer>) { // compile-time error
// ...
}
}
The set of parameterized types passed to the rtti method is:
S = { ArrayList<Integer>, ArrayList<String> LinkedList<Character>, ... }
The runtime does not keep track of type parameters, so it cannot tell the difference between an
ArrayList<Integer> and an ArrayList<String>. The most you can do is to use an unbounded
wildcard to verify that the list is an ArrayList:
public static void rtti(List<?> list) {

23 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

if (list instanceof ArrayList<?>) { // OK; instanceof requires a reifiable type


// ...
}
}
Typically, you cannot cast to a parameterized type unless it is parameterized by unbounded
wildcards. For example:
List<Integer> li = new ArrayList<>();
List<Number> ln = (List<Number>) li; // compile-time error
However, in some cases the compiler knows that a type parameter is always valid and allows
the cast. For example:
List<String> l1 = ...;
ArrayList<String> l2 = (ArrayList<String>)l1; // OK
4.9.5 Cannot Create Arrays of Parameterized Types
You cannot create arrays of parameterized types. For example, the following code does not
compile:
List<Integer>[] arrayOfLists = new List<Integer>[2]; // compile-time error
The following code illustrates what happens when different types are inserted into an array:
Object[] strings = new String[2];
strings[0] = "hi"; // OK
strings[1] = 100; // An ArrayStoreException is thrown.
If you try the same thing with a generic list, there would be a problem:
Object[] stringLists = new List<String>[]; // compiler error, but pretend it's allowed
stringLists[0] = new ArrayList<String>(); // OK
stringLists[1] = new ArrayList<Integer>(); // An ArrayStoreException should be thrown,
// but the runtime can't detect it.
If arrays of parameterized lists were allowed, the previous code would fail to throw the desired
ArrayStoreException.

4.9.6 Cannot Create, Catch, or Throw Objects of Parameterized Types


A generic class cannot extend the Throwable class directly or indirectly. For example, the
following classes will not compile:
// Extends Throwable indirectly
class MathException<T> extends Exception { /* ... */ } // compile-time error
// Extends Throwable directly

24 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

class QueueFullException<T> extends Throwable { /* ... */ // compile-time error


A method cannot catch an instance of a type parameter:
public static <T extends Exception, J> void execute(List<J> jobs) {
try {
for (J job : jobs)
// ...
} catch (T e) { // compile-time error
// ...
}
}
You can, however, use a type parameter in a throws clause:
class Parser<T extends Exception> {
public void parse(File file) throws T { // OK
// ...
}
}

4.9.7 Cannot Overload a Method Where the Formal Parameter Types of Each Overload
Erase to the Same Raw Type
A class cannot have two overloaded methods that will have the same signature after type
erasure.
public class Example {
public void print(Set<String> strSet) { }
public void print(Set<Integer> intSet) { }
}
The overloads would all share the same classfile representation and will generate a compile-
time error.

4.6 Strings
In java, string is basically an object that represents sequence of char values. An array of
characters works same as java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";

25 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
Thejava.lang.String class implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface
The CharSequence interface is used to represent sequence of characters. It is
implemented by String, StringBuffer and StringBuilder classes. It means, we can create string
in java by using these 3 classes.

The java String is immutable i.e. it cannot be changed. Whenever we change any string,
a new instance is created. For mutable string, you can use StringBuffer and StringBuilder
classes.
There are two ways to create String object:
1. By string literal
2. By new keyword

4.6.1 By String literal

Java String literal is created by using double quotes. For Example:


1. String s="welcome";
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:

26 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

String s1="Welcome";
String s2="Welcome";//will not create new instance

In the above example only one object will be created. Firstly JVM will not find any
string object with the value "Welcome" in string constant pool, so it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create new
object but will return the reference to the same instance.
4.6.2 By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal(non-pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non-pool).
Example
public class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}

27 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

Output

4.6.3 String methods

Method Description

char charAt(int index) returns char value for the particular index

int length() returns string length

static String format(String format, returns formatted string


Object... args)

static String format(Locale l, String returns formatted string with given locale
format, Object... args)

String substring(int beginIndex) returns substring for given begin index

String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index

boolean contains(CharSequence s) returns true or false after matching the sequence of


char value

static String join(CharSequence returns a joined string


delimiter, CharSequence... elements)

static String join(CharSequence returns a joined string


delimiter, Iterable<? extends
CharSequence> elements)

boolean equals(Object another) checks the equality of string with object

boolean isEmpty() checks if string is empty

String concat(String str) concatinates specified string

String replace(char old, char new) replaces all occurrences of specified char value

String replace(CharSequence old, replaces all occurrences of specified


CharSequence new) CharSequence

28 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

static String equalsIgnoreCase(String compares another string. It doesn't check case.


another)

String[] split(String regex) returns splitted string matching regex

String[] split(String regex, int limit) returns splitted string matching regex and limit

String intern() returns interned string

int indexOf(int ch) returns specified char value index

int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index

int indexOf(String substring) returns specified substring index

int indexOf(String substring, int returns specified substring index starting with
fromIndex) given index

String toLowerCase() returns string in lowercase.

String toLowerCase(Locale l) returns string in lowercase using specified locale.

String toUpperCase() returns string in uppercase.

String toUpperCase(Locale l) returns string in uppercase using specified locale.

String trim() removes beginning and ending spaces of this


string.

static String valueOf(int value) converts given type into string. It is overloaded.

4.6.4 JAVA STRINGBUFFER CLASS

➢ Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.
IMPORTANT CONSTRUCTORS OF STRINGBUFFER CLASS

Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified string..

29 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.

IMPORTANT METHODS OF STRINGBUFFER CLASS

Modifier and Method Description


Type

public append(String s) It is used to append the specified string with this


synchronized string. The append() method is overloaded like
StringBuffer append(char), append(boolean), append(int),
append(float), append(double) etc.

public insert(int offset, String It is used to insert the specified string with this
synchronized s) string at the specified position. The insert()
StringBuffer method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.

public replace(int startIndex, It is used to replace the string from specified


synchronized int endIndex, String str) startIndex and endIndex.
StringBuffer

public delete(int startIndex, It is used to delete the string from specified


synchronized int endIndex) startIndex and endIndex.
StringBuffer

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least equal to


minimumCapacity) the given minimum.

public char charAt(int index) It is used to return the character at the specified
position.

public int length() It is used to return the length of the string i.e.
total number of characters.

30 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

public String substring(int It is used to return the substring from the


beginIndex) specified beginIndex.

public String substring(int It is used to return the substring from the


beginIndex,int specified beginIndex and endIndex.
endIndex)

WHAT IS A MUTABLE STRING?

➢ A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.

STRING BUFFER CLASS METHODS

1) StringBuffer Class append() Method

➢ The append() method concatenates the given argument with this String.

Example Program

class StringBufferExample

public static void main(String args[])

StringBuffer sb=new StringBuffer("Hello ");

sb.append("Java"); //now original string is changed

System.out.println(sb); //prints Hello Java

OUTPUT

Hello Java

31 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

2. StringBuffer insert() Method

➢ The insert() method inserts the given String with this string at the given position.

Example Program

class StringBufferExample2{

public static void main(String args[])

StringBuffer sb=new StringBuffer("Hello ");

sb.insert(1,"Java");//now original string is changed

System.out.println(sb);//prints HJavaello

OUTPUT

HJavaello

3. StringBuffer replace() Method

➢ The replace() method replaces the given String from the specified beginIndex and
endIndex.
Example Program

class StringBufferExample3{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}

32 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

OUTPUT
HJavalo

4. StringBuffer delete() Method


➢ The delete() method of the StringBuffer class deletes the String from the specified
beginIndex to endIndex.
Example Program
class StringBufferExample4{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb); //prints Hlo
}
}
OUTPUT
Hlo
5.StringBuffer reverse() Method
➢ The reverse() method of the StringBuilder class reverses the current String.
Example Program
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);// prints olleH
}
}
OUTPUT
olleH
6.StringBuffer capacity() Method
➢ The capacity() method of the StringBuffer class returns the current capacity of the
buffer.

33 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

➢ The default capacity of the buffer is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.

Example Program

class StringBufferExample6{

public static void main(String args[])

StringBuffer sb=new StringBuffer();

System.out.println(sb.capacity());//default 16

sb.append("Hello");

System.out.println(sb.capacity());//now 16

sb.append("java is my favourite language");

System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2

Output:

16

16

34

7.StringBuffer ensureCapacity() method

➢ The ensureCapacity() method of the StringBuffer class ensures that the given capacity
is the minimum to the current capacity. If it is greater than the current capacity, it
increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16,
it will be (16*2)+2=34.

34 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

Example Program

class StringBufferExample7

public static void main(String args[])

StringBuffer sb=new StringBuffer();

System.out.println(sb.capacity()); //default 16

sb.append("Hello");

System.out.println(sb.capacity()); //now 16

sb.append("java is my favourite language");

System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2

sb.ensureCapacity(10); //now no change

System.out.println(sb.capacity()); //now 34

sb.ensureCapacity(50); //now (34*2)+2

System.out.println(sb.capacity()); //now 70

Output

35 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE


UNIT-4 CS3391-OOP

Difference between String and StringBuffer

36 PREPARED BY: BASTIN ROGERS C, AP/CSE, SMCE

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy