0% found this document useful (0 votes)
93 views

Unit 5 Java Students

This document provides an overview of nested types (inner classes) in Java, including the different types of inner classes and examples of each: 1) It defines nested types as a type defined within another type, and discusses the need for type within type including increased encapsulation. 2) The four types of inner classes in Java are defined as non-static, static, local, and anonymous inner classes with brief descriptions and examples provided for each. 3) Additional details and examples are given on non-static inner classes, static inner classes, and anonymous inner classes to further illustrate their properties and usage. Local inner classes are also briefly covered.

Uploaded by

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

Unit 5 Java Students

This document provides an overview of nested types (inner classes) in Java, including the different types of inner classes and examples of each: 1) It defines nested types as a type defined within another type, and discusses the need for type within type including increased encapsulation. 2) The four types of inner classes in Java are defined as non-static, static, local, and anonymous inner classes with brief descriptions and examples provided for each. 3) Additional details and examples are given on non-static inner classes, static inner classes, and anonymous inner classes to further illustrate their properties and usage. Local inner classes are also briefly covered.

Uploaded by

Mohit Agrawal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 167

UNIT 5

K.S.SHASHIKALA,AP/CSE
SYLLABUS

 Nested Types: Need for Type within Type

 Different Types of Inner Classes, Anonymous Inner


Classes

 Persistence: Reading from Files, Writing into Files

 Concept of Serialization.

 Introduction to Generics and Collections: Generic


Programming Concepts, Concept of Generic Box, List
Interface, Sort and Search.
K.S.SHASHIKALA,AP/CSE
Nested Types
Whenever we require a type inside a type, this concept is called nested type or inner
class. In short, an instance of inner types hold a reference to an instance of the outer
type.

Need for type within type

 We can increase the encapsulation.


 We can hide the class.
 This shall be used only by the outer class and no other class.
 As only this class requires the inner class, we can avoid polluting the namespace.
 Implementation of this inner class may require or may use the outer class.

K.S.SHASHIKALA,AP/CSE
Different types of inner classes in java

There are four types of inner classes in java:

a) non-static inner class


b) static inner class
c) local inner class
d) anonymous inner class

K.S.SHASHIKALA,AP/CSE
a)Inner class or non-static inner class:
Here, the object of the inner class is created using an object of
outer class.

The object of inner class remembers the object of outer


class,using which the inner class object is created – is called
outer this.

In the example, there is a class called Domain. Each Domain


has a name.

The Domain contains a class called Member. Every member


has to belong one or the other Domain. So the member object
is created using the Domain object.
K.S.SHASHIKALA,AP/CSE
package shashikala1;

public class Example1innner


{
public static void main(String[] args)
{
Domain d1 = new Domain("RainBow");
// John and peter belong to the domain RainBow
//member cannot be resolved to a type if d1 is not present.
Domain.member m1 = d1.new member("john”);
Domain.member m2 = d1.new member("peter");

Domain d2 = new Domain("Sea");


// mary belongs to the domain Sea.
Domain.member m3 = d2.new member("mary");

m1.disp();
m2.disp();
m3.disp();
}
}

K.S.SHASHIKALA,AP/CSE
class Domain
{
private String name;
public Domain(String name)
{
this.name = name;
}
public class member
{
private String memberName;

public member(String memberName)


{
this.memberName = memberName;
}
// name here refers to the field of the outer class
public void disp()
{
System.out.println("name : " + name + " member : " + memberName);
}
}
K.S.SHASHIKALA,AP/CSE
}
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
2) Static inner class
 The inner class does not remember anything of the outer class.

 We do not require an object of outer class to create an object of


inner class.

 This is the way many utility classes are developed.


 Static nested classes are accessed using the enclosing class name
OuterClass.StaticNestedClass
 For example, to create an object for the static nested class, use this
syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass. StaticNestedClass();

 It can access static data members of outer class including private.


Static nested class cannot access non-static (instance) data
member or method. K.S.SHASHIKALA,AP/CSE
Java static nested class example with instance method
package shashikala1;
public class TestOuter12
{
private static int data=30;
static class Inner{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
//TestOuter1.Inner obj=new TestOuter1.Inner(); //allowed
Inner obj=new Inner();
obj.msg();
}
} K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
//STATIC INNER CLASS – ANOTHER EXAMPLE
package shashikala1;

public class Example2inner


{
public static void main(String[] args)
{
int[] x = { 1, 1, 2, 3, 5, 8, 13, 21, 34 };
MyNumbers n = new MyNumbers(x);
//outer.inner method
System.out.println(n.firstTwo().getFirst());
MyNumbers.Pair p = n.lastTwo();

System.out.println(p.getFirst() + " : " + p.getSecond());


}
}
K.S.SHASHIKALA,AP/CSE
class MyNumbers
{
private int[] a;
public MyNumbers(int[] x) //constructor takes array as parameter
{
a = new int[x.length];
for (int i = 0; i < x.length; i++)
{
a[i] = x[i];
}
}
public Pair firstTwo()
{
return new Pair(a[0], a[1]);
}
public Pair lastTwo()
{
return new Pair(a[a.length - 2], a[a.length - 1]);
}
K.S.SHASHIKALA,AP/CSE
static public class Pair {
private int first;
private int second;
public Pair(int first, int second)
{
this.first = first;
this.second = second;
}
public int getFirst()
{
return first;
}

public int getSecond()


{
return second;
}
}} K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
local inner class
In this case, we create a class within a method. So, this
can be used only in that method and nowhere else.

Local Inner Classes are the inner classes that are defined
inside a block. Generally, this block is a method body.

Sometimes this block can be a for loop, or an if clause.

Local Inner classes are not a member of any enclosing


classes.
K.S.SHASHIKALA,AP/CSE
// local inner class
// class within a method; no body can use it outside of this method
public class Example3
{
public static void main(String[] args)
{
foo();
}
// no body outside of foo can know MyBreakfast!
public static void foo()
{
class MyBreakfast
{
private String name;
public MyBreakfast(String name)
{ this.name = name; }
public void disp()
{
System.out.println("breakfast : " + name);
}
}
K.S.SHASHIKALA,AP/CSE
MyBreakfast mbf = new MyBreakfast("dosa"); mbf.disp(); } }
K.S.SHASHIKALA,AP/CSE
Can you find out the error in the following code?

class A
{
class B //Member non static inner class
{
static void methodB()
{
System.out.println("Method B");
}
}
}

