Professional Documents
Culture Documents
Unit 4 - Oops - Notes
Unit 4 - Oops - Notes
Unit 4 - Oops - Notes
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
1
SCE/CSBS/CS3391/V.S
File Operations
o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
A pathname
A parent pathname and a child pathname
A URI (uniform resource identifier)
We can use one of the following constructors of the File class to create a file:
File(String pathname)
File(File parent, String child)
File(String parent, String child)
File(URI uri)
import java.io.File;
// Importing the IOException class for handling errors
import java.io.IOException;
class CreateFile {
public static void main(String args[]) {
try {
// Creating an object of a file
File f0 = new File("D:\\FileExample.txt");
if (f0.createNewFile()) {
System.out.println("File " + f0.getName() + " is created successfully.");
} else {
System.out.println("File is already exist in the directory.");
}
System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());
E:\Java_MAT\pgms\29_09>java
29_09>java CreateFile
File FileExample.txt is created successfully.
The absolute path of the file is: D:\FileExample.txt
D:
Is file writeable?: true
Is file readable true
The size of the file in bytes is: 0
The next operation which we can perform on a file is "writing into a file". file" In order to
write data into a file, we will use the FileWriter class and its write() method together.
Java I/O (Input and Output) is used to process the input and produce the output.
output
Java uses the concept of a stream to make I/O operations fast. The java.i
java.io package contains all
the classes required for input and output operations.
3
SC
CE/CSBS/CS3391/V.S
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
ams are created for us automatically. All these streams are attached with the
In Java, 3 streams
console.
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 superclass of all classes representing an output
sends them to some sink.
stream of bytes. An output stream accepts output bytes and sends
Types of Streams
Depending upon the data a stream holds, it can be classified into:
1. Byte Stream
2. Character Stream
1. Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called InputStream and
OutputStream.
4
SC
CE/CSBS/CS3391/V.S
Useful methods of OutputStream
Method Description
4) public void close()throws IOException is used to close the current output stream.
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
The InputStream class provides different methods that are implemented by its subclasses. Here
are some of the commonly used methods:
read() - reads one byte of data from the input stream
read(byte[] array) - reads bytes from the stream and stores in the specified array
available() - returns the number of bytes available in the input stream
mark() - marks the position in the input stream up to which data has been read
reset() - returns the control to the point in the stream where the mark was set
markSupported() - checks if the mark() and reset() method is supported in the stream
skips() - skips and discards the specified number of bytes from the input stream
close() - closes the input stream
2. Character Stream
Character stream is used to read and write a single character of data.
All the character stream classes are derived from base abstract classes Reader and Writer.
5
SCE/CSBS/CS3391/V.S
When to use Character / Byte streams?
Character streams are used when we want to process text files. As we know Java stores
characters in Unicode format. Character stream processes data character by character. Character
stream performs input and output operations
operati bit Unicode which is equivalent to the size of
of 16-bit
a character in Java.
Byte streams are used to process raw data like binary files. If we have a file that contains binary
data, then it will be appropriate to use Byte stream. They can be used to read/write
read data of 8-bit
bytes.
6
SC
CE/CSBS/CS3391/V.S
Examples of Byte streams
public class ReadFile {
//3. to read file contents line-by-line /to convert byte stream to character stream
InputStreamReaderfile_source = new InputStreamReader(fin);
}
else {
System.out.println("File is not available!");
}
}
}
import java.io.FileOutputStream;
7
SCE/CSBS/CS3391/V.S
public class WriteFile {
fout.write(data);
System.out.println("file created");
fout.close();
}
import java.io.FileWriter;
try {
// Creates a FileWriter
FileWriter output = new FileWriter("output.txt");
8
SCE/CSBS/CS3391/V.S
// Writes the string to the file
output.write(data);
catch (Exception e) {
e.getStackTrace();
}
}
}
--------------------------------
Example:
import java.io.FileWriter;
import java.io.FileReader;
try {
// creates a file reader
FileReader fr=new FileReader("FileIn.txt");
// Creates a FileWriter
FileWriter output = new FileWriter("Upperoutput.txt");
int i;
while((i=fr.read())!=-1) {
// read each char as byte and convert to uppercase
char outChar = Character.toUpperCase((char) i);
// write to the output file
output.write(outChar);
9
SCE/CSBS/CS3391/V.S
}
// Closes the writer
output.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
@Override
public String toString() {
return "Name:" + name + "\nAge: " + age + "\nGender: " + gender;
}
}
10
SCE/CSBS/CS3391/V.S
public class WriterReaderObject {
try {
FileOutputStream f = new FileOutputStream(new File("myObjects.txt"));
ObjectOutputStream o = new ObjectOutputStream(f);
o.close();
f.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} /* catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} */
Strings in Java
In Java, a string is a sequence of characters. For example, "hello" is a string containing a
sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use double quotes to represent a string in Java. For example,
// create a string
String type = "Java programming";
Here, we have created a string variable named type. The variable is initialized with the string
Java Programming.
11
SCE/CSBS/CS3391/V.S
There are two ways to create String object:
1. By string literal
2. By new keyword
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
In the above example, we have created three strings named first, second, and third. Here, we are
directly creating strings like primitive types.
However, there is another way of creating Java strings (using the new keyword) which is given
later in this notes.
Note: Strings in Java are not primitive types (like int, char, etc). Instead, all strings are objects
of a predefined class named String.
And, all string variables are instances of the String class.
java.lang.String package contains all required classes, methods, properties, interface for strings
1.String s = new String();
2. String st = new String(String str);
String s2 = new String("Hello Java");
12
SCE/CSBS/CS3391/V.S
String s3 = new String(chars);
4. String str = new String(char chars[ ], intstartIndex, int count);
char chars[ ] = { 'w', 'i', 'n', 'd', 'o', 'w', 's' };
String str = new String(chars, 2, 3); ” ndo”
5. String(byte byteArr[ ])
public class ByteArray
{
public static void main(String[] args)
{
byte b[] = { 97, 98, 99, 100 }; // Range of bytes: -128 to 127. These byte values will be
converted into corresponding characters.
String s = new String(b);
System.out.println(s); abc
}
class Main {
public static void main(String[] args) {
13
SCE/CSBS/CS3391/V.S
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer
and StringBuilder classes implement it. It means, we can create strings in Java by using these
three classes.
14
SCE/CSBS/CS3391/V.S
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder
classes.
15
SCE/CSBS/CS3391/V.S
7 boolean contains(CharSequence s) It returns true or false after matching the
sequence of char value.
13 String replace(char old, char new) It replaces all occurrences of the specified
char value.
17 String[] split(String regex, int limit) It returns a split string matching regex and
limit.
16
SCE/CSBS/CS3391/V.S
22 intindexOf(String substring, It returns the specified substring index
intfromIndex) starting with given index.
Example 1
class Teststringcomparison1{ class Teststringcomparison2{ class Teststringcomparison3{
public static void main(String args[]){ public static void main(String args[] public static void main(String
String s1="Sachin"; ){ args[]){
String s2="Sachin"; String s1="Sachin"; String s1="Sachin";
String s3=new String("Sachin"); String s2="SACHIN"; String s2="Sachin";
17
SCE/CSBS/CS3391/V.S
String s4="Saurav"; String s3=new String("Sachin
System.out.println(s1.equals(s2));//true System.out.println(s1.equals(s2)); ");
//false System.out.println(s1==s2);
System.out.println(s1.equals(s3));//true System.out.println(s1.equalsIgnoreCa //true (because both refer to sa
se(s2));//true me instance)
System.out.println(s1.equals(s4));//false } System.out.println(s1==s3);
} //false(because s3 refers to insta
} nce created in nonpool)
} }
}
Example 2
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2)); //0
System.out.println(s1.compareTo(s3)); //1(because s1>s3)
System.out.println(s3.compareTo(s1)); //-1(because s3 < s1 )
}
}
In Java, String concatenation forms a new String that is the combination of multiple
strings. There are two ways to concatenate strings in Java:
18
SCE/CSBS/CS3391/V.S
Example of string concatenation
A part of String is called substring. Java String class provides the built-in substring() method
that extract a substring from the given string by using the index values passed as an argument.
Example :
class TestSubstring{
public static void main(String args[]){
String s="SachinTendulkar";
System.out.println("Original String: " + s);
System.out.println("Substring starting from index 6: " +s.substring(6));//Tendulkar
System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6)); //Sachin
}
}
Output is:
Original String: SachinTendulkar
19
SCE/CSBS/CS3391/V.S
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6: Sachin
An Example of various built-in function of a String class
public class Stringoperations
{
public static void main(String ar[])
{
// builtin functions of String class
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s); //Sachin(no change in original)
System.out.println("-----------------------------------------------");
System.out.println("-----------------------------------------------");
System.out.println(s.length());//6
System.out.println("----- valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into String----");
int a=10;
String ss=String.valueOf(a);
System.out.println(ss+10);
20
SCE/CSBS/CS3391/V.S
System.out.println("-----------------------------------------------");
String s2="Java is a programming language. Java is a platform. Java is an Island.";
String replaceString=s2.replace("Java","Gova"); //replaces all occurrences of "Java" to "Gova"
System.out.println(replaceString);
}
}
}
}
Output:
Hello Java
Python
In the above example, the orginal value of the StringBuffer is changes wheres that of the String
is not changed.
Important Constructors of StringBuffer Class
Constructor Description
21
SCE/CSBS/CS3391/V.S
capacity of 16.
//The append() method concatenates the given argument with this String.
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Hello Java
//The insert() method inserts the given String with this string at the given position.
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb); //prints HJavaello Java
//The replace() method replaces the given String from the specified beginIndex and
endIndex.
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
//The delete() method of the StringBuffer class deletes the String from the specified
beginIndex to endIndex.
sb.delete(1,3);
System.out.println(sb);//prints Hvavaello Java
//The reverse() method of the StringBuilder class reverses the current String.
sb.reverse();
System.out.println(sb); //prints avaJ olleavavH
22
SCE/CSBS/CS3391/V.S
//The capacity() method of the Strin gBuffer class returns the current capacity of the buffer.
StringBuffer
The default capacity of the buffer is 16.
System.out.println(sb.capacity()
capacity());//now 16
}
}
NOTE: like StringBuffer class , java also has StringBuilder class ( which is also
mutable)
StringBuffer StringBuilder
StringBuffer operations are thread-safe
thread and StringBuilder operations are not thread
thread-safe are not-
synchronized synchronized.
StringBuffer is to used when multiple threads are StringBuilder is used in a single-threaded
single
working on the same String environment.
StringBuffer performance is slower when compared StringBuilder performance is faster when compared
to StringBuilder to StringBuffer
Syntax: StringBuffer var = new StringBuffer(str); Syntax: StringBuilder var = new StringBuilder(str);
23
SC
CE/CSBS/CS3391/V.S
Generics in Java
Generics is a concept in Java where you can enable a class, interface and, method, accept all
(reference) types as parameters. In other words it is the concept which enables the users to
choose the reference type that a method, constructor of a class accepts, dynamically.
By defining a class generic you are making it type-safe i.e. it can act up on any datatype. To
understand generics let us consider an example −
class Student{
Integer age;
Student(Integer age){
this.age = age;
}
public void display() {
System.out.println("Value of age: "+this.age);
}
}
public class NoNGenericsExample {
public static void main(String args[]) {
Student std = new Student(25);
std.display();
}
}
24
SCE/CSBS/CS3391/V.S
Student std = new Student("25");
std.display();
it gives error as the constructor will take only int not string
or, if we want our class to work with different datatype then , we should add the different
constructor ( constructor overloading) as folows:
class Student{
String age;
Student(String age){
this.age = age;
}
}
Or,
class Student{
Float age;
Student(Float age){
this.age = age;
}
}
So,
When you declare generic types they can act upon any datatypes and, they are known as
parameterized types. You cannot use primitive datatypes in generics.
To create a class of generic type by using generic parameter T or, GT as −
class Student <T>{
T obj;
}
Where T (generic parameter) represents the datatype of the object you can pass to the
constructor of this class. This will be determined at the compilation time.
While instantiating the class you need to/can choose the type of the generic parameter as
−
Student<Float> obj = new Student<Float>();
25
SCE/CSBS/CS3391/V.S
class Student<T>{
T age;
Student(T age){
this.age = age;
}
public void display() {
System.out.println("Value of age: "+this.age);
}
}
public class GenericsExample {
public static void main(String args[]) {
Student<Float> std1 = new Student<Float>(25.5f);
std1.display();
Student<String> std2 = new Student<String>("25");
std2.display();
Student<Integer> std3 = new Student<Integer>(25);
std3.display();
}
}
Output
Value of age: 25.5
Value of age: 25
Value of age: 25
26
SCE/CSBS/CS3391/V.S
Code reuse − You can write a method or, Class or, interface using generic type
once and you can use this code multiple times with various parameters.
For certain types, with formal types, you need to cast the object and use. Using
generics (in most cases) you can directly pass the object of required type without
relying on casting.
// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}
obj.print();
}
}
Output is : RamLakshman
15
NOTE:
When we declare an instance of a generic type, the type argument passed to the type
parameter must be a reference type. We cannot use primitive data types like int, char.
Test<int> obj = new Test<int>(20); //ERROR
Test<Integer> obj=new Text<Integer>(20); // correct
Generic Method
Like the generic class, we can create a generic method that can accept any type of
arguments. Here, the scope of arguments is limited to the method where it is declared. It
allows static as well as non-static methods.
Let's see a simple example of java generic method to print array elements. We are using
here E to denote the element.
28
SCE/CSBS/CS3391/V.S
System.out.println( "Printing Integer Array" );
printArray( intArray );
Bounded-types in generics
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.
You can declare a bound parameter just by extending the required class with the type-
parameter, within the angular braces as −
class Sample <T extends Number>
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.
Output
30
SCE/CSBS/CS3391/V.S