UNIT 4
UNIT 4
InputStream
➢ Java application uses an input stream to read data from a source, it may be a file, an
array, peripheral device or socket.
OutputStream class
➢ OutputStream class is an abstract class. It is the super class of all classes
representing an output stream of bytes. An output stream accepts output bytes and
sends them to some sink.
Method Description
OutputStream Hierarchy
InputStream class
➢ InputStream class is an abstract class. It is the super class of all classes representing
an input stream of bytes.
Useful Methods of InputStream
Method Description
1) public abstract int reads the next byte of data from the input stream.
read()throws IOException It returns -1 at the end of file.
InputStream Hierarchy
Method Description
void write(byte[] ary, int off, int len) It is used to write len bytes from the byte
array starting at offset off to the file output
stream.
fout.write(b1);
fout.close();
System.out.println("success...");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data AB.
testout.txt
AB
Method Description
int available() It is used to return the estimated number of bytes that can
be read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input
stream.
int read(byte[] b, int It is used to read up to len bytes of data from the input
off, int len) stream.
long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.
protected void It is used to ensure that the close method is call when there
finalize() is no more reference to the file input stream.
{
System.out.println(e);
}
}
}
Output:
Contents in testout.txt will be displayed
4.1.4 BYTE STREAMS AND CHARACTER STREAMS
BYTE STREAMS
Java ByteArrayOutputStream Class
➢ Java ByteArrayOutputStream class is used to write common data into multiple files.
In this stream, the data is written into a byte array which can be written to multiple
streams later.
➢ The ByteArrayOutputStream holds a copy of data and forwards it to multiple
streams. The buffer of ByteArrayOutputStream automatically grows according to
data.
Java ByteArrayOutputStream Class Declaration
Let's see the declaration for Java.io.ByteArrayOutputStream class:
public class ByteArrayOutputStream extends OutputStream
Java ByteArrayOutputStream Class Constructors
Constructor Description
ByteArrayOutputStream() Creates a new byte array output stream with the initial
capacity of 32 bytes, though its size increases if
necessary.
Method Description
String toString() It is used for converting the content into a string decoding
bytes using a platform default character set.
String toString(String It is used for converting the content into a string decoding
charsetName) bytes using a specified charsetName.
void write(int b) It is used for writing the byte specified to the byte array
output stream.
void write(byte[] b, int off, It is used for writing len bytes from specified byte array
int len starting from the offset off to the byte array output stream.
void writeTo(OutputStream It is used for writing the complete content of a byte array
out) output stream to the specified output stream.
void reset() It is used to reset the count field of a byte array output
stream to zero value.
bout.writeTo(fout2);
bout.flush();
bout.close();//has no effect
System.out.println("Success...");
}
}
Output:
Success...
f1.txt:
A
f2.txt:
A
Method Description
import java.io.*;
class Consoleexp
Console C=System.console();
System.out.println("Enter UserName:");
str=C.readLine();
System.out.println("Enter Password:");
ch=C.readPassword();
String S=String.valueOf(ch);
System.out.println("UserName:" +str);
System.out.println("Password:" +S);
Output
Output
Constructor
Methods
➢ read() - reads a single character from the reader
➢ read(char[] array) - reads the characters from the reader and stores in the specified array
➢ read(char[] array, int start, int length) - reads the number of characters equal to length
from the reader and stores in the specified array starting from the position start
Example
import java.io.*;
class Reader
{
public static void main(String[] args)
{
File infile=new File("a2.txt");
FileReader fr=null;
try
{
fr=new FileReader(infile);
int ch;
while ((ch=fr.read())!= -1)
{
System.out.print((char)ch);
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
Constructor Description
FileWriter(File file) Creates a new file. It gets file name in File object.
Method Description
fout=new FileWriter(outfile);
String s="WELCOME TO JAVA";
fout.write(s);
fout.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Success...");
}
}
Output:
Success...
A2.txt:
WELCOME TO JAVA
4.4 Generic programming
➢ Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of
related types, respectively.
➢ Generics also provide compile-time type safety that allows programmers to catch
invalid types at compile time.
➢ Using Java Generic concept, we might write a generic method for sorting an array of
objects, then invoke the generic method with Integer arrays, Double arrays, String
arrays and so on, to sort the array elements.
➢ We can write a single generic method declaration that can be called with arguments of
different types. Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately. Following are the rules to define
Generic Methods −
➢ Following example illustrates how we can print an array of different type using a single
Generic method −
public class GenericMethod
{
public static < E > void printArray(E[] elements)
{
for ( E element : elements)
{
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] )
{
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'W','E','L','C','O','M','E' };
Double[] doubleArray={5.10,8.10,76.89,45.67,2.87};
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
System.out.println( "Printing Double Array" );
printArray( doubleArray );
}
}
Output
➢ Whenever you want to restrict the type parameter to subtypes of a particular class you
can use the bounded type parameter.
➢ If you just specify a type (class) as bounded parameter, only sub types of that particular
class are accepted by the current generic class. These are known as bounded-types in
generics in Java.
➢ For example, a method that operates on numbers might only want to accept instances
of Number or its subclasses. This is what bounded type parameters are for.
4.4.2.1 Defining bounded-types for class
➢ You can declare a bound parameter just by extending the required class with the type-
parameter, within the angular braces as
➢ Syntax
class Sample <T extends Number>
Example
➢ In the following Java example, the generic class Sample restricts the type parameter to
the sub classes of the Number classes using the bounded parameter.
class Sample <T extends Number>
{
T data;
Sample(T data)
{
this.data = data;
}
public void display()
{
System.out.println("Data value is: "+this.data);
}
}
public class BoundsExample
{
public static void main(String args[])
{
Sample<Integer> obj1 = new Sample<Integer>(20);
obj1.display();
Sample<Double> obj2 = new Sample<Double>(20.22d);
obj2.display();
Sample<Float> obj3 = new Sample<Float>(125.332f);
obj3.display();
}
}
Output
}
public T get()
{
return t;
}
public void getArea()
{
}
public static void main(String[] args)
{
// Object of generic class Area with parameter Type
// as Integer
Area<Integer> rectangle = new Area<Integer>();
// Object of generic class Area with parameter Type
// as Double
Area<Double> circle = new Area<Double>();
rectangle.add(10);
circle.add(2.5);
System.out.println(rectangle.get());
System.out.println(circle.get());
}
}
Output
4.9.3 Cannot Declare Static Fields Whose Types are Type Parameters
A class's static field is a class-level variable shared by all non-static objects of the class. Hence,
static fields of type parameters are not allowed. Consider the following class:
public class MobileDevice<T> {
private static T os;
// ...
}
If static fields of type parameters were allowed, then the following code would be confused:
MobileDevice<Smartphone> phone = new MobileDevice<>();
MobileDevice<Pager> pager = new MobileDevice<>();
MobileDevice<TabletPC> pc = new MobileDevice<>();
Because the static field os is shared by phone, pager, and pc, what is the actual type of os? It
cannot be Smartphone, Pager, and TabletPC at the same time. You cannot, therefore, create
static fields of type parameters.
4.9.7 Cannot Overload a Method Where the Formal Parameter Types of Each Overload
Erase to the Same Raw Type
A class cannot have two overloaded methods that will have the same signature after type
erasure.
public class Example {
public void print(Set<String> strSet) { }
public void print(Set<Integer> intSet) { }
}
The overloads would all share the same classfile representation and will generate a compile-
time error.
4.6 Strings
In java, string is basically an object that represents sequence of char values. An array of
characters works same as java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
Thejava.lang.String class implements Serializable, Comparable and CharSequence interfaces.
CharSequence Interface
The CharSequence interface is used to represent sequence of characters. It is
implemented by String, StringBuffer and StringBuilder classes. It means, we can create string
in java by using these 3 classes.
The java String is immutable i.e. it cannot be changed. Whenever we change any string,
a new instance is created. For mutable string, you can use StringBuffer and StringBuilder
classes.
There are two ways to create String object:
1. By string literal
2. By new keyword
String s1="Welcome";
String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any
string object with the value "Welcome" in string constant pool, so it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create new
object but will return the reference to the same instance.
4.6.2 By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal(non-pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non-pool).
Example
public class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
Output
Method Description
char charAt(int index) returns char value for the particular index
static String format(Locale l, String returns formatted string with given locale
format, Object... args)
String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index
String replace(char old, char new) replaces all occurrences of specified char value
String[] split(String regex, int limit) returns splitted string matching regex and limit
int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index
int indexOf(String substring, int returns specified substring index starting with
fromIndex) given index
static String valueOf(int value) converts given type into string. It is overloaded.
➢ Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.
IMPORTANT CONSTRUCTORS OF STRINGBUFFER CLASS
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
public insert(int offset, String It is used to insert the specified string with this
synchronized s) string at the specified position. The insert()
StringBuffer method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public char charAt(int index) It is used to return the character at the specified
position.
public int length() It is used to return the length of the string i.e.
total number of characters.
➢ A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.
➢ The append() method concatenates the given argument with this String.
Example Program
class StringBufferExample
OUTPUT
Hello Java
➢ The insert() method inserts the given String with this string at the given position.
Example Program
class StringBufferExample2{
System.out.println(sb);//prints HJavaello
OUTPUT
HJavaello
➢ The replace() method replaces the given String from the specified beginIndex and
endIndex.
Example Program
class StringBufferExample3{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}
OUTPUT
HJavalo
➢ The default capacity of the buffer is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
Example Program
class StringBufferExample6{
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
Output:
16
16
34
➢ The ensureCapacity() method of the StringBuffer class ensures that the given capacity
is the minimum to the current capacity. If it is greater than the current capacity, it
increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16,
it will be (16*2)+2=34.
Example Program
class StringBufferExample7
System.out.println(sb.capacity()); //default 16
sb.append("Hello");
System.out.println(sb.capacity()); //now 16
System.out.println(sb.capacity()); //now 34
System.out.println(sb.capacity()); //now 70
Output