Answer :
Members of inner classes can’t have static members in
them. K.S.SHASHIKALA,AP/CSE
2 ) What is the output of the following code?
class X
{
static int x = 3131;
static class Y
{
static int y = x++;
static class Z
{
static int z = y++;
}
}
}
public class MainClass
{
public static void main(String[] args)
{
System.out.println(X.x);
System.out.println(X.Y.y);
System.out.println(X.Y.Z.z);
}
}
Answer :
K.S.SHASHIKALA,AP/CSE
3131 3131 3131
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
3) Static nested classes can have only static members in them. True
OR False?

Answer :
False. Static nested classes can have both static and non-static
members.
4) How do you access field ‘i’ of class ‘XYZ’ in the below code?

class ABC
{
class XYZ
{
int i = 111;
}
}
Ans:
new ABC().new XYZ().i,bothK.S.SHASHIKALA,AP/CSE
are non static ,so u need to create
objects to access i.
K.S.SHASHIKALA,AP/CSE
class A // 5) What is the output of the following code?
{
{
new B();
}

static class B
{
{
new A().new C();
}
}
class C
{
{
System.out.println("SUCCESS");
}
}
}
public class MainClass
{
public static void main(String[] args)
{
new A(); } } K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
6)IS THE BELOW CODE CORRECT?
class A
{
String s = "AAA";

void methodA() //non static method


{
System.out.println(s);
}
static class B
{
void methodB()
{
methodA();
}
}
}
K.S.SHASHIKALA,AP/CSE
No. You can’t use non-static method of outer class inside a static nested class
directly. You have to instantiate the outer class.

Cannot make a static reference to the non static method methodA().

K.S.SHASHIKALA,AP/CSE
d) Anonymous inner class:
In the good old days, the husbands of the house would
not call their wife by name and the wives forbidden to call
their husbands by name. The lady would refer to the husband
as “that person – avaru in kannada” or as “father of chinnu or
munnu”. So clearly name is not a necessity to refer to a thing
or a person.

Why should everything have a name? If I want to use


something only once, why give a name at all? This is the
concept behind anonymous entities in programming.

We can make a new class from an existing class and make an


object immediately – all in one go. For this, in Java, we use
Anonymous inner class. This is used very heavily in Java.
K.S.SHASHIKALA,AP/CSE
// anonymous inner class
public class Example4 {
public static void main(String[] args)
{
Tester t1 = new Tester();
t1.test();
// makes a new class with no name; overrides whichever methods it wants to.
// avoids unnecessary name
Tester t2 = new Tester()
{
public void test()
{
System. out. println("this is a new test"); } };
t2.test();
}
}
class Tester
{
public void test()
{
System.out.println("this is a test");
} K.S.SHASHIKALA,AP/CSE
}
K.S.SHASHIKALA,AP/CSE
Consider the following code:

Tester is a class. The code new Tester() would create an


object of the class Tester.

But this code is followed by a block of code. This block of


code is extending the class Tester – thereby creating a new
class with no name – anonymous class.

This new class overrides the method test. Therefore t2


instantiates this new anonymous class which extends Tester.

Call to the method test using tester would call this


overridden method.
Tester t2 = new Tester() {
public void test() {
System.out.println("this is a new test");
} }; K.S.SHASHIKALA,AP/CSE
7)Can abstract class be instantiated? If yes, what will be the
output?
abstract class A
{
{
System.out.println(1);
}

static
{
System.out.println(2);
}
}

public class MainClass


{
public static void main(String[] args)
{
A a = new A() { };
}
}
K.S.SHASHIKALA,AP/CSE
If the class instance creation expression results in a class body,
then the class being instantiated is an anonymous subclass.

you can instantiate a concrete subclass of your abstract class.


Anonymous codeblocks limit the scope of variables.

This line of code is executed whenever a new instance of the


class is created.

K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
Will the previous code produce output if the line

A9 a = new A9( ) { };

is not there?

K.S.SHASHIKALA,AP/CSE
What will be the output of the below program?
class A7
{
static String s = "AAA";
class B
{
String s = "BBB";

void methodB()
{ OUTPUT:
System.out.println(s); AAA
} BBB
} BBB
}
public class MainClass
{
public static void main(String[] args)
{
A7 a = new A7();
System.out.println(a.s);
A7.B b = a.new B();
System.out.println(b.s);
b.methodB(); K.S.SHASHIKALA,AP/CSE
} }
Can you find out the error in the following code?
class A
{
void methodOne()
{
class B
{
void methodTwo()
{
System.out.println("Method Two");
}
}
}

void methodThree()
{
new B().methodTwo();
}
}

Ans:Local inner classes are not visible outside the method or block in which they are
defined. K.S.SHASHIKALA,AP/CSE
What will be the output of the following program?
class X
{
{
System.out.println(1);
}
static
{
System.out.println(2);
}
public X()
{
new Y();
}
static class Y
{
{
System.out.println(3);
}
static
{
K.S.SHASHIKALA,AP/CSE
System.out.println(4); } } }
public class MainClass
{
public static void main(String[] args)
{
X x = new X();
X.Y y = new X.Y();
}
}

Ans: 2 1 4 3 3
//inner class constructors are not invoked until you
create an object.

K.S.SHASHIKALA,AP/CSE
WHAT IS THE OUTPUT OF THIS CODE?

10099
2
2

K.S.SHASHIKALA,AP/CSE
Persistence: Reading from Files, Writing into Files

 A file provides mechanism to store the information even after the


program terminates – and can be read by the same or some other
program later. This concept is called serialization or persistence.

 It is equally true that there are number of ways of reading and writing
from a file .We will go through a series of examples of input and output.

 We may expect IO exceptions – file not found, no permission for read


or writing … There are a number of reasons why the input output
operations could fail. So We specify that our program may throw an
exception and we also try to handle the exception.

 We will close the opened file in finally block if the opening has
succeeded.

K.S.SHASHIKALA,AP/CSE
Introduction to Data Streams
Often programs need to bring in information from an external
source or send out information to an external destination. The
information can be anywhere: in a file, on disk, somewhere on
the network, in memory, or in another program.

Also, it can be of any type: objects, characters, images, or


sounds.

To bring in information, a program opens a stream on an


information source (a file, memory, a socket) and reads the
information serially, like this:

K.S.SHASHIKALA,AP/CSE
Similarly, a program can send information to an external
destination by opening a stream to a destination and writing
the information out serially, like this:

No matter where the information is coming from or going to and


no matter what type of data is being read or written, the
algorithms for reading and writing data is pretty much
always the same.

K.S.SHASHIKALA,AP/CSE
Four types of streams
There are 4 different types of streams available.
They are:

• Byte streams

• Character streams

• Line oriented streams

• Scanner Object

K.S.SHASHIKALA,AP/CSE
1.byte streams:

We read the file byte by byte and write to another file.


Programs should use the byte streams, descendants of InputStream
and OutputStream, to read and write 8-bit bytes.

These streams are typically used to read and write binary data
such as images and sounds.

