Unit 4 - Oops - Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

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

File operations in Java


In Java, a File is an abstract data type. A named location used to store related information is
known as a File. There are several File Operations like creating a new File, getting
information about File, writing into a File, reading from a File and deleting a File.

Java File Class Methods

S.No. Method Return Type Description

1. canRead() Boolean The canRead() method is used to check


whether we can read the data of the file or
not.

2. createNewFile() Boolean The createNewFile() method is used to


create a new empty file.

3. canWrite() Boolean The canWrite() method is used to check


whether we can write the data into the file
or not.

4. exists() Boolean The exists() method is used to check


whether the specified file is present or not.

5. delete() Boolean The delete() method is used to delete a file.

6. getName() String The getName() method is used to find the


file name.

7. getAbsolutePath() String The getAbsolutePath() method is used to


get the absolute pathname of the file.

8. length() Long The length() method is used to get the size


of the file in bytes.

9. list() String[] The list() method is used to get an array of


the files available in the directory.

10. mkdir() Boolean The mkdir() method is used for creating a


new directory.

1
SCE/CSBS/CS3391/V.S
File Operations

We can perform the following operation on a file:

o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File

We can create a File object from

 A pathname
 A parent pathname and a child pathname
 A URI (uniform resource identifier)

We can use one of the following constructors of the File class to create a file:

 File(String pathname)
 File(File parent, String child)
 File(String parent, String child)
 File(URI uri)

import java.io.File;
// Importing the IOException class for handling errors
import java.io.IOException;
class CreateFile {
public static void main(String args[]) {
try {
// Creating an object of a file
File f0 = new File("D:\\FileExample.txt");
if (f0.createNewFile()) {
System.out.println("File " + f0.getName() + " is created successfully.");
} else {
System.out.println("File is already exist in the directory.");
}
System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());

// Checking whether the file is writable or not


System.out.println("Is file writeable?: " + f0.canWrite());
2
SCE/CSBS/CS3391/V.S
// 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());
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
}
Output:

E:\Java_MAT\pgms\29_09>java
29_09>java CreateFile
File FileExample.txt is created successfully.
The absolute path of the file is: D:\FileExample.txt
D:
Is file writeable?: true
Is file readable true
The size of the file in bytes is: 0

The next operation which we can perform on a file is "writing into a file". file" In order to
write data into a file, we will use the FileWriter class and its write() method together.

Java I/O (Input and Output) is used to process the input and produce the output.
output

Java uses the concept of a stream to make I/O operations fast. The java.i
java.io package contains all
the classes required for input and output operations.

3
SC
CE/CSBS/CS3391/V.S
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.

ams are created for us automatically. All these streams are attached with the
In Java, 3 streams
console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.

OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an output
sends them to some sink.
stream of bytes. An output stream accepts output bytes and sends

Types of Streams
Depending upon the data a stream holds, it can be classified into:
1. Byte Stream
2. Character Stream
1. Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called InputStream and
OutputStream.

4
SC
CE/CSBS/CS3391/V.S
Useful methods of OutputStream
Method Description

1) public void write(int)throws is used to write a byte to the current output


IOException stream.

2) public void write(byte[])throws is used to write an array of byte to the


IOException current output stream.

3) public void flush()throws IOException flushes the current output stream.

4) public void close()throws IOException is used to close the current output stream.

InputStream class

InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.

Useful methods of InputStream

The InputStream class provides different methods that are implemented by its subclasses. Here
are some of the commonly used methods:
read() - reads one byte of data from the input stream
read(byte[] array) - reads bytes from the stream and stores in the specified array
available() - returns the number of bytes available in the input stream
mark() - marks the position in the input stream up to which data has been read
reset() - returns the control to the point in the stream where the mark was set
markSupported() - checks if the mark() and reset() method is supported in the stream
skips() - skips and discards the specified number of bytes from the input stream
close() - closes the input stream

2. Character Stream
Character stream is used to read and write a single character of data.
All the character stream classes are derived from base abstract classes Reader and Writer.

5
SCE/CSBS/CS3391/V.S
When to use Character / Byte streams?
Character streams are used when we want to process text files. As we know Java stores
characters in Unicode format. Character stream processes data character by character. Character
stream performs input and output operations
operati bit Unicode which is equivalent to the size of
of 16-bit
a character in Java.
Byte streams are used to process raw data like binary files. If we have a file that contains binary
data, then it will be appropriate to use Byte stream. They can be used to read/write
read data of 8-bit
bytes.

