0% found this document useful (0 votes)
11 views89 pages

Java I/O, Generics, and String Handling

The document covers Java I/O basics, including reading and writing console input and files, as well as the use of generics and string handling. It explains various stream types, such as byte and character streams, and provides examples of file operations using classes like FileWriter, FileReader, BufferedReader, and BufferedWriter. Additionally, it discusses generic programming, highlighting its advantages over non-generics in terms of type safety and flexibility.

Uploaded by

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

Java I/O, Generics, and String Handling

The document covers Java I/O basics, including reading and writing console input and files, as well as the use of generics and string handling. It explains various stream types, such as byte and character streams, and provides examples of file operations using classes like FileWriter, FileReader, BufferedReader, and BufferedWriter. Additionally, it discusses generic programming, highlighting its advantages over non-generics in terms of type safety and flexibility.

Uploaded by

ponmanie5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

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.
Java Input
 Java I/O (Input and Output) is used to process the
input and produce the output.
The [Link] package contains all the classes
required for input and output operations.

Java Input
 There are several ways to get input from the user in
Java. To get input by using Scanner object, import
Scanner class using:
 import [Link];
 Then, we will create an object of Scanner class which
will be used to get input from the user.
 Scanner input = new Scanner ([Link]); int
number = [Link]();

Example
Get Integer Input From the User
import [Link]; class Input
{
public static void main(String[] args)
{
Scanner input =newScanner ([Link]);
[Link] ("Enter an integer: ");
int number =[Link] ();
[Link] ("You entered”+ number);
} }
Output
Enter an integer: 23 You entered 23
Java Output
Simply use [Link](), [Link]() or
[Link]() to send output to standard output
(screen).system is a class and out is a public static field
which accepts output data.
 print () - prints string inside the quotes.
 println () - prints string inside the quotes similar like print()
method. Then the cursor moves to the beginning of the next line.

Example to output a line:


class Test
{
public static void main(String[] args)
{
[Link]("Java programming is interesting.");
}
}
Output:
Java programming is interesting.
Stream
A Stream is a sequence of data or it is an
abstraction that either produces or consumes
information. In other simple words it is a flow
of data from which you can read or write data
to it. It’s called a stream because it's like a
stream of water that continues to flow.
 PREDEFINED STREAMS:
 In java, 3 streams are created for us automatically. All these
streams are attached with console.

 [Link]: This is used to feed the data to user's program and
usually a keyboard is used as standard input stream and
represented as [Link]. – It is an object of type InputStream.

 [Link]: This is used to output the data produced by the
user's program and usually a computer screen is used to standard
output stream and represented as [Link]. - It is an object of
type PrintStream

 [Link]: This is used to output the error data produced by the
user's program and usually a computer screen is used to standard
error stream and represented as [Link]. - It is an object of
type PrintStream
TYPES OF STREAMS

Byte Stream – Byte Streams provide a


convenient means of handling input and
output in terms of bytes. Byte streams are
used when reading or writing binary data.
Character Stream – Character streams
provide a convenient means of handling input
or output in terms of characters. In some
cases, character streams are more efficient
than byte streams.
Some important Byte stream classes

BufferedInputStream
Used for Buffered Input Stream.
BufferedOutputStream
Used for Buffered Output Stream.
DataInputStream
Contains method for reading java standard datatype
DataOutputStream
An output stream that contain method for writing java
standard 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
Some important Character stream classes
Stream class
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
Example of Java FileOutputStream class
import [Link].*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("[Link]");
String s="java is my favourite language";
byte b[]=[Link](); //converting string into byte array
[Link](b);
[Link]();
[Link]("success...");
}
catch(Exception e)
{[Link](e);}
}
}
Output:success...
Example of FileInputStream class
import [Link].*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("[Link]");
int i=0;
while((i=[Link]())!=-1){
[Link]((char)i); 9. }
[Link]();
}
catch(Exception e)
{[Link](e);}
}
}
Output: java is my favourite language
Example of Buffered Output Stream class
import [Link].*;
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("[Link]");
BufferedOutputStream bout=new
BufferedOutputStream(fout);
String s="Java is my favourite language";
byte b[]=[Link]();
[Link](b);
[Link]();
[Link]();
[Link]();
[Link]("success");
13. }
14.}
Output: success...
Example of Java BufferedInputStream
import [Link].*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("[Link]");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=[Link]())!=-1){
[Link]((char)i);
10. }
[Link]();
[Link]();
}catch(Exception e){[Link](e);}
}
}
Output: Java is my favourite language
DataInputStream and DataOutputStream
 [Link]
 this is test 1 , this is test 2 , this is test 3 , this is test 4 , this is test 5 ,

 [Link]
 import [Link].*; public class Test{
 public static void main(String args[])throws IOException{
 DataInputStream d = new DataInputStream(new
FileInputStream("[Link]")); DataOutputStream out = new
DataOutputStream(new FileOutputStream("[Link]")); String count;
 while((count = [Link]()) != null){ String u = [Link]();
[Link](u);
 [Link](u + " ,");}
 [Link]();
 [Link]();
 }}

 Output:
 THIS IS TEST 1 , THIS IS TEST 2 , THIS IS TEST 3 , THIS IS TEST 4 ,