FileInputStream supports read and returns -1 when the end of


file is reached.

FileOutputStream supports write operation, which writes a single


byte to the output file. These are very low level routines.
This stream is a very lower stream.
K.S.SHASHIKALA,AP/CSE
import java.io.*;
public class Example1
{
public static void main(String[] args) throws IOException
{
FileInputStream fin = null;
FileOutputStream fout = null;
try
{
fin = new FileInputStream("test.txt");
fout = new FileOutputStream("newtest.txt");
int ch;
while((ch = fin.read()) != -1)
{
fout.write(ch);
}
}
catch(IOException e) { System.out.println(e); }
finally {
if(fin != null) fin.close();
if(fout != null) fout.close(); }
K.S.SHASHIKALA,AP/CSE
} }
K.S.SHASHIKALA,AP/CSE
2.Character Streams

This treats the character as the smallest unit of reading and


writing.

FileReader allows reading a character – could be unicode.

FileWriter allows writing a unicode character into the file.


Otherwise this is similar to bytestreams.

// FileReader extends Reader

// FileWriter extends Writer

// can support unicode format


K.S.SHASHIKALA,AP/CSE
import java.io.*;
public class Example2
{
public static void main(String[] args) throws IOException
{
FileReader fin = null;
FileWriter fout = null;
try { fin = new FileReader("test.txt");
fout = new FileWriter("newtest.txt");
int ch;
while((ch = fin.read()) != -1)
{
fout.write(ch);
}
}
catch(IOException e) {
System.out.println(e);
} finally { if(fin != null) fin.close();
if(fout != null)
fout.close(); }
}
K.S.SHASHIKALA,AP/CSE
}
3. Line oriented streams

 These streams provide mechanism to read line and


write line.

 We can also make a string and write it in one stroke.

 This concept of buffering helps in matching


memory speeds with I/O speeds.

 Line Oriented IO provides line functionality over


CharacterStreams

 BufferedReader &PrintWriter classes are used.


K.S.SHASHIKALA,AP/CSE
import java.io.*;
public class Example3
{
public static void main(String[] args) throws IOException
{
BufferedReader fin = null;
PrintWriter fout = null;
try
{
fin = new BufferedReader(new FileReader("test.txt"));
fout = new PrintWriter(new FileWriter("newtesting.txt"));
String ch;
int i = 0;
while((ch = fin.readLine()) != null)
{
fout.println(++i + " : " + ch);
}
}
catch(IOException e)
{
System.out.println(e);
}
finally { if(fin != null) fin.close();
if(fout != null) fout.close(); } } } K.S.SHASHIKALA,AP/CSE
OUTPUT FILE WHICH IS COPIED FROM test.txt

K.S.SHASHIKALA,AP/CSE
DIFFERENCES BETWEEN PRINTWRITER AND
FILEWRITER

• The main difference is that PrintWriter offers some additional


methods for formatting such as println and printf.

• PrintWriter methods do not throws IOException, instead they set a


boolean flag which can be obtained using checkError().

• FileWriter throws IOException in case of any I/O failure.

• PrintWriter automatically invokes flush after every byte of data is


written.

• In case of FileWriter, caller has to take care of invoking flush.

K.S.SHASHIKALA,AP/CSE
Java Scanner class

There are various ways to read input from the keyboard, the
java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a
delimiter that is whitespace by default. It provides many
methods to read and parse various primitive values.

Java Scanner class is widely used to parse text for string and
primitive types using regular expression.

Java Scanner class extends Object class and implements


Iterator and Closeable interfaces.

K.S.SHASHIKALA,AP/CSE
List of commonly used Scanner class methods

Method Description

public String next() it returns the next token from the scanner.

public String nextLine() it moves the scanner position to the next line
and returns the value as a string.

public byte nextByte() it scans the next token as a byte.

public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

public double nextDouble() it scans the next token as a double value.

K.S.SHASHIKALA,AP/CSE
Text File Input with the Scanner Class
• In the earlier cases, we used read the input as characters.

• The Scanner class make text file input easy enough as the
scanner is opened on a text file rather than the keyboard, and
the usual methods can be used for the input of different data
types.

• When used with a text file, a scanner behaves a bit like an


iterator with collections.

• The method hasNext detects the end of the file, so a


simple while loop can be used to read through a file of data.