6
SC
CE/CSBS/CS3391/V.S
Examples of Byte streams
public class ReadFile {

public static void main(String[] args) throws Exception{


File file = new File("source.txt");
if(file.exists()) {

FileInputStream fin = new FileInputStream("source.txt");

//1. to read the file contents byte-by-byte


int n = fin.read();
while(n != -1) {
System.out.print((char)n);
n = fin.read();
//Thread.sleep(10);
}

//2. to read file contents completely


byte[] b = new byte[fin.available()];
fin.read(b);
String file_contents = new String(b);
System.out.println(file_contents);

//3. to read file contents line-by-line /to convert byte stream to character stream
InputStreamReaderfile_source = new InputStreamReader(fin);

BufferedReaderbr = new BufferedReader(file_source);


String line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
//Thread.sleep(2000);
}
br.close();
fin.close();

}
else {
System.out.println("File is not available!");
}
}
}

To copy the content of one file to another file

import java.io.FileOutputStream;

7
SCE/CSBS/CS3391/V.S
public class WriteFile {

public static void main(String[] args) throws Exception {


//FileOutputStreamfout = new FileOutputStream("output/outfile.txt");
FileOutputStreamfout = new FileOutputStream("output/outfile.txt",true);

String str = "This is the content to write to file. ";


//to convert String to byte[]
byte[] data = str.getBytes();

fout.write(data);

System.out.println("file created");
fout.close();
}

Example of Character stream to read the content of a file


import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
--------------------------
Example of Character stream to write the content in to a file

import java.io.FileWriter;

public class Main {

public static void main(String args[]) {

String data = "This is the data in the output file";

try {
// Creates a FileWriter
FileWriter output = new FileWriter("output.txt");

8
SCE/CSBS/CS3391/V.S
// Writes the string to the file
output.write(data);

// Closes the writer


output.close();
}

catch (Exception e) {
e.getStackTrace();
}
}
}
--------------------------------
Example:

Convert all the text in a file to uppercase characters

import java.io.FileWriter;
import java.io.FileReader;

public class FileCaseChange {

public static void main(String args[]) {

String data = "This is the data in the output file";

try {
// creates a file reader
FileReader fr=new FileReader("FileIn.txt");
// Creates a FileWriter
FileWriter output = new FileWriter("Upperoutput.txt");
int i;
while((i=fr.read())!=-1) {
// read each char as byte and convert to uppercase
char outChar = Character.toUpperCase((char) i);
// write to the output file
output.write(outChar);
9
SCE/CSBS/CS3391/V.S
}
// Closes the writer
output.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}

Example: How to write the contents of an object to a file


import java.io.Serializable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
// this class’s object is stored in the file . so implement the interface serializable
class Person implements Serializable {

private String name;


private int age;
private String gender;
// default constructor
Person() {
};
// parameter constructor
Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}

@Override
public String toString() {
return "Name:" + name + "\nAge: " + age + "\nGender: " + gender;
}
}

10
SCE/CSBS/CS3391/V.S
public class WriterReaderObject {

public static void main(String[] args) {

Person p1 = new Person("Ram", 30, "Male");


Person p2 = new Person("Seetha", 25, "Female");

try {
FileOutputStream f = new FileOutputStream(new File("myObjects.txt"));
ObjectOutputStream o = new ObjectOutputStream(f);

// Write objects to file


o.writeObject(p1);
o.writeObject(p2);

o.close();
f.close();

} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} /* catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} */

Strings in Java
In Java, a string is a sequence of characters. For example, "hello" is a string containing a
sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use double quotes to represent a string in Java. For example,
// create a string
String type = "Java programming";
Here, we have created a string variable named type. The variable is initialized with the string
Java Programming.

11
SCE/CSBS/CS3391/V.S
There are two ways to create String object:

1. By string literal
2. By new keyword

Example: Create a String in Java(using literal)


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

// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";

// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
In the above example, we have created three strings named first, second, and third. Here, we are
directly creating strings like primitive types.

However, there is another way of creating Java strings (using the new keyword) which is given
later in this notes.
Note: Strings in Java are not primitive types (like int, char, etc). Instead, all strings are objects
of a predefined class named String.
And, all string variables are instances of the String class.
java.lang.String package contains all required classes, methods, properties, interface for strings
1.String s = new String();
2. String st = new String(String str);
String s2 = new String("Hello Java");

3. String str = new String(char char[])

char chars[ ] = { 'a', 'b', 'c', 'd' };

12
SCE/CSBS/CS3391/V.S
String s3 = new String(chars);
4. String str = new String(char chars[ ], intstartIndex, int count);
char chars[ ] = { 'w', 'i', 'n', 'd', 'o', 'w', 's' };
String str = new String(chars, 2, 3); ” ndo”
5. String(byte byteArr[ ])
public class ByteArray
{
public static void main(String[] args)
{
byte b[] = { 97, 98, 99, 100 }; // Range of bytes: -128 to 127. These byte values will be
converted into corresponding characters.
String s = new String(b);
System.out.println(s);  abc
}

6. String(byte byteArr[ ], intstartIndex, int count)


public class ByteArray
{
public static void main(String[] args)
{
byte b[] = { 65, 66, 67, 68, 69, 70 }; // Range of bytes: -128 to 127.
String s = new String(b, 2, 4); // CDEF
System.out.println(s);
}
}

Java String Operations


Java String provides various methods to perform different operations on strings. We will look
into some of the commonly used string operations.

1. Get length of a String


To find the length of a string, we use the length() method of the String. For example,

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

13
SCE/CSBS/CS3391/V.S
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);

// get the length of greet


int length = greet.length();
System.out.println("Length: " + length);
}
}
Output
String: Hello! World
Length: 12
In the above example, the length() method calculates the total number of characters in the string
and returns it.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer
and StringBuilder classes implement it. It means, we can create strings in Java by using these
three classes.

14
SCE/CSBS/CS3391/V.S
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder
classes.

Another way to create a string in java is as


String s=new String("Welcome"); //creates two objects and one reference variable

No. Method Description

1 char charAt(int index) It returns char value for the particular


index

2 int length() It returns string length

3 static String format(String format, It returns a formatted string.


Object... args)

4 static String format(Locale l, String It returns formatted string with given


format, Object... args) locale.

5 String substring(intbeginIndex) It returns substring for given begin index.

6 String substring(intbeginIndex, It returns substring for given begin index


intendIndex) and end index.

15
SCE/CSBS/CS3391/V.S
7 boolean contains(CharSequence s) It returns true or false after matching the
sequence of char value.

8 static String join(CharSequence It returns a joined string.


delimiter, CharSequence... elements)

9 static String join(CharSequence It returns a joined string.


delimiter, Iterable<? extends
CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string with the


given object.

11 booleanisEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

13 String replace(char old, char new) It replaces all occurrences of the specified
char value.

14 String replace(CharSequence old, It replaces all occurrences of the specified


CharSequence new) CharSequence.

15 static String It compares another string. It doesn't


equalsIgnoreCase(String another) check case.

16 String[] split(String regex) It returns a split string matching regex.

17 String[] split(String regex, int limit) It returns a split string matching regex and
limit.

18 String intern() It returns an interned string.

19 intindexOf(intch) It returns the specified char value index.

20 intindexOf(intch, intfromIndex) It returns the specified char value index


starting with given index.

21 intindexOf(String substring) It returns the specified substring index.

16
SCE/CSBS/CS3391/V.S
22 intindexOf(String substring, It returns the specified substring index
intfromIndex) starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase using


specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase using


specified locale.

27 String trim() It removes beginning and ending spaces


of this string.

28 static String valueOf(int value) It converts given type into string. It is an


overloaded method.

There are three ways to compare String in Java:

1. By Using equals() Method


2. By Using == Operator
3. By compareTo() Method

Suppose s1 and s2 are two String objects. If:

o s1 == s2 : The method returns 0.


o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.

Example 1
class Teststringcomparison1{ class Teststringcomparison2{ class Teststringcomparison3{
public static void main(String args[]){ public static void main(String args[] public static void main(String
String s1="Sachin"; ){ args[]){
String s2="Sachin"; String s1="Sachin"; String s1="Sachin";
String s3=new String("Sachin"); String s2="SACHIN"; String s2="Sachin";
17
SCE/CSBS/CS3391/V.S
String s4="Saurav"; String s3=new String("Sachin
System.out.println(s1.equals(s2));//true System.out.println(s1.equals(s2)); ");
//false System.out.println(s1==s2);
System.out.println(s1.equals(s3));//true System.out.println(s1.equalsIgnoreCa //true (because both refer to sa
se(s2));//true me instance)
System.out.println(s1.equals(s4));//false } System.out.println(s1==s3);
} //false(because s3 refers to insta
} nce created in nonpool)
} }
}

Example 2
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2)); //0
System.out.println(s1.compareTo(s3)); //1(because s1>s3)
System.out.println(s3.compareTo(s1)); //-1(because s3 < s1 )
}
}

