Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit IV

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 42

UNIT IV

I/O, GENERICS, STRING HANDLING


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.
I/O Basics
Stream Definition:
 Stream is basically a channel on which the data flow from sender to receiver.
 An input object that reads the stream of data from a file is called input stream.
 The output object that writes the stream of data to a file is called output stream.

Byte Stream and Character Stream

 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

 The byte stream is used for inputting or outputting the bytes


 There are two super classes in byte stream and those are InputStream and
OutputStream from which most of the other classes are derived.
 These classes define several important methods such as read () and write ().
Character Stream

 The character stream is used for inputting or outputting the characters.


 There are two super classes in character stream and those are Reader and Writer.
 These classes handle the Unicode character streams.
 The two important methods defined by the character stream classes are read () and
Write () for reading and writing the characters of data.
 Various Reader and Writer classes are -

Reader and InputStream


Reader and InputStream define similar APIs but for different data types. For example, Reader
contains these methods for reading characters and arrays of characters:

 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

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)

And OutputStream defines the same methods but for bytes:

 int write(int c)
 int write(byte buf[])
 int write(byte buf[], int offset, int length)

Comparison between Byte Stream and Character Stream (2 mark Question)

Byte Stream Character Stream


 The byte stream is used for inputting  The character stream is used for
and outputting the bytes inputting and outputting characters

 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.

How to create String object?


There are two ways to create a String object:
1. By string literal: Java String literal is created by using double quotes.
For Example: String s=“Welcome”;
2. By new keyword: Java String is created by using a keyword “new”.
For example: String s=new String(“Welcome”);
Syntax of String Constructor

Java String Pool:


Java String pool refers to collection of Strings which are stored in heap memory. In this,
whenever a new object is created,
1) String pool first checks whether the object is already present in the pool or not.
2) If it is present, then same reference is returned to the variable
3) else new object will be created in the String pool and the respective reference will be
returned.

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

Immutable String in Java


In java, string objects are immutable. Immutable simply means un-modifiable or
unchangeable.
 Once string object is created its data or state can't be changed but a new string object
is created.
 Let's try to understand the immutability concept by the example given below:
class Simple{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable
objects
}
}
Output: Sachin
Methods
Following are some commonly defined methods by a string class -

String Comparison Java [Nov / Dec 2022 University Question]


 There are three ways to compare String objects:
o By equals() method
o By = = operator
o By compareTo() method
1) By equals () method
o Equals () method compares the original content of the string. It compares
values of string for equality.
o String class provides two methods:
 public boolean equals(Object another){} compares this string to the
specified object.
 public boolean equalsIgnoreCase(String another){} compares this
String to another String, ignoring case.
 Example: equals() method
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output:

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

String Concatenation in Java:


 Concatenating strings form a new string i.e. the combination of multiple strings.
There are two ways to concat string objects:
1. By + (string concatenation) operator
2. By concat() method
1) By + (string concatenation) operator
String concatenation operator is used to add strings. For Example:
//Example of string concatenation operator

class Test

public static void main(String[] args)

String fruit new String("mango");

System.out.println("I like "+fruit +" very much");

Output

I like mango very much

2) By concat() method
concat() method concatenates the specified string to the end of current string.

class Test

public static void main(String[] args)

String str=new String("I like ");

String fruit=new String("mango very much");

System.out.println(str.concat(fruit));
}

Output

I like mango very much

String Reverse [University Question Nov/Dec 2022]


There is no direct method for reversing the string but we can display it in reverse direction.

class Str_reverse

public static void main(String[] args)

char str[] = {'S','T', 'R','I', 'N','G'};

String S=new String(str);

System.out.println("The string S is "+S);

System.out.print("The string written in Reverse order ");

for(int i=S.length()-1;i>=0;i--)

System.out.print(str[i]);

Output

The string S is STRING

The string written in Reverse order GNIRTS

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

// 4th to the 5th character


// 4th character to the last character System.out.println(str1.substring(3, 5)); // gr
System.out.println(str1.substring(3)); // gram }
} }
}

Replacing the Character from String

We can replace the character by some desired character. For example

Java Program [replace Demo.java]

class replaceDemo

public static void main(String[] args)

String str=new String("Nisha is Indian ");


String s= str.replace('i','a');

System.out.println(s);

Output

D:\>javac replace Demo.java

D:\>java replace Demo

Nasha as Indaan

Upper and Lower Case

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 -

Java Program [CaseDemo.Java]

class caseDemo

public static void main(String[] args)