K.S.SHASHIKALA,AP/CSE
import java.io.*;
import java. util.*;
public class Example4
{
public static void main(String[] args) throws IOException
{
Scanner fin = null;
PrintWriter fout = null;
try {
fin = new Scanner( new FileReader(“src/test.txt")));
fout = new PrintWriter(new FileWriter(“src/newtest.txt"));
String s;
while(fin. hasNext())
{
s = fin.next(); // finds and returns the next complete token from the scanner
fout.println(s);
}}
catch(IOException e)
{ System.out.println(e); }
finally { if(fin != null) fin.close();
if(fout != null)
fout.close();
}
} } K.S.SHASHIKALA,AP/CSE
Java PrintStream Class
The PrintStream class provides methods to write data to another stream.

The PrintStream class automatically flushes the data so there is no need to


call flush() method. Moreover, its methods don't throw IOException.

Class declaration
Let's see the declaration for Java.io.PrintStream class:

public class PrintStream extends FilterOutputStream implements Closeable.

K.S.SHASHIKALA,AP/CSE
PrintStream class Example

K.S.SHASHIKALA,AP/CSE
mfile.txt

K.S.SHASHIKALA,AP/CSE
Example of Scanner class with delimiter.

K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
In the below code, Class C extends Class A which has Class B as a
member inner class. Then, can you tell whether the members of Class
B are also inherited to Class C or not?

class A
{
int a;

class B
{
int b;
}
}

class C extends A
{

}
K.S.SHASHIKALA,AP/CSE
Can interfaces have inner classes in them?

Answer :
Yes, interfaces can have inner classes defined in them.

How do you access hidden outer class variable in inner


class?
Answer
To access non-static hidden outer class variable in inner class,
use this syntax : OuterClassName. this. variableName

and to access static hidden outer class variable in inner class


use the same syntax or access like

OuterClassName.variableName.
K.S.SHASHIKALA,AP/CSE
Java Nested Interface
An interface i.e. declared within another interface or class is
known as nested interface.

The nested interfaces are used to group related interfaces so


that they can be easy to maintain.

The nested interface must be referred using the outer interface


or class. It can't be accessed directly.

Nested interface must be public if it is declared inside the


interface but it can have any access modifier if declared within
the class.

Nested interfaces are declared static implicitly.


K.S.SHASHIKALA,AP/CSE
WHAT WILL BE THE OUTPUT OF THE CODE?

Ans: 4444
methodA of class D calls show method of class E which is inner class of class D
Method of outer class calls method of inner class by creating objects of inner class.
K.S.SHASHIKALA,AP/CSE
Ans:
78

K.S.SHASHIKALA,AP/CSE
WHAT IS THE OUTPUT ?

Ans:
4444

K.S.SHASHIKALA,AP/CSE
Interview Question :What is the reason for this output ?

K.S.SHASHIKALA,AP/CSE
DataInputStream and DataOutputStream class in Java
 A data input stream enable an application read primitive Java data types from
an underlying input stream in a machine-independent way(instead of raw bytes).
That is why it is called DataInputStream – because it reads data (numbers)
instead of just bytes.

 A Java application uses a data output stream to write data that can later be read
by a data input stream. Data input streams and data output streams represent
Unicode strings in a format that is a slight modification of UTF-8.

 DataInputStream is not necessarily safe for multithreaded access. Thread


safety is optional and is the responsibility of users of methods in this class.

 Java DataOutputStream class allows an application to write primitive Java


data types to the output stream in a machine-independent way.

K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
writeUTF method:

The java.io.DataOuputStream.writeUTF(String str) method


writes a string to the underlying output stream using modified
UTF-8 encoding.

Declaration

public final void writeUTF(String str)

Parameters
str − a string to be written to the output stream.

This method does not return any value.

K.S.SHASHIKALA,AP/CSE
UTF-8 ENCODING
A more efficient encoding can be achieved for files that are
composed primarily of ASCII text by encoding the more
common characters in fewer bytes.

UTF-8 is one such format that encodes the non-null ASCII


characters in a single byte, characters between 128 and 2047
and ASCII null in two bytes, and the remaining characters in
three bytes.

While theoretically this encoding might expand a file’s size by


50%, because most text files contain primarily ASCII, in practice
it’s almost always a huge savings.

Therefore, Java uses UTF-8 in string literals, identifiers, and


other text data in compiled byte code.
K.S.SHASHIKALA,AP/CSE
// Can have combination of different types, all simple types and strings
// Create a data stream and write the data
import java.io.*;
import java.util.*;

public class Example1data {


public static void main(String[] args) throws IOException
{
DataOutputStream fout = null;
String[] s = { "gavaskar", "srikanth", "amarnath", "kapildev" };
int[] runs = { 36, 66, 85, 175 };
try {
fout = new DataOutputStream( new FileOutputStream ("newtestdata.txt"));
for(int i = 0; i < s.length; i++) {
fout. writeUTF(s[i]);
fout.writeInt(runs[i]);
}
}

catch(IOException e)
{
System.out.println (e);
} finally { if(fout != null) fout.close(); }
} K.S.SHASHIKALA,AP/CSE
}
K.S.SHASHIKALA,AP/CSE
// Writing the data using DataOutputStream and reading the data
back using DataInputStream
package shashikala1;
import java.io.*;
public class Example1File
{
public static void main(String args[]) throws IOException
{
. try
{
DataOutputStream dout = new DataOutputStream(new FileOutputStream("src/test.bat")) ;
dout.writeDouble(1.1);
dout.writeInt(55);
dout.writeBoolean(true);
dout.writeChar('4');
}
catch(FileNotFoundException ex)
{
System.out.println("Cannot Open the Output File");
return;
} K.S.SHASHIKALA,AP/CSE
// reading the data back using DataInputStream
try
{
DataInputStream din = new DataInputStream(new
FileInputStream("src/test.bat")) ;

double a = din.readDouble();
int b = din.readInt();
boolean c = din.readBoolean();
char d=din.readChar();
System.out.println("Values: " + a + " " + b + " " + c+" " + d);
}
catch(FileNotFoundException e)
{
System.out.println("Cannot Open the Input File");
return;
}
} } K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
//WRITING INTEGER TO FILE AND READING IT
package examples;
import java.io.*;

public class FileCheck {

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


// TODO Auto-generated method stub
File f=new File("src/shashifile.txt");
FileOutputStream fos=new FileOutputStream(f);
DataOutputStream dos=new DataOutputStream(fos);
dos.writeInt(1237777);

FileInputStream fis=new FileInputStream(f);


DataInputStream dis=new DataInputStream(fis);

int s=dis.readInt();
System.out.println(s);
//dos.close();
}
K.S.SHASHIKALA,AP/CSE
}
Serialization in Java
• Serialization in java is a mechanism of writing the state of an object into a
byte stream.
• The reverse operation of serialization is called deserialization.

• It is mainly used in Hibernate, RMI, JPA, EJB.

Advantage of Java Serialization


 It is mainly used to travel object's state on the network (known as
marshaling).

 In the next example, we will store the objects into a file and bring them
back later.

 This serialization of objects requires that we implement the marker


interface called Serializable.
 As in the case of Cloneable interface, JVM will take care of all the
operations. We only have to indicate that we want this service. In this
example, we create an array of 4 objects. We write the object into a
file. K.S.SHASHIKALA,AP/CSE
Java.io.ObjectOutputStream Class in Java
 An ObjectOutputStream writes primitive data types and graphs of Java
objects to an OutputStream. The objects can be read (reconstituted) using an
ObjectInputStream.

 Persistent storage of objects can be accomplished by using a file for the


stream.

 Only objects that support the java.io.Serializable interface can be


written to streams.

 The class of each serializable object is encoded including the class name
and signature of the class, the values of the object’s fields and arrays,
and the closure of any other objects referenced from the initial objects.

 The Java ObjectOutputStream is often used together with a Java


ObjectInputStream.

 The ObjectOutputStream is used to write the Java objects, and the


ObjectInputStream is used to read the objects again.
K.S.SHASHIKALA,AP/CSE
// Create a serialization of object(s)
import java.io.*;
import java. util.*;
public class Example3 {
public static void main(String[] args) throws IOException
{
ObjectOutputStream fout = null;
String[] s = { "gavaskar", "srikanth", "amarnath", "kapildev" };
int[] runs = { 36, 66, 85, 175 };
Score[] score = new Score[4]; //declaring array of objects
for(int i = 0; i < score.length; i++)
{
score[i] = new Score(s[i], runs[i]); //Score(String name, int runs)
}
try {
fout = new ObjectOutputStream(new BufferedOutputStream( new
FileOutputStream("out.txt")));
for(int i = 0; i < score.length; i++)
{
fout. writeObject(score[i]);
} K.S.SHASHIKALA,AP/CSE
catch(IOException e)
{
System.out.println(e);
}
finally
{
if(fout != null)
fout.close();
}
}
}
class Score implements Serializable // marker interface
{
private String name;
private int runs;
public Score(String name, int runs)
{
this.name = name; this.runs = runs;
}
public String toString()
{ return name + ":" + runs;
K.S.SHASHIKALA,AP/CSE
} }
out.txt

K.S.SHASHIKALA,AP/CSE
In the deserialization example, we read from the object created in the last example as an
Object and downcast to the right class. Now the object is ready for consumption.
import java.io.*;
import java.util.*;
public class Example4 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream fin = null;
try
{
fin = new ObjectInputStream(new BufferedInputStream( new
FileInputStream("out.txt")));
while(true)
{
Score s = (Score)fin.readObject();
System.out.println(s);
}
}
catch(IOException e)
{ System.out.println(e);
}
finally
{
if(fin != null) fin.close();
K.S.SHASHIKALA,AP/CSE
}}}
class Score implements Serializable
{
private String name;
private int runs;

public Score(String name, int runs)


{
this.name = name;
this.runs = runs;
}

public String toString()


{
return name + ":" + runs;
}
}
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
SERIALIZATION & DESERIALIZATION EXAMPLE
package shashikala1;
import java.io.*;
import java.util.*;
import java.io.Serializable;

class Student35 implements Serializable


{
int id;
String name;

public Student35(int id, String name)


{
this.id = id;
this.name = name;
}
}
K.S.SHASHIKALA,AP/CSE
public class Example3
{
public static void main(String args[]) throws Exception
{
Student35 s1 = new Student35(211, “Peter");
FileOutputStream fout = new FileOutputStream("f.txt");
ObjectOutputStream out = new ObjectOutputStream(fout);

out.writeObject(s1);
// out.flush();

System.out.println("success");

// deserialization

ObjectInputStream in = new ObjectInputStream(new FileInputStream("f.txt"));


Student35 s= (Student35) in.readObject();
System.out.println(s.id + " " + s.name);
in.close();
}
} K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
Boxing and Unboxing
 There are cases where we may have to convert a value of a primitive
type to an object reference. To support this feature, java provides
wrapper classes corresponding to each of the eight primitive types.

