Unit IV
Unit IV
Unit IV
In Java input and output operations are performed using streams. And Java
implements streams within the classes that are defined in java.io
There are basically two types of streams used in Java.
1. Byte stream
2. Character stream
Byte Stream
int read()
int read(char buf[])
int read(char buf[], int offset, int length)
InputStream defines the same methods but for reading bytes and arrays of bytes:
int read()
int read(byte buf[])
int read(byte buf[], int offset, int length)
Writer and OutputStream are similarly parallel. Writer defines these methods for writing
characters and arrays of characters:
int write(int c)
int write(char buf[])
int write(char buf[], int offset, int length)
int write(int c)
int write(byte buf[])
int write(byte buf[], int offset, int length)
There are two super classes used in There are two super classes used in
byte stream and those are – byte stream and those are
InputStream and OutputStream Reader and Writer
Not specifically designed for string Convenient methods for string
operations operations
It never supports Unicode characters It supports Unicode characters
Strings
Definition:
String is a sequence of characters. But in Java, a string is an object that represents a
sequence of characters. The java.lang.String class is used to create string object.
Refer to the diagrammatic representation for better understanding: In the above image, two
Strings are created using literal i.e “Apple” and “Mango”. Now, when third String is created
with the value “Apple”, instead of creating a new object, the already present object reference
is returned.
Example: Creating Strings
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 character array to string
String s3=new String(“example);//creating java string by using new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output
java
strings
example
true
true
false
equalsIgnoreCase(String) method
The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case
differences. This method returns true if the strings are equal, and false if not.
class Main {
public static void main(String[] args) {
String str1 = "Learn Java";
String str2 = "learn java";
String str3 = "Learn Kolin";
Boolean result;
// comparing str1 with str2
result = str1.equalsIgnoreCase(str2);
System.out.println(result); // true
}
}
2) By == operator
The = = operator compares references not values.
class Simple{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
Output:
true
false
3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values
compare less than, equal, or greater than.
o Suppose s1 and s2 are two string variables. If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
Example: compareTo() method:
class Simple{
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 )
}
}
Output:
0
1
-1
class Test
Output
2) By concat() method
concat() method concatenates the specified string to the end of current string.
class Test
System.out.println(str.concat(fruit));
}
Output
class Str_reverse
for(int i=S.length()-1;i>=0;i--)
System.out.print(str[i]);
Output
Character Extraction
There is a method called charAt(index) with the help of which we can extract the
character denoted by some index in the array.
Example
String fruit=new String("mango");
char ch;
ch=fruit.charAt(2);
System.out.println(ch);
Output: n
Searching for the Substring
The Java substring () method extracts a part of the string (substring) and returns it.
Syntax of substring():string.substring(int startIndex, int endIndex)
Java substring() With Only Start Index Java substring() With Start and End Index
class Main { class Main {
public static void main(String[] args) { public static void main(String[] args) {
String str1 = "program"; String str1 = "program";
// 1st to the 5th character
// 1st character to the last character System.out.println(str1.substring(0, 5)); // progr
System.out.println(str1.substring(0)); // program
class replaceDemo
System.out.println(s);
Output
Nasha as Indaan
We can convert the given string to either upper case or lower case using the methods
toUpperCase() and toLowerCase(). Following program demonstrates the handling of the case
of the string -
class caseDemo
Output
D:\>javac caseDemo.java
D:\>java caseDemo
The Java String class length() method finds the length of a string.
StringBuffer Class
}
}
Output
F:\test>javac StringBuffDemo1.java
F:\test>java StringBuffDemo1
The length is 4
The capacity is 20
StringBuffer: append()
The append() method is used to append the string or number at the end of the string.
import java.io.*;
class Main
{
public static void main(String[] args)
{
StringBuffer str = new StringBuffer("Tech");
str.append("Vidvan"); // appends a string in the previously defined string.
System.out.println(str);
str.append(0); // appends a number in the previously defined string.
System.out.println(str);
}
}
Output:
TechVidvanTechVidvan0
StringBuffer: insert()
The insert() method is used to insert the string into the previously defined string at a
particular indexed position.
In the insert method as a parameter, we provide two-argument first is the index and
second is the string.
Example:
str.insert(13,new_str);
str.insert(0,new_str);
Output
F:\test>javac StringBuffDemo4.java
F:\test>java StringBuffDemo4
F:\test>
StringBuffer: delete()
The delete() method deletes a sequence of characters from the StringBuffer object.
Syntax:
stringName.delete(int startIndex, int
endIndex)
import java.io. * ;
myString.delete(0, 4);
Output:
StringBuffer deleteCharAt()
The deleteCharAt() method deletes only the character at the specified index.
Syntax:
stringName.deleteCharAt(int index)
Example:
import java.io. * ;
public class DeleteCharAtDemo {
public static void main(String[] args) {
StringBuffer myString = new StringBuffer("TechVidvanJava");
System.out.println("Original String: " + myString);
myString.deleteCharAt(0);
System.out.println("Resulting String after deleting a character at 0th index: " + myString);
myString.deleteCharAt(6);
System.out.println("Resulting String after deleting a character at 6th index: " + myString);
}
}
Output:
Original String: TechVidvanJava
Resulting String after deleting a character at 0th index: echVidvanJava
Resulting String after deleting a character at 6th index: echVidanJava
StringBuffer replace()
The replace() method of the StringBuffer class replaces a sequence of characters with another
sequence of characters.
Syntax:
str.setCharAt(1,'o');'
str.setCharAt(2,'d');
str.setLength(3);
Output
F:\test>javac StringBuffDemo2.java
F:\test>java StringBuffDemo2
String StringBuffer
The String class is immutable. The StringBuffer class is mutable.
String is slow and consumes more StringBuffer is fast and consumes less
memory when we concatenate too memory when we concatenate two
many strings because every time it strings.
creates new instance.
String class uses String constant pool. StringBuffer uses Heap memory
o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
Create a File
The createNewFile() method returns true when it successfully creates a new file and
returns false when the file already exists.
Program
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:FileOperationExample.txt");
if (f0.createNewFile()) {
System.out.println("File " + f0.getName() + " is created successfully.");
} else {
System.out.println("File is already exist in the directory.");
}
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
}
Output
Get File Information
The operation is performed to get the file information. We use several methods to get the
information about the file like name, absolute path, is readable, is writable and length.
Example:
// Import the File class
import java.io.File;
class FileInfo {
public static void main(String[] args) {
// Creating file object
File f0 = new File("D:FileOperationExample.txt");
if (f0.exists()) {
// Getting file name
System.out.println("The name of the file is: " + f0.getName());
Write to a File
The next operation which we can perform on a file is "writing into a file".
In order to write data into a file, we will use the FileWriter class and its write()
method together.
We need to close the stream using the close() method to retrieve the allocated
resources.
Program
// Importing the FileWriter class
import java.io.FileWriter;
// Importing the IOException class for handling errors
import java.io.IOException;
class WriteToFile {
public static void main(String[] args) {
try {
FileWriter fwrite = new FileWriter("D:FileOperationExample.txt");
// writing the content into the FileOperationExample.txt file
fwrite.write("A named location used to store related information is referred to as a
File.");
// Closing the stream
fwrite.close();
System.out.println("Content is successfully wrote to the file.");
} catch (IOException e) {
System.out.println("Unexpected error occurred");
e.printStackTrace();
}
}
}
Output:
Read from a File
The next operation which we can perform on a file is "read from a file".
In order to write data into a file, we will use the Scanner class.
Program
// Importing the File class
import java.io.File;
// Importing FileNotFoundException class for handling errors
import java.io.FileNotFoundException;
// Importing the Scanner class for reading text files
import java.util.Scanner;
class ReadFromFile {
public static void main(String[] args) {
try {
// Create f1 object of the file to read data
File f1 = new File("D:FileOperationExample.txt");
Scanner dataReader = new Scanner(f1);
while (dataReader.hasNextLine()) {
String fileData = dataReader.nextLine();
System.out.println(fileData);
}
dataReader.close();
} catch (FileNotFoundException exception) {
System.out.println("Unexcpected error occurred!");
exception.printStackTrace();
}
}
}
Output:
Delete a File
The next operation which we can perform on a file is "deleting a file".
In order to delete a file, we will use the delete() method of the file.
We don't need to close the stream using the close() method because for deleting a
file, we neither use the FileWriter class nor the Scanner class.
Program
// Importing the File class
import java.io.File;
class DeleteFile {
public static void main(String[] args) {
File f0 = new File("D:FileOperationExample.txt");
if (f0.delete()) {
System.out.println(f0.getName()+ " file is deleted successfully.");
} else {
System.out.println("Unexpected error found in deletion of the file.");
}
}
}
Output:
DataInputStream / DataOutputStream
DataInputStream reads bytes from the stream and converts them into appropriate primitive
data types whereas the DataOutputStream converts the primitive data types into the bytes and
then writes these bytes to the stream.
import java.io.*;
class DataStream Prog
{
public static void main(String[] args) throws Exception
{
DataOutputStream obj=new DataOutputStream gibi mene(new FileOutputStream("in.txt"));
obj.write UTF("Archana");
obj.writeDouble(44.67);
obj.writeUTF("Keshavanand");
obj.writeInt(77);
obj.writeUTF("Chitra");
obj.writeChar('a');
obj.close();
DataInputStream in=new DataInputStream(new FileInputStream("in.txt"));
System.out.println("\nFollowing are the contents of the 'in.txt' file");
System.out.println(in.readUTF()+":"+in.readDouble());
System.out.println(in.readUTF()+":"+in.readInt());
System.out.println(in.readUTF()+":"+in.readChar());
}
}
BufferedInputStream / BufferedOutputStream
The BufferedInputStream and BufferedOutputStream is an efficient class used for speedy
read and write operations. All the methods of BufferedInputStream and
BufferedOutputStream class are inherited from InputStream and OutputStream classes.
import java.io.*;
class BufferedStreamProg
{
public static void main(String[] args)throws Exception
{
DataOutputStream obj=new DataOutputStream(new BufferedOutputStream(new
FileOutputStream("in.txt")));
obj.writeUTF("Archana");
obj.writeDouble(44.67);
obj.writeUTF("Keshavanand");
obj.writeInt(77);
obj.writeUTF("Chitra");
obj.writeChar('a');
obj.close();
DataInputStream in=new DataInputStream(new BufferedInputStream(new
FileInputStream("in.txt")));
System.out.println("\nFollowing are the contents of the 'in.txt' file");
System.out.println(in.readUTF()+":"+in.readDouble());
System.out.println(in.readUTF()+":"+in.readInt());
System.out.println(in.readUTF()+":"+in.readChar());
}
}
Generic Programming
It refers to writing code that will work for many types of data.
All generic declarations have a type parameter section delimited by angle brackets (<
and >).
Generic programming = programming with classes and methods.
Each type parameter section contains one more type parameters separated by
<X,Y,Z>
All generic method’s body is declared like that of any other method. No that type
parameters can represent only reference types, not primitive types (like int, double
and String).
Advantages of Generic Programming
Code Reuse: Define a method/class/ interface once and use for any data types.
Type Safety: Generics make errors to appear compile time than at runtime (It’s
always better to know problems in your code at compile time rather than making
your code fail at run time).
Individual Type Casting is not needed.
Output
> javac genpro.java
> java genpro
10
20
100.5
200.2
Hello
World
Output
100.5
200.2
Hello
World
Generic Classes
A generic class declaration looks like a normal class declaration, except that the class
name is followed by a type parameter section.
A generic class can have one or more type parameters separated by commas. These
classes are known as parameterized classes. They accept one or more parameters.
To create objects of generic class, we use following syntax.
o udcn <Type> obj = new udcn <Type>()
o udcn- user defined class name
o Type- Any one of valid data type such Integer, Double, String etc
class gsample
{
public static void main(String args[])
{
// instance of Integer Type
Test < Integer> iObj= new Test<Integer>(15);
System.out.println(iObj.getObject());
Output
>javac gsample.java
> java gsample
15
Hello World
Program for Generic classes in Two Data Types
class Test <T,U>
{
T obj1; // An object of Type T
U obj2;// An object of type U
Test(T obj1, U obj2)
{
this.obj1=obj1;
this.obj2=obj2;
}
public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}
class gtsample
{
public static void main(String [] args)
{
Test<String, Integer> obj= new Test<String, Integer>(“Hai”,15);
obj.print();
Test<String, String> obj= new Test<String, String>(“Sachin”, “Tendulkar”);
obj1.print();
Test<Integer, String>obj2=new Test<Integer, String>(50, “Tendulkar”);
obj2.print();
Test<Integer, Integer> obj3= new Test<Integer, Integer>(50,100);
obj3.print();
}
}
OUTPUT
>javac gtsample.java
>java gtsample
Hai
15
Sachin
Tendulkar
50
Tendulkar
50
100
OUTPUT
>javac gmethod.java
>java gmethod
java.lang.Integer=11
java.lang.String=Helloworld
java.lang.Double=1.0
1. In Java, generic types are compile time entities. The runtime execution is possible
only if it is used along with raw type.
2. Primitive type parameters is not allowed for generic programming.
For example: Stack<int> is not allowed.
3. For the instances of generic class throw and catch instances are not allowed.
For example:
public class Test<T> extends Exception
{
//code // Error:can't extend the Exception class
}
4. Instantiation of generic parameter T is not allowed.
For example:
new T() //Error
new T[10]
5. Arrays of parameterized types are not allowed.
For example:
new Stack<String>[10];//Error
6. Static fields and static methods with type parameters are not allowed.
Input and Output streams. Explain with illustration (Very Important Question)
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system
to make input and output operation in java. In general, a stream means continuous flow of
data. Streams are clean way to deal with input/output without having every part of your code
understand the physical.
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given
below.
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.
Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
Some important Character stream classes
We use the object of BufferedReader class to take inputs from the keyboard.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}
Reading Strings in Java
To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException
import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}
Program to read from a file using BufferedReader class
import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
import java. Io *;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}