THIS IS TEST 5 ,

PrintStream
 Example of [Link] class:

 In this example, we are simply printing integer and string values.
 import [Link].*;
 class PrintStreamTest{
 public static void main(String args[])throws Exception{
 FileOutputStream fout=new FileOutputStream("[Link]");
 PrintStream pout=new PrintStream(fout);
 [Link](1900);
 [Link]("Hello Java");
 [Link]("Welcome to Java");
 [Link]();
 [Link]();
}
}
CHARACTER STREAMS (READER & WRITER)
Java IO's Reader and Writer work much like
the InputStream and OutputStream with the
exception that Reader and Writer are
character based. They are intended for
reading and writing text. The InputStream
and OutputStream are byte based.

Java FileWriter and FileReader (File


Handling in java)
Java FileWriter and FileReader classes are
used to write and read data from text files.
These are character-oriented classes, used
for file handling in java.
BufferedReader and BufferedWriter classes

BufferedWriter class
This can be used for writing character data to the file.

BufferedReader
BufferedReader class can read character data from the file.
BufferedReader br = new BufferedReader(Reader r)
BufferedReader br = new BufferedReader(Reader r, int
buffersize)
BufferedReader never communicates directly with
the file. It should Communicate through
some reader object only.

Important methods of BufferedReader Class