 Conversion of a value of a primitive to its corresponding reference type


is called Boxing. Conversion of a value of a reference type back its
corresponding primitive type is called Unboxing.

 When we assign a value of primitive to a reference of its corresponding


reference type, the boxing happens automatically – is called
autoboxing.

 Conversion of a value in a reference type to its corresponding primitive


type happens when a reference is assigned to a variable of primitive
type. This is called autounboxing.
K.S.SHASHIKALA,AP/CSE
AUTOBOXING / AUTOUNBOXING EXAMPLE

K.S.SHASHIKALA,AP/CSE
// Boxing and unboxing, autoboxing and
autounboxing

public class Ex
{
public static void main(String[] args)
{
int a = 10; // primitive type
Integer b = new Integer(20); // reference type
Integer c = 30; // autoboxing
// unboxing : reference type -> corresponding primitive
int d = c;
}
}
K.S.SHASHIKALA,AP/CSE
Collections in Java
• The Collection in Java is a framework that provides
an architecture to store and manipulate the group of
objects.

• All the operations that you perform on a data such as


searching, sorting, insertion, manipulation, deletion,
etc. can be achieved by Java Collections.

• Java Collection means a single unit of objects. Java


Collection framework provides many interfaces (Set,
List, Queue, Deque, etc.) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet, etc.).
K.S.SHASHIKALA,AP/CSE
Using the Collection framework

Prior to the JDK 5.0 release, when you created a Collection, you
could put any object in it.

List myList = new ArrayList(10);


myList.add(new Integer(10));
myList.add("Hello, World");

Getting items out of the collection required you to use a casting


operation:
Integer myInt = (Integer)myList.iterator().next();
If you accidentally cast the wrong type, the program would
successfully compile, but an exception would be thrown at
runtime.

K.S.SHASHIKALA,AP/CSE
Collection Framework

Collections framework was not a part of original Java release.

Collections was added to J2SE 1.2.

Prior to Java 2, Java provided adhoc classes such as Dictionary,


Vector, Stack and properties to store and manipulate groups of
objects.

Framework in java means hierarchy of classes and interfaces.

Collections framework is contained in java.util package.

It provides many important classes and interfaces to collect and


organize group of alike objects.
K.S.SHASHIKALA,AP/CSE
Important Interfaces of Collection API
Interface Description

Collection Enables you to work with groups of object; it is at the top


of Collection hierarchy

Deque Extends Queue to handle double ended queue.

List Extends Collection to handle sequences list of object.

Queue Extends Collection to handle special kind of list in which


element are removed only from the head.

Set Extends Collection to handle sets, which must contain


unique element.

SortedSet Extends Set to handle sorted set.


K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
Concept of Generic Box
J2SE 5.0 provides compile-time type safety with the Java
Collections framework through generics

The concept of Generic box is a new paradigm in Generic


Programming which, allows us to specify what type of object we
would like to use, at the point of instantiating the class.

Generics allows you to specify, at compile-time, the types of objects


you want to store in a Collection. Then when you add and get items
from the list, the list already knows what types of objects are
supposed to be acted on.

So you don't need to cast anything. The "<>" characters are used
to designate what type is to be stored. If the wrong type of data
is provided, a compile-time exception is thrown.
K.S.SHASHIKALA,AP/CSE
// generic: no casting while accessing
// compile time errors instead of runtime errors
// All types are reduced to Object type at the end of compilation
public class Ex2
{
public static void main(String[] args)
{
Box<String> box = new Box<String>();
String s = "pes";
box.put(s); //assigns “pes” to box
String s1 = box. get(); // no casting
System.out.println(s1);
// Box<int> box1 = new Box<int>(); // NO primitive types
Box<Integer> box1 = new Box<Integer>();
box1.put(20);
int x = box1.get(); // OK; no casting required
System.out.println(x);
// String s2 = box1.get(); // Compile time error } }
K.S.SHASHIKALA,AP/CSE
// T is a place holder for some reference type
class Box<T> //< > brackets indicates that the class is of
generic type
{
private T o;
public void put(T o)

{
this. o = o;
}
public T get()
{
return this.o;
}
} K.S.SHASHIKALA,AP/CSE
PURPOSE OF USING GENERICS

• Using Generics, it has become possible to create a


single class, interface or method that automatically
works with all types of data(Integer, String, Float etc).

• It has expanded the ability to reuse the code safely and


easily.

• Before Generics was introduced, generalized classes,


interfaces or methods were created using references of
type Object, because Object is the super class of all
classes in Java.

• But this way of programming did not ensure type safety.


K.S.SHASHIKALA,AP/CSE
Syntax for creating an object of a generic type
class_name<data type> reference_name = new Class_name<data type> ();
or

class_name <data type> reference_name = new Class_name<>();

This is also known as Diamond Notation of creating an


object of Generic type.

K.S.SHASHIKALA,AP/CSE
Generic Class - Another Example
class Gen <T> //<> brackets indicates that the class is of generic type
{
T ob; // an instance of type T is declared
Gen(T o) //constructor
{
ob = o;
}
public T getOb()
{
return ob;
}}
class Test
{
public static void main (String[] args)
{
Gen < Integer> iob = new Gen<>(100); //instance of Integer type Gen Class.
int x = iob.getOb();
System.out.println(x);
Gen < String> sob = new Gen<>("Hello"); //instance of String type Gen Class.
String str = sob.getOb(); K.S.SHASHIKALA,AP/CSE
System.out.println(str);} } // 100 Hello
In the above program, we first passed an Integer type parameter to
the Generic class.

Then, we passed a String type parameter to the same Generic


class. Hence, we reused the same class for two different data
types. Thus, Generics helps in code reusability with ease.

K.S.SHASHIKALA,AP/CSE
ii) Generics Work Only with Objects

Generics work only with objects i.e the type


argument must be a class type.

We cannot use primitive datatypes such as int, char


etc. with Generics type. It should always be an
object.

We can use all the Wrapper Class objects and String


class objects as Generic type.

Gen<int> iOb = new Gen<int>(07); //Error


K.S.SHASHIKALA,AP/CSE
iii)Generics Types of different Type Arguments are never same
Reference of one generic type is never compatible with other generic
type unless their type argument is same.

In the example above we created two objects of class Gen, one of


type Integer, and other of type String, hence,
iob = sob; //Absolutely Wrong

iv)An array of Generic type cannot be created