String str=new String("Nisha is Indian ");

System.out.println("\n The original string is: "+str);

String str_upper= str.toUpperCase();

System.out.println("\n The Upper case string is: "+str_upper);

String str_lower= str.toLowerCase();


System.out.println("\n The Lower case string is: "+str_lower);

Output

D:\>javac caseDemo.java

D:\>java caseDemo

The original string is: Nisha is Indian

The Upper case string is: NISHA IS INDIAN

The Lower case string is: nisha is Indian

Java String length()

The Java String class length() method finds the length of a string.

public class LengthExample{


public static void main(String args[]){
String s1="javatpoint";
String s2="python";
System.out.println("string length is: "+s1.length());//10 is the length of javatpoint string
System.out.println("string length is: "+s2.length());//6 is the length of python string
}}

StringBuffer Class

 The StringBuffer is a class which is alternative to the String class.


 But StringBuffer class is more flexible to use than the String class.
 That means, using StringBuffer we can insert some components to the existing string
or modify the existing string but in case of String class once the string is defined then
it remains fixed.
 The StringBuffer and the StringBuilder are almost one and the same. The
StringBuilder or StringBuffer have three constructors and 30 methods.
 Following are some simple methods used for StringBuffer –

Capacity and length function of StringBuffer.

Java Program [StringBuffDemo1.java]

public class StringBuffDemo1{

public static void main(String args[])

StringBuffer str=new StringBuffer("Java");

System.out.println("The String Buffer is "+str);

System.out.println("The length is "+str.length());

System.out.println("The capacity is"+ str.capacity());-

}
}

Output

F:\test>javac StringBuffDemo1.java

F:\test>java StringBuffDemo1

The String Buffer is Java

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:

public class StringBuffDemo4{

public static void main(String args[])

StringBuffer str=new StringBuffer(" in need is a in deed");

StringBuffer new_str=new StringBuffer(" FRIEND");

System.out.println("Initially the String is: "+str);

str.insert(13,new_str);

str.insert(0,new_str);

System.out.println("Now the String is: "+str);

Output

F:\test>javac StringBuffDemo4.java

F:\test>java StringBuffDemo4

Initially the String is: in need is a in deed

Now the String is: FRIEND in need is a FRIEND in deed

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. * ;

public class DeleteMethodDemo {

public static void main(String[] args) {

StringBuffer myString = new StringBuffer("TechVidvanJava");

System.out.println("Original String: " + myString);

myString.delete(0, 4);

System.out.println("Resulting String after deleting sequence of characters: " + myString);

Output:

Original String: TechVidvanJava

Resulting String after deleting a sequence of characters: VidvanJava

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:

stringName.replace(int startIndex, int endIndex, String string)

public class Demo {


public static void main(String[] args) {
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);
}
}
Output: Hello java
setChatAt() and setLength()
setChatAt(int index, char ch)- The character specified by the index from the StringBuffer is
set to ch
setLength(int new_len)- It sets the length of the string buffer.

public class StringBuffDemo2{

public static void main(String args[])

StringBuffer str=new StringBuffer("Great");

System.out.println("The String is: "+str);

str.setCharAt(1,'o');'
str.setCharAt(2,'d');

str.setLength(3);

System.out.println("Now the String is: "+str);

Output

F:\test>javac StringBuffDemo2.java

F:\test>java StringBuffDemo2

The String is: Great

Now the String is: God

Differences between String and StringBuffer

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 is slower while performing  StringBuffer class is faster while


concatenation operation. performing concatenation operation.

 String class uses String constant pool.  StringBuffer uses Heap memory

Reading and Writing Files in Java


What is File Handling in Java?
 File handling in Java implies reading from and writing data to a file.
 The File class from the java.io package, allows us to work with different formats of
files.
 In order to use the File class, you need to create an object of the class and specify the
filename or directory name.
Java File Class Methods
Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath( String Returns the absolute pathname of the file
)
length() Long Returns the size of the file in bytes
File Operations

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

 Create a File operation is performed to create a new file.

 We use the createNewFile() method of 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());

// Getting path of the file


System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());
// Checking whether the file is writable or not
System.out.println("Is file writeable?: " + f0.canWrite());

// Checking whether the file is readable or not


System.out.println("Is file readable " + f0.canRead());

// Getting the length of the file in bytes


System.out.println("The size of the file in bytes is: " + f0.length());
} else {
System.out.println("The file does not exist.");
}
}
}
Output:

1. We get the name of the file using the getName()


2. We get the absolute path of the file using the getAbsolutePath() method of the file.
3. We check whether we can write data into a file or not using the canWrite()
4. We check whether we can read the data of the file or not using the canRead()
5. We get the length of the file by using the length()

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.

 Here, we need to close the stream using the close() method.

 We will create an instance of the Scanner class and use


the hasNextLine() method nextLine() method to get data from the file.

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.

Java Program[DataStream Prog.java]

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.

Java Program [Buffered Stream Prog.java]

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.

Program for non-generic programming


class intsample class doublesample class strsample
{ { {
int a,b; double a,b; String a,b;
void input(int c, int d) void input(double c, double void input(String c, String
{ d) d)
{ {
a=c;
b=d; a=c; a=c;
System.out.println(a+“\ b=d; b=d;
n”+b+“\n”); System.out.println(a+“\ System.out.println(a+“\
} n”+b+“\n”); n”+b+“\n”);
} } }
} }
class genpro
{
public static void main(String args[])
{
intsample is=new intsample();
doublesample ds=new doublesample();
strsample ss=new strsample();
is.input(10,20);
ds.input(100.5,200.2);
ss.input(“Hello”, “World”);
}
}

Output
> javac genpro.java
> java genpro
10
20

100.5
200.2

Hello
World

Program for generic programming


class sample <T>
{
T a,b;
void input(T c, T d)
{
a=c;
b=d;
System.out.println(a+“\n”+b+“\n);
}
}
class genpro2
{
public static void main(String args[])
{
sample <Integer> is=new sample<Integer>();
sample <Double> ds=new sample< Double>();
sample <String> ss=new sample<String>();
is.input(10,20);
ds.input(100.5,200.2);
ss.input(“Hello”, “World”);
}
}

Output

> javac genpro2.java


> java genpro2
10
20

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

Program for Generic classes in Single Data Type


class Test <T>
{
T obj;
Test ( T obj) // constructor
{
this.obj=obj;
}
public T getObject()
{
return this.obj;
}
}

class gsample
{
public static void main(String args[])
{
// instance of Integer Type
Test < Integer> iObj= new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String Type


Test < String> sObj= new Test<String>(“Hello World”);
System.out.println(sObj.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

Generic Methods/ Functions


 We can also write generic functions that can be called with different types of
arguments based on the types of arguments passed to generic method, the compiler
handles each method.

Example for Generic Methods / Functions


class gmethod
{
public static void main(String[] args)
{
// Calling generic method with Integer argument
genericDisplay(11);
//Calling generic method with String argument
genericDisplay(“Helloworld”);
//Calling generic method with double argument
genericDisplay(1.0);
// A Generic method example
public static <T> void genericDisplay ( T element)
{
System.out.println(element.getClass().getName() + “ = ” + element);
}
}

OUTPUT
>javac gmethod.java
>java gmethod
java.lang.Integer=11
java.lang.String=Helloworld
java.lang.Double=1.0

Bounded Type Generic Programming


 While creating objects to generic classes we can pass any derived type as type
parameters.
 Many times it will be useful to limit the types that can be passed to type parameters.
For that purpose, bounded types are introduced in generics.
 Using bounded types, we can make the objects of generic class to have data of
specific derived types.
 Syntax for declaring bounded type parameter
o <T extends SuperClass>
 This specifies that 'T' can only be replaced by 'SuperClass' or it's sub classes.
Example Program
class Test<T extends Number> //Declaring Number class as upper bound of T
{
T t;
public Test(T t)
{
this.t = t;
}
public T getT()
{
return t;
}
}
public class BoundedTypeDemo
{
public static void main(String[] args)
{
//Creating object by passing Number as a type parameter
Test<Number> obj1 = new Test<Number>(123);
System.out.println("The integer is: "+obj1.getT());
//While Creating object by passing String as a type parameter, it gives compile time //error
Test<String> obj2: = new Test<String>("I am string"); //Compile time error
System.out.println("The string is: "+obj2.getT());
}
}

Restrictions and Limitations

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.

Java Byte Stream Classes

Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.

Some important Byte stream classes.

Stream class Description


BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
An output stream that contain method for writing java standard
DataOutputStream
data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method
These classes define several key methods. Two most important are

1. read() : reads byte of data.

2. write() : Writes byte of data.

Java Character Stream Classes

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

Stream class Description


BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output

Reading Console Input

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.

int read() throws IOException

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();
}
}
}

Program to write to a File using FileWriter class

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(); }
}
}

You might also like