int read()
int read(char [] ch)
String readLine(); - Reads the next line present in the file. If
there is no nextline this method returns null.
void close()
Example for Java FileWriter and FileReader , BufferedReader and
BufferedWriter classes
 import [Link].*; class Simple{
 public static void main(String args[]){ try{
 FileWriter fw=new FileWriter("d:/archana/[Link]");
BufferedWriter bw = new BufferedWriter(fw); [Link]("
Java");
 [Link]();
 [Link]();
 FileReader fr=new FileReader("d:/archana/[Link]");
BufferedReader br = new BufferedReader(fr);
 int i; while((i=[Link]())!=-1) [Link]((char)i);
[Link]();
 [Link]();
 }catch(Exception e){[Link](e);}
[Link]("success");
} }
 Output Java success

READING AND WRITING CONSOLE
3 Ways to read input from console in Java
Using Buffered Reader Class
Advantages
The input is buffered for efficient reading.
Drawback:
The wrapping code is hard to remember.
Using Scanner Class
Advantages:
Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized
input.
Regular expressions can be used to find tokens. Drawback:
The reading methods are not synchronized

Using Console Class


Advantages:
Reading password without echoing the entered characters.
Reading methods are synchronized.
Format string syntax can be used. Drawback:
Does not work in non-interactive environment (such as in an IDE).
Java Console Class

The Java Console class is be used to get input from


console. It provides methods to read texts and
passwords.
If you read password using Console class, it will not
be displayed to the user. The [Link] class
is attached with system console internally.

Let's see a simple example to read text from console.

String text=[Link]().readLine();
[Link]("Text is: "+text);
Java Console Example to Read password
import [Link];
class ReadPasswordTest{
public static void main(String args[]){
Console c=[Link]();
[Link]("Enter password: ");
char[] ch=[Link]();
String pass=[Link](ch);//converting char array
into string
[Link]("Password is: "+pass);
}
}

Output

Enter password: Password is: 123


READING AND WRITING FILES
What is File Handling in Java?
File handling in Java implies reading from and
writing data to a file.
The File class from the [Link] 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.
For example:
//import the File class
import [Link]
//specify the filename
File obj = new File("[Link]");
File Operations in Java
Basically, you can perform four operations
on a file. They are as follows:
Create a File
Get File Information
Write To a File
Read from a File
Create a File
To create a file in Java, you can use the createNewFile()
method. This method returns a boolean value: true if the
file was successfully created, and false if the file already
exists.

import [Link];
import [Link];
public class CreateFile {
public static void main(String[] args) { try {
File myObj = new File("[Link]"); if
([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}} catch (IOException e) { [Link]("An error
occurred."); [Link]();
}}}
The output will be:
File created: [Link]
Write To a File
In the following example, we use the FileWriter class together with its write()
method to write some text to the file we created in the example above. Note that
when we are done writing to the file, we should close it with the close() method.
Example:
import [Link]; // Import the FileWriter class
import [Link]; // Import the IOException class to handle errors public class
WriteToFile {
public static void main(String[] args)
{
try
{
FileWriter myWriter = new FileWriter("[Link]");
[Link]("Files in Java might be tricky, but it is fun enough!");
[Link]();
[Link]("Successfully wrote to the file.");
}
catch (IOException e)
{ [Link]("An error occurred.");
[Link]();
}
}
}
Output:
Successfully wrote to the file.
Read a File
 In the following example, we use the Scanner class to read the contents of the text file we created
in the previous example:
 Example:
 import [Link]; // Import the File class
 import [Link]; // Import this class to handle errors
 import [Link]; // Import the Scanner class to read text files
 public class ReadFile {
 public static void main(String[] args)
 {
 try
 {
 File myObj = new File("[Link]");
 Scanner myReader = new Scanner(myObj);
 while ([Link]()) {
 String data = [Link]();
 [Link](data);
 }
 [Link]();
 }
 catch (FileNotFoundException e)
 {
 [Link]("An error occurred.");
 [Link]();
 }}}
 Output:
 Files in Java might be tricky, but it is fun enough!
Get File Information
To get more information about a file, use any of the File methods
Example:
import [Link]; // Import the File class public class GetFileInfo {
public static void main(String[] args) { File myObj = new File("[Link]");
if ([Link]())
{
[Link]("File name: " + [Link]());
[Link]("Absolute path: " + [Link]());
[Link]("Writeable: " + [Link]());
[Link]("Readable " + [Link]());
[Link]("File size in bytes " + [Link]());
}
else
{
[Link]("The file does not exist.");
}}}
Output:
File name: [Link]
Absolute path: C:\Users\MyName\[Link] Writeable: true
Readable: true
File size in bytes: 0
Generic Programming
Generic programming is a style of computer
programming in which algorithms are written in
terms of “to-be-specified-later” types that are then
instantiated when needed for specific types provided
as parameters.
Generic programming refers to writing code that will
work for many types of data.
NON-GENERICS:
In java, there is an ability to create generalized
classes, interfaces and methods by operating through
Object class.

Example
class NonGen
{
Object ob; NonGen(Object o)
{}
Object getob()
{
ob=o;

return ob;
}
void showType()
{
[Link]("Type of ob is "+[Link]().getName());
}}
public class NonGenDemo
{
public static void main(String[] arg)
{
NonGen integerObj; integerObj=new NonGen(88);
[Link]();
int v=(Integer)[Link](); // casting required [Link]("Value = "+v);
NonGen strObj=new NonGen("Non-Generics Test");
[Link]();
String str=(String)[Link](); // casting required [Link]("Vlaue = "+str);
}}
Output:
Type of ob is [Link] Value = 88
Type of ob is [Link] Vlaue = Non-Generics Test
Limitation of Non-Generic:
Explicit casts must be employed to retrieve the stored data.
Type mismatch errors cannot be found until run time.

Need for Generic:


It saves the programmers burden of creating separate methods for handling data belonging to different data
types.
It allows the code reusability.
Compact code can be created.

Advantage of Java Generics (Motivation for Java Generics):


Code Reuse: We can write a method/class/interface once and use for any type we want.
Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
Elimination of casts: There is no need to typecast the object. The following code snippet without generics
requires casting:
List list = new ArrayList(); [Link]("hello");
String s = (String) [Link](0);//typecasting
When re-written to use generics, the code does not require casting: List<String> list = new
ArrayList<String>(); [Link]("hello");
String s = [Link](0);
Stronger type checks at compile time:
A Java compiler applies strong type checking to generic code and issues errors if the code violates type
safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
List<String> list = new ArrayList<String>(); [Link]("hello");
[Link](32); //Compile Time Error
Enabling programmers to implement generic algorithms.
By using generics, programmers can implement generic algorithms that work on collections of different
types, can be customized, and are type safe and easier to read.
GENERIC CLASSES
A class that can refer to any type is known as generic class. Here, we are using
T type parameter to create the generic class of specific type.

Class reference declaration:


To instantiate this class, use the new keyword, as usual, but place <type_parameter>
between the class name and the parenthesis:

class_name<type-arg-list> var-name= new class_name<type-arg-list>(cons-


arg- list);
 Type Parameter Naming Conventions:

 Type parameter is a place holder for a type argument.
 By convention, type parameter names are single, uppercase letters.

 The most commonly used type parameter names are:

 E - Element (used extensively by the Java Collections Framework)
 K - Key
 N - Number
 T - Type
 V - Value
 S,U,V etc. - 2nd, 3rd, 4th types
Example: Generic class with single type parameter

class Gen <T>


{
T obj; Gen(T x)
{
obj= x;
}
T show()
{
return obj;
}
void disp()
{
[Link]([Link]().getName());
}}
public class Test
{
public static void main (String[] args)
{
Gen < String> ob = new Gen<>("java programming with Generics");

[Link]();
[Link]("value : " +[Link]());

Gen < Integer> ob1 = new Gen<>(550); [Link]();


[Link]("value :" +[Link]());
}}
Output:
[Link]
value : java programming with Generics [Link]
value :550
Generic class with more than one type parameter

In Generic parameterized types, we can pass more than 1 data type as parameter. It works the same as with one parameter Generic type.
class Gen <T1,T2>
{
T1 obj1; T2 obj2;
Gen(T1 o1,T2 o2)
{
obj1 = o1; obj2 = o2;
}
T1 get1()
{
return obj1;
}
T2 get2()
{
return obj2;
}
void disp()
{
[Link]([Link]().getName());
[Link]([Link]().getName());
}
}

public class Test


{
public static void main (String[] args)
{
Gen < String, Integer> obj = new Gen<>("java programming with Generics",560); [Link]();
[Link]("value 1 : " +obj.get1()); [Link]("value 2: "+obj.get2());

Gen < Integer, Integer> obje = new Gen<>(1000,560); [Link]();


[Link]("value 1 : " +obje.get1()); [Link]("value 2: "+obje.get2());
}
}

Output:
[Link] [Link]
value 1 : java programming with Generics value 2: 560
[Link] [Link] value 1 : 1000
value 2: 560
GENERIC METHODS
A Generic Method is a method with type
parameter. 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.
GENERICS WITH BOUNDED TYPES
GENERICS WITH BOUNDED TYPE
PARAMETERS
 Bounded Type Parameter is a type
parameter with one or more bounds. The
bounds restrict the set of types that can be
used as type arguments and give access to
the methods defined by the bounds.
For example, a method that operates on
numbers might only want to accept instances
of Number or its subclasses.
 Syntax:
 <T extends superclass>

 Example:

 The following example creates a generic class that contains a method that returns the average of array of any type of numbers. The type of the numbers is represented
generically using Type Parameter.

 public class GenBounds<T extends Number>
 {
 T[] nums;
 GenBounds(T[] obj)
 {
 nums=obj;
 }
 double average()
 {
 double sum=0.0;
 for(int i=0;i<[Link];i++)


 CS3391 – Object Oriented Programming – III Sem CSE Unit 4
 .


 sum+=nums[i].doubleValue(); double avg=sum/[Link]; return avg;
 }
 public static void main(String[] args)
 {
 Integer inum[]={1,2,3,4,5};
 GenBounds<Integer> iobj=new GenBounds<Integer>(inum); [Link]("Average of Integer Numbers : "+[Link]());

 Double dnum[]={1.1,2.2,3.3,4.4,5.5};
 GenBounds<Double> dobj=new GenBounds<Double>(dnum); [Link]("Average of Double Numbers : "+[Link]());

 /* Error: java,[Link] not within bound String snum[]={"1","2","3","4","5"};
 GenBounds<String> sobj=new GenBounds<String>(snum); [Link]("Average of Integer Numbers : "+[Link]()); */
 }
 }


Output:

 F:\>java GenBounds
 Average of Integer Numbers : 3.0 Average of Double Numbers : 3.3

Wild Card Arguments

Question mark (?) is the wildcard in


generics and represents an unknown
type. The wildcard can be used as the
type of a parameter, field, or local
variable and sometimes as a return type.
UNBOUNDED WILDCARD

Sometimes we have a situation where we


want our generic method to be working with
all types; in this case unbounded wildcard can
be used. The wildcard “?” simply matches any
valid objects.
Its same as using <? extends Object>. import [Link].*;
public class GenUBWildcard
{
public static void main(String[] args)
{
List<Integer> ints = new ArrayList<Integer>(); [Link](3);
[Link](5);
[Link](10); printData(ints);

List<String> str = new ArrayList<String>(); [Link]("\nWelcome");


[Link](" to ");
[Link](" JAVA "); printData(str);
}
public static void printData(List<?> list)
{
for(Object obj : list)
{
[Link](obj + "\n");
}}}
Output:
F:\>java GenUBWildcard 3
5
10
Welcome to
JAVA
RESTRICTIONS AND LIMITATIONS OF GENERICS
In Java, generic types are compile time entities. The runtime
execution is possible only if it is used along with raw type.
Primitive type parameters are not allowed for generic programming.
For example:
Stack<int> is not allowed.
For the instances of generic class throw and catch keywords are not
allowed. For example:
public class Test<T> extends Exception
{
// code // Error: can’t extend the Exception class
}
Instantiation of generic parameter T is not allowed. For Example:
new T(); // Error new T[10]; // Error
Arrays of parameterized types are not allowed.
For Example:
New Stack<String>[10]; // Error
STRINGS
 String is a sequence of characters. But in Java, a string is an
object that represents a sequence of characters. The
[Link] class is used to create string object.

How to create String object?


 There are two ways to create a String object:

 By string literal: Java String literal is


created by using
double quotes. For Example: String s=“Welcome”;

 By new keyword: Java String is created by using a keyword


“new”. For example: String s=new String(“Welcome”);

It creates two objects (in String pool and in heap) and one
reference variable where the variable ‘s’ will refer to the
object in the heap.
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";
[Link](" Tendulkar");//concat() method appends the string at the
end
[Link](s);//will print Sachin because strings are
immutable objects
}
}
Output: Sachin
METHODS
 [Link] class provides a lot of methods to work on string.