String Concatenation in Java

In Java, String concatenation forms a new String that is the combination of multiple
strings. There are two ways to concatenate strings in Java:

1. By + (String concatenation) operator


2. By concat() method

18
SCE/CSBS/CS3391/V.S
Example of string concatenation

class TestStringConcatenation2{ class TestStringConcatenation3{


public static void main(String args[]){ public static void main(String args[]){
String s=50+30+"Sachin"+40+40; String s1="Sachin ";
System.out.println(s); //80Sachin4040 String s2="Tendulkar";
} String s3=s1.concat(s2);
} System.out.println(s3); //Sachin Tendulkar
}
}

A part of String is called substring. Java String class provides the built-in substring() method
that extract a substring from the given string by using the index values passed as an argument.
Example :
class TestSubstring{
public static void main(String args[]){
String s="SachinTendulkar";
System.out.println("Original String: " + s);
System.out.println("Substring starting from index 6: " +s.substring(6));//Tendulkar
System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6)); //Sachin
}
}
Output is:
Original String: SachinTendulkar

19
SCE/CSBS/CS3391/V.S
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6: Sachin
An Example of various built-in function of a String class
public class Stringoperations
{
public static void main(String ar[])
{
// builtin functions of String class
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s); //Sachin(no change in original)
System.out.println("-----------------------------------------------");

String s1=" Sachin";


System.out.println(s1);// Sachin
System.out.println(s1.trim());//Sachin //trim() method
System.out.println("-----------------------------------------------");

System.out.println(s.startsWith("Sa"));//true startWith() and endWith() functions


System.out.println(s.endsWith("n"));//true
System.out.println("-----------------------------------------------");

System.out.println(s.charAt(0));//S //charAt() function


System.out.println(s.charAt(3));//h

System.out.println("-----------------------------------------------");
System.out.println(s.length());//6
System.out.println("----- valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into String----");
int a=10;
String ss=String.valueOf(a);
System.out.println(ss+10);
20
SCE/CSBS/CS3391/V.S
System.out.println("-----------------------------------------------");
String s2="Java is a programming language. Java is a platform. Java is an Island.";
String replaceString=s2.replace("Java","Gova"); //replaces all occurrences of "Java" to "Gova"
System.out.println(replaceString);
}
}