Creation of a generic type array is not allowed in Generic
programming.
We can make a reference of an array, but we cannot instantiate it.
For example, In the above program, in class Gen,

T a[]; //this is allowed


T a[] = new T[10]; //this is not allowed
K.S.SHASHIKALA,AP/CSE
Generic Methods

You can also create generic methods that can be called with
different types of arguments.

Based on the type of arguments passed to generic method,


the compiler handles each method.

The syntax for a generic method includes a type-


parameter inside angle brackets, and should appear
before the method's return type.

<type-parameter> return_type method_name (parameters) {...}

K.S.SHASHIKALA,AP/CSE
Example of Generic method
class GenTest
{
static < V, T> void display (V v, T t)
{
System.out.println(v. getClass().getName()+" = " +v);
System.out.println(t.getClass().getName()+" = " +t);
}
public static void main(String[] args)
{
display(88,"This is string");
}
}

java lang.Integer = 88
java lang.String = This is string
K.S.SHASHIKALA,AP/CSE
Generic Constructors
It is possible to create a generic constructor even if the class is not generic.
Example of Generic Constructor
class Gen
{
private double val;
< T extends Number> Gen(T ob) // BOUNDED TYPE PARAMETER
{
val=ob.doubleValue();
}
void show()
{
System.out.println(val);
}
}
class Test
{
public static void main(String[] args)
{
Gen g = new Gen(100);
Gen g1 = new Gen(121.5f); K.S.SHASHIKALA,AP/CSE
g.show(); g1.show(); } } //100.0 121.5
Bounded type parameter in Generic types means
that we are restricting the type that can be used as
type arguments in a parameterized type.

For Example, a method that operates on numbers


only might want to accept instances of Number or its
subclasses.

To declare a bounded type parameter, list the type


parameters name ,followed by the extends keyword,
followed by its upper bound.

K.S.SHASHIKALA,AP/CSE
Generic Interface
Like classes and methods, you can also create generic interfaces.

interface MyInterface< T >


{ .. }

Generic Bounded type Parameter

You can also set restriction on the type that will be allowed to
pass to a type-parameter. This is done with the help of extends
keyword when specifying the type parameter.
< T extends Number >

Here we have taken Number class, it can be any wrapper class


name. This specifies that T can be only be replaced by Number
class data itself or any of its subclass.
K.S.SHASHIKALA,AP/CSE
Generic Method with bounded type parameters.
class Gen
{
static < T, V extends number> void display(T t, V v)
{
System.out.println(v.getClass().getName()+" = " +v);
System.out.println(t.getClass().getName()+" = " +t);
}
public static void main(String[] args)
{
display(88,90.5f);
//display (99, “this is string");
}
}
java.lang.String = This is string
java.lang.Double = 99.O
Type V is bounded to Number type and its subclass only.
If display(99, “this is string"); is uncommented, it will give an error of type
incompatibility, as String is not a subclass of Number class.
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
Java Input-Output Exercise

Write a Java program to find the longest word


in a given input text file.

Hint:Can use hasNext() and next() method of


the Scanner class.

K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
PROGRAM OUTPUT

K.S.SHASHIKALA,AP/CSE
Accessing a Collection
To access, modify or remove any element from any collection we
need to first find the element, for which we have to cycle through
the elements of the collection.

There are three possible ways to cycle through the elements of any
collection.

 Using Iterator interface


 Using for-each loop

K.S.SHASHIKALA,AP/CSE
Steps to use an Iterator
1.Obtain an iterator to the start of the collection by calling the
collection's iterator() method. Iterator object can be created
by calling iterator() method present in Collection interface.

Limitations of Iterator : Only forward direction iterating is


possible.

2.Set up a loop that makes a call to hasNext() method. Make


the loop iterate as long as hasNext() method returns true.

3.Within the loop, obtain each element by calling next()


method. K.S.SHASHIKALA,AP/CSE
Accessing elements using Iterator
Iterator Interface is used to traverse a list in forward direction,
enabling you to remove or modify the elements of the collection. Each
collection classes provide iterator() method to return an iterator.

Methods of Iterator:

1.boolean hasNext()
Returns true if there are more elements in the collection. Otherwise, returns false.

2.next()
Returns the next element present in the collection. Throws NoSuchElementException
if there is not a next element.

3.void remove()

Removes the current element. Throws IllegalStateException if an attempt is made


to call remove() method that is notK.S.SHASHIKALA,AP/CSE
preceded by a call to next() method.
//ACCESSING ELEMENTS USING ITERATOR FOR
ARRAYLIST CLASS
import java.util.*;
class Test_Iterator
{
public static void main(String[] args)
{
ArrayList< String> ar = new ArrayList< String>();
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
Iterator it = ar. iterator(); //Declaring Iterator
while(it.hasNext())
{
System.out.print(it.next()+" ");
}
} } K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
TYPE ERASURE
• The Java compiler uses a technique called type
erasure to translate generic classes into executable
code.
• Type erasure eliminates all generic type information at
compile time.
• All the type information between angle brackets is thrown
out so, for example, a parameterized type like List<String>
is converted into a List raw type.
• All remaining uses of type variables are replaced by the
upper bound of the type variable (or Object if there is no
type bound).
• Whenever the resulting code isn’t type-correct, a cast to the
appropriate type is automatically inserted.
K.S.SHASHIKALA,AP/CSE
JAVA GENERICS VS C++ TEMPLATES

• While Java generics syntactically look like C++ templates and are used to
achieve the same purpose, it is important to note that they are not
implemented using the same concepts, nor do they provide the same
programming features.

• Java generics simply provide compile-time type safety and eliminate the
need for explicit casts when using type-abstract types and algorithms.

• Java generics use a technique known as type erasure, and the compiler
keeps track of the generic definitions internally, hence using the same
class definition at compile/run time.

• A C++ template on the other hand use template metaprogramming, by


which whenever a template is instantiated with a new type parameter, the
entire code for the template is generated adapted to the type parameter and
then compiled, hence having several definitions for each template instance
at run time. K.S.SHASHIKALA,AP/CSE
Rules to define Generic Methods
You 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.

 All generic method declarations have a type parameter section delimited by


angle brackets (< and >) that precedes the method's return type. Each type
parameter section contains one or more type parameters separated by commas.

 A type parameter, also known as a type variable, is an identifier that specifies


a generic type name.

 The type parameters can be used to declare the return type and act as
placeholders for the types of the arguments passed to the generic method,
which are known as actual type arguments.

 A generic method's body is declared like that of any other method. Note that
type parameters can represent only reference types, not primitive types (like
int, double and char).
K.S.SHASHIKALA,AP/CSE
Example illustrates how we can print an array of
different type using a single Generic method

public class GenericMethodTest


{
// generic method printArray
public static < E > void printArray( E[] inputArray )
{
// Display array elements
for(E element : inputArray)
{
System.out.printf("%s ", element);
}
System.out.println();
}
K.S.SHASHIKALA,AP/CSE
public static void main(String args[])
{
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println("Array integerArray contains:");


printArray(intArray); // pass an Integer array
System.out.println("\nArray doubleArray contains:");
printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");


printArray(charArray); // pass a Character array
}
}
K.S.SHASHIKALA,AP/CSE
Collection Framework Methods
Some most important methods in the Collections framework are:

1.boolean add( E obj )


Used to add objects to a collection. Returns true if obj was added
to the collection.

Returns false if obj is already a member of the collection, or if


the collection does not allow duplicates.

2.boolean addAll( Collection C )

Add all elements of collection C to the invoking collection.


Returns true if the element were added. Otherwise, returns false.

K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
Let us briefly examine the two collections.

a) List
The list data structure supports dynamic size – we can add and
remove elements. It also provides methods to check whether the
element exists.

The List interface is implemented as an ArrayList or a


LinkedList.

b) Set
The Set data structure also supports dynamic size – we can add
and remove elements.
The set stores unique elements. It does not store the
duplicates. The set interface has three different implementations.
K.S.SHASHIKALA,AP/CSE
The List Interface

It extends the Collection Interface, and defines storage as sequence


of elements. Following is its general declaration,
interface List < E >
Allows random access and insertion, based on position.
It allows duplicate elements.
Apart from methods of Collection Interface, it adds following
methods of its own.

K.S.SHASHIKALA,AP/CSE
An example of usage of List Collection
Given a file containing a number of lines – each line containing
name of a city and a place of interest in the city, find the unique
names of cities. The city names do repeat. A city may have more
than one place of attraction.

We read a file using Scanner object, If the file has some more
input lines, we read two words each time in the loop. The first is
the city and the second in the place of interest in the city.

We create a list of String to hold the names of the city. Observe


that on the left of assignment we use an interface and on the
right of assignment, we create an object of the class
implementing that interface.

List<String> citylist = new ArrayList<String>();


K.S.SHASHIKALA,AP/CSE
How to add elements to the List?

The List interface provides a method called add.

We can add the city, which is a String to the citylist each time we
encounter a city.

But this will end up with duplicates. How to avoid this?

K.S.SHASHIKALA,AP/CSE
The List interface provides a search method called
indexOf similar to what Strings provide. If the element
is found, this method returns the position, else -1. So
we add the city only if the city is not already present in
the list.

if(citylist.indexOf(city) == -1)
citylist.add(city);

We used the enhanced for loop to walk through the


collection.
for(String s : citylist)
{
System.out.println(s);
} K.S.SHASHIKALA,AP/CSE
//EXAMPLE OF LIST IMPLEMENTATION
import java. util.*;
import java.io.*;
public class Ex1
{
public static void main(String[] args)
{
Scanner in = null;
List<String> citylist = new ArrayList<String>();
try
{
String city;
String place;
in = new Scanner(new File("places.txt"));
while(in.hasNext())
{
city = in.next();
place = in.next(); //System.out.println(city);
//System.out.println(place);
if(citylist.indexOf(city) == -1)
citylist.add(city);
K.S.SHASHIKALA,AP/CSE
} }
catch(Exception e)
{
System.out.println(e);
}
finally
{
if(in != null)
in.close();
}

for(String s : citylist)
{
System.out.println(s);
}
}
}
K.S.SHASHIKALA,AP/CSE
An example of usage of Set Collection:
The Set is an ideal data structure to remove the duplicates and
store the elements uniquely – we call this deduplication. The
reading of file is similar to the one in the earlier example.

We choose one of the implementations of the Set interface


and create a Set object.

Set<String> cityset = new TreeSet<String>();

We add elements uniquely by using the add interface of the Set


Collection.
cityset.add(city);

We use the enhanced for loop to walk through the collection.


for(String s : cityset)
{
System.out.println(s); } K.S.SHASHIKALA,AP/CSE
import java.util.*;
import java.io.*;
public class Ex2
{
public static void main(String[] args)
{
Scanner in = null;
Set<String> cityset = new TreeSet<String>();
try
{
String city;
String place;
in = new Scanner(new File("places.txt"));
while(in.hasNext())
{
city = in.next();
place = in.next();
//System.out.println(city);
//System.out.println(place);
cityset.add(city);
}
K.S.SHASHIKALA,AP/CSE
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
if(in != null)
in.close();
}
for(String s : cityset)
{
System.out.println(s);
}

}
}
K.S.SHASHIKALA,AP/CSE
Generic Collection Algorithms
(Sort & BinarySearch)
Sort:

Generics enables types to be parameters while defining


classes, interfaces and methods. Inputs to type
parameters are types.

By using generics programmers can implement generic


algorithms that work on collections of different
types, that can be customized, type safe and easier
to read.

K.S.SHASHIKALA,AP/CSE
In this example, we create a List of Strings. We sort them by using the generic
method of the Collections. This will arrange the strings in the lexicographic order.

Collections.sort(mylist);

We have seen earlier that Arrays.sort requires that we implement an interface


called Comparable – override the method compareTo in the component class of
the Array.

In case of Generic Collections, there is a Generic Interface called Comparator.

interface Comparator<T>
{
int compare(T x, T y);
}

Collections. sort is overridden to take an object implementing this interface. This


method compare will decide the order of elements in sorting.
K.S.SHASHIKALA,AP/CSE
Comparator interface

Comparator interface is used to order the objects of


user-defined class.

This interface is present in java.util package and


contains 2 methods compare(Object obj1, Object obj2)
and equals(Object element).

Using comparator, we can sort the elements based on


data members. For instance it may be on rollno, name,
age or anything else.

K.S.SHASHIKALA,AP/CSE
To sort a given list. ComparatorClass must implement
Comparator interface.

public void sort(List list, ComparatorClass c)

How does Collections.Sort() work?

Internally the Sort method does call Compare


method of the classes it is sorting. To compare two
elements, it asks “Which is greater?” Compare
method returns -1, 0 or 1 to say if it is less than,
equal, or greater to the other.
It uses this result to then determine if they should
be swapped for its sort.
K.S.SHASHIKALA,AP/CSE
import java.util.*; // Using generic sort method of the Collections.
public class Example1
{
public static void main(String[] args)
{
List<String> mylist = new ArrayList<String>();
String[] a = { "dhoni", "raina", "kohli", "yuvaraj", "rahane" };
for(String e : a)
{
mylist.add(e);
}
System.out.println(mylist);
Collections.sort(mylist);
System.out.println(mylist);
Collections. sort(mylist, new Comparator<String>()
{
public int compare(String lhs, String rhs)
{
return lhs. length() - rhs. length();
}
});
System.out.println(mylist); } } K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
Binary Search
Collections also provide an interface to do an efficient search on a
sorted collection. Think of the way we search in a dictionary for a
word like zebra. Definitely we would not start from the first page.

We start somewhere in the middle and based on the words in that


page, we discard the left or the right portion for further searching.

The Collections.binarySearch does the same thing. This works


only on sorted collections.

In this example, we sort a List. Then we search for an element which


exists. We get the position as an index – positive integer.

int res = Collections.binarySearch(mylist, "raina");

K.S.SHASHIKALA,AP/CSE
Then we search for an element which does not exist. We get a
negative integer value indicating the element is not found.

But the negation of the value indicates where it could have been
if found. Then we can insert that element if we want to.

res = Collections.binarySearch(mylist, "sehwag");


System.out.println("res : " + res);
mylist.add(-res-1, "sehwag");

The Generic method binarySearch can also take a


Comparator as the second argument. In that case, the
searching is based on that predicate.

The requirement is that the Generic Collection is sorted using


the same predicate.
K.S.SHASHIKALA,AP/CSE
import java.util.*;
public class MyListBinarySearch {
public static void main(String a[]){
List<Emp> empList = new ArrayList<Emp>();
empList.add(new Emp(12,"Dinesh",50000));
empList.add(new Emp(146,"Tom",20000));
empList.add(new Emp(201,"John",40000));
empList.add(new Emp(302,"Krish",44500));
empList.add(new Emp(543,"Abdul",10000));
Emp searchKey = new Emp(201,"John",40000);
int index = Collections.binarySearch(empList, searchKey, new EmpComp());
System.out.println("Index of the searched key: "+index);
}
}
class EmpComp implements Comparator<Emp>{
public int compare(Emp e1, Emp e2) {
if(e1.getEmpId() == e2.getEmpId()){
return 0;
} else {
return -1;
} } } K.S.SHASHIKALA,AP/CSE
class Emp {
private int empId;
private String empName;
private int empSal;

public Emp(int id, String name, int sal){


this.empId = id;
this.empName = name;
this.empSal = sal;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
K.S.SHASHIKALA,AP/CSE
}
public int getEmpSal() {
return empSal;
}
public void setEmpSal(int empSal) {
this.empSal = empSal;
}

public String toString(){


return empId+" : "+empName+" : "+empSal;
}
}

K.S.SHASHIKALA,AP/CSE
//ANOTHER BINARY SEARCH EXAMPLE
import java.util.*;
public class Example2
{
public static void main(String[] args)
{
List<String> mylist = new ArrayList<String>();
String[] a = { "dhoni", "raina", "kohli", "yuvaraj", "rahane" };

for(String e : a)
{
mylist.add(e);
}
Collections.sort(mylist);
System.out.println(mylist);
int res = Collections.binarySearch(mylist, "raina");
System.out.println("res : " + res);
res = Collections.binarySearch(mylist, "sehwag");
System.out.println("res : " + res);
mylist.add(-res-1, "sehwag");
System.out.println(mylist); K.S.SHASHIKALA,AP/CSE
System.out.println("-----------------------------");
// Sort based on the last character
Collections.sort(mylist, new Comparator<String>()
{
public int compare(String lhs, String rhs)
{
return lhs.charAt(lhs.length() -1) - rhs.charAt(rhs.length() -1);
}
});
System.out.println(mylist);

K.S.SHASHIKALA,AP/CSE
// do a binarySearch based on the last character.
// In this case, search for a name ending with i
// So, we may not find dhoni !

res = Collections.binarySearch(mylist, "dhoni",


new Comparator<String>()
{
public int compare(String lhs, String rhs)
{
return lhs. charAt(lhs.length() -1) - rhs.charAt(rhs.length() - 1);
}
});
System.out.println("res : " + res + ":" + mylist.get(res));
}
}

K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
intValue() method
The java.lang.Integer.intValue() is an inbuilt method in java
that returns the value of this integer as an int.

Syntax :
public int intValue()
Parameters: The method does not accept any parameters.

Return Value :
The method returns the numeric value which is represented by
the object after conversion to the integer type.

K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
Covariant return types

Java 5.0 onwards it is possible to have different return


type for a overriding method in child class, but child’s
return type should be sub-type of parent’s return type.
Overriding method becomes variant with respect to
return type.

Co-variant return type is based on Liskov substitution


principle.

Simple example to understand the co-variant return


type with method overriding.

K.S.SHASHIKALA,AP/CSE
class A {}
class B extends A {}
class Base Output:
{
A fun() Base fun()
{ Derived fun()
System.out.println("Base fun()");
return new A();
}
}
class Derived extends Base
{
B fun()
{
System.out.println("Derived fun()");
return new B();
}
}
public class Main
{ public static void main(String args[])
{
Base base = new Base();
base.fun();
Derived derived = new Derived();K.S.SHASHIKALA,AP/CSE
derived.fun(); } }
END OF UNIT-5

K.S.SHASHIKALA,AP/CSE

You might also like