Unit 5 Java Students
Unit 5 Java Students
K.S.SHASHIKALA,AP/CSE
SYLLABUS
Concept of Serialization.
K.S.SHASHIKALA,AP/CSE
Different types of inner classes in java
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.
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;
Local Inner Classes are the inner classes that are defined
inside a block. Generally, this block is a method body.
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";
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.
static
{
System.out.println(2);
}
}
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
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 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.
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:
K.S.SHASHIKALA,AP/CSE
Four types of streams
There are 4 different types of streams available.
They are:
• Byte streams
• Character streams
• Scanner Object
K.S.SHASHIKALA,AP/CSE
1.byte streams:
These streams are typically used to read and write binary data
such as images and sounds.
K.S.SHASHIKALA,AP/CSE
DIFFERENCES BETWEEN PRINTWRITER AND
FILEWRITER
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.
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.
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.
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.
Class declaration
Let's see the declaration for Java.io.PrintStream class:
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.
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.
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.
K.S.SHASHIKALA,AP/CSE
K.S.SHASHIKALA,AP/CSE
writeUTF method:
Declaration
Parameters
str − a string to be written to the output stream.
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.
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.*;
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.
In the next example, we will store the objects into a file and bring them
back later.
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.
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;
out.writeObject(s1);
// out.flush();
System.out.println("success");
// deserialization
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.
Prior to the JDK 5.0 release, when you created a Collection, you
could put any object in it.
K.S.SHASHIKALA,AP/CSE
Collection Framework
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
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.
K.S.SHASHIKALA,AP/CSE
ii) Generics Work Only with Objects
You can also create generic methods that can be called with
different types of arguments.
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.
K.S.SHASHIKALA,AP/CSE
Generic Interface
Like classes and methods, you can also create generic interfaces.
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 >
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.
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.
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()
• 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.
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
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.
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
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 can add the city, which is a String to the citylist each time we
encounter a city.
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);
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.
}
}
K.S.SHASHIKALA,AP/CSE
Generic Collection Algorithms
(Sort & BinarySearch)
Sort:
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);
interface Comparator<T>
{
int compare(T x, T y);
}
K.S.SHASHIKALA,AP/CSE
To sort a given list. ComparatorClass must implement
Comparator interface.
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.
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 !
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
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