Java StringBuffer Class


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.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously.
So it is safe and will result in an order.
Take an example of the folowing program that differenciates the string and a stringbuffer class
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
String s=new String("Python");
sb.append("Java");//now original string is changed
s.concat("Lang"); // original value of s doesn't change
System.out.println(sb);//prints Hello Java
System.out.println(s);

}
}
Output:
Hello Java
Python
In the above example, the orginal value of the StringBuffer is changes wheres that of the String
is not changed.
Important Constructors of StringBuffer Class

Constructor Description

StringBuffer() It creates an empty String buffer with the initial

21
SCE/CSBS/CS3391/V.S
capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified string..

StringBuffer(int capacity) It creates an empty String buffer with the specified


capacity as length.

An example shows various built-in methods of StringBuffer class


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

//The append() method concatenates the given argument with this String.
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Hello Java

//The insert() method inserts the given String with this string at the given position.
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb); //prints HJavaello Java

//The replace() method replaces the given String from the specified beginIndex and
endIndex.
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo

//The delete() method of the StringBuffer class deletes the String from the specified
beginIndex to endIndex.
sb.delete(1,3);
System.out.println(sb);//prints Hvavaello Java
//The reverse() method of the StringBuilder class reverses the current String.
sb.reverse();
System.out.println(sb); //prints avaJ olleavavH

22
SCE/CSBS/CS3391/V.S
//The capacity() method of the Strin gBuffer class returns the current capacity of the buffer.
StringBuffer
The default capacity of the buffer is 16.
System.out.println(sb.capacity()
capacity());//now 16
}
}

NOTE: like StringBuffer class , java also has StringBuilder class ( which is also
mutable)

StringBuffer StringBuilder
StringBuffer operations are thread-safe
thread and StringBuilder operations are not thread
thread-safe are not-
synchronized synchronized.
StringBuffer is to used when multiple threads are StringBuilder is used in a single-threaded
single
working on the same String environment.
StringBuffer performance is slower when compared StringBuilder performance is faster when compared
to StringBuilder to StringBuffer
Syntax: StringBuffer var = new StringBuffer(str); Syntax: StringBuilder var = new StringBuilder(str);

23
SC
CE/CSBS/CS3391/V.S
Generics in Java
Generics is a concept in Java where you can enable a class, interface and, method, accept all
(reference) types as parameters. In other words it is the concept which enables the users to
choose the reference type that a method, constructor of a class accepts, dynamically.
By defining a class generic you are making it type-safe i.e. it can act up on any datatype. To
understand generics let us consider an example −
class Student{
Integer age;
Student(Integer age){
this.age = age;
}
public void display() {
System.out.println("Value of age: "+this.age);
}
}
public class NoNGenericsExample {
public static void main(String args[]) {
Student std = new Student(25);
std.display();
}
}

The output of the above program is : Value of age: 25


Suppose, if we write

24
SCE/CSBS/CS3391/V.S
Student std = new Student("25");
std.display();

it gives error as the constructor will take only int not string
or, if we want our class to work with different datatype then , we should add the different
constructor ( constructor overloading) as folows:
class Student{
String age;
Student(String age){
this.age = age;
}
}
Or,
class Student{
Float age;
Student(Float age){
this.age = age;
}
}

So,
When you declare generic types they can act upon any datatypes and, they are known as
parameterized types. You cannot use primitive datatypes in generics.
To create a class of generic type by using generic parameter T or, GT as −
class Student <T>{
T obj;
}
Where T (generic parameter) represents the datatype of the object you can pass to the
constructor of this class. This will be determined at the compilation time.
While instantiating the class you need to/can choose the type of the generic parameter as

Student<Float> obj = new Student<Float>();

The previous example can be re-written using generics as,

25
SCE/CSBS/CS3391/V.S
class Student<T>{
T age;
Student(T age){
this.age = age;
}
public void display() {
System.out.println("Value of age: "+this.age);
}
}
public class GenericsExample {
public static void main(String args[]) {
Student<Float> std1 = new Student<Float>(25.5f);
std1.display();
Student<String> std2 = new Student<String>("25");
std2.display();
Student<Integer> std3 = new Student<Integer>(25);
std3.display();
}
}

Output
Value of age: 25.5
Value of age: 25
Value of age: 25

The advantages of using Generics are:


 Type check at compile time −usually, when you use types (regular objects), when
you pass an incorrect object as a parameter, it will prompt an error at the run time.
 Whereas, when you use generics the error will be at the compile time which is
easy to solve.

26
SCE/CSBS/CS3391/V.S
 Code reuse − You can write a method or, Class or, interface using generic type
once and you can use this code multiple times with various parameters.
 For certain types, with formal types, you need to cast the object and use. Using
generics (in most cases) you can directly pass the object of required type without
relying on casting.

We can also pass multiple Type parameters in Generic classes.


Example:
// Java program to show multiple
// type parameters in Java Generics
// We use < > to specify Parameter type

class Test<T, U>


{
T obj1; // An object of type T
U obj2; // An object of type U

// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

// To print objects of T and U


public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}

// Driver class to test above


class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj =
27
SCE/CSBS/CS3391/V.S
new Test<String, Integer>("Ramlakshman", 15);

obj.print();
}
}

Output is : RamLakshman
15
NOTE:
When we declare an instance of a generic type, the type argument passed to the type
parameter must be a reference type. We cannot use primitive data types like int, char.
Test<int> obj = new Test<int>(20); //ERROR
Test<Integer> obj=new Text<Integer>(20); // correct

Generic Method
Like the generic class, we can create a generic method that can accept any type of
arguments. Here, the scope of arguments is limited to the method where it is declared. It
allows static as well as non-static methods.
Let's see a simple example of java generic method to print array elements. We are using
here E to denote the element.

public class TestGenericsMethod{

public static < E > void printArray(E[] elements) {


for ( E element : elements){
System.out.print(element );
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'S', 'A', 'R', 'A', ‘N’,’A','T','H','A','N' };

28
SCE/CSBS/CS3391/V.S
System.out.println( "Printing Integer Array" );
printArray( intArray );

System.out.println( "Printing Character Array" );


printArray( charArray );
}
}
Output:
Printing Integer Array
10 20 30 40 50
Printing Character Array
SARANATHAN

Bounded-types in generics

Whenever you want to restrict the type parameter to subtypes of a particular class you
can use the bounded type parameter. If you just specify a type (class) as bounded
parameter, only sub types of that particular class are accepted by the current generic
class. These are known as bounded-types in generics in Java.
You can declare a bound parameter just by extending the required class with the type-
parameter, within the angular braces as −
class Sample <T extends Number>
In the following Java example the generic class Sample restricts the type parameter to the
sub classes of the Number classes using the bounded parameter.

class Sample <T extends Number>{


T data;
Sample(T data){
this.data = data;
}
public void display() {
29
SCE/CSBS/CS3391/V.S
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

Data value is: 20


Data value is: 20.22
Data value is: 125.332
Now, if you pass other types as parameters to this class (say, String for example) a
compile time error will be generated.
Sample<String> obj3 = new Sample<String>("Krishna");
obj3.display(); ERROR

30
SCE/CSBS/CS3391/V.S

You might also like