By the help of these methods, we can perform operations on string
such as trimming, concatenating, converting strings etc.
 Important methods of String class.
 public String concat(String str)-Concatenates the specified string to
the end of this string.
 public int compareTo(String str)-Compares two strings and returns
int
 public int compareToIgnoreCase(String str)-Compares two strings,
ignoring case differences.
 public String substring(int beginIndex,int endIndex)-Returns a new
string that is a
 substring of this string.
 public String toUpperCase()-Converts all of the characters in this
String to upper case
 public String toLowerCase()-Converts all of the characters in this
String to lower case.
 public String trim()-Returns a copy of the string, with leading and
trailing whitespace Omitted.
String comparison in Java

 We can compare two given strings on the basis of
content and reference.
 It is used in authentication (by equals() method),
sorting (by compareTo() method), reference
matching (by == operator) etc.
 There are three ways to compare String objects:

By equals() method
By = = operator
By compareTo() method
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";

[Link]([Link](s2));//true

[Link]([Link](s3));//true

[Link]([Link](s4));//false

} }
Output:
true true false
Example: equalsIgnoreCase(String) method
class Simple{
public static void main(String args[]){
String s1="Sachin"; String s2="SACHIN";
[Link]([Link](s2));//false
[Link]([Link](s3));//
true
}
}
Output:
False
True
By == operator
The = = operator compares references not values.
Example: == operator:
class Simple{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
[Link](s1==s2);//true (because both refer to
same instance)
[Link](s1==s3);//false(because s3 refers to
instance created in nonpool)
}}
Output:
true
false
Example: compareTo() method:
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because
s1>s3)
[Link]([Link](s1));//-1(because s3 <
s1 )
}
}
Output:
0
1
-1
String Concatenation in Java
There are two ways to concat string objects:
By + (string concatenation) operator
By concat() method

By + (string concatenation) operator

class Simple{
public static void main(String args[]){

String s="Sachin"+" Tendulkar";


[Link](s);//Sachin Tendulkar
}
}
Output: Sachin Tendulkar

You might also like