JP Unit-Ii
JP Unit-Ii
UNIT-II 1
UNIT-II 2
Interfaces:
Interfaces are similar to classes, but they lack instance variables and their
methods are declared without any body.
Using interface, we can specify what a class must do, but not how it does it.
All methods and variables are implicitly public if the interface is declared
as public.
Example1: Interface
interface A
{
int i=10;
void firstMethod( );
}
UNIT-II 4
Implementing Interfaces:
UNIT-II 5
Example2: Implementing Interfaces
interface A class InterfaceDemo1
{ {
int i=10; public static void main(String args[ ])
void firstMethod(); {
} P p1=new P();
class P implements A p1.firstMethod();
{ }
public void firstMethod( ) }
{
System.out.println("This is firstMethod");
}
void display( )
{ O/P:
System.out.println("This is display");
} This is firstMethod
}
UNIT-II 6
Example3: Accessing Implementations Through Interface
References
UNIT-II 7
Extending Interfaces:
UNIT-II 8
Example4: Extending Interfaces
class Test implements InterTwo {
interface InterOne {
public void firstMethod( ) {
void firstMethod( );
System.out.println("firstMethod");
void secondMethod( );
}
}
public void secondMethod( ) {
System.out.println("secondMethod");
interface InterTwo extends InterOne {
}
void thirdMethod( );
public void thirdMethod( ) {
void fourthMethod( );
System.out.println("thirdMethod");
}
}
public void fourthMethod( ) {
System.out.println("fourthMethod");
class InterfaceDemo2 { }
public static void main(String args[ ]) { void display( ) {
Test t1=new Test( ); System.out.println("This is display");
t1.firstMethod( ); }
t1.secondMethod( ); }
t1.thirdMethod( );
t1.fourthMethod( );
}
} UNIT-II 9
Java file:
A Java source file can contain any (or) all of the following four internal parts:
UNIT-II 10
Packages:
Packages are containers for classes.
UNIT-II 11
Creating a Package:
The .class files for any classes to be part of a package must be stored in a
directory with the same name of the package.
The directory name must match the package name.
UNIT-II 13
Example: Create a package
Create a package with three classes Arithmetic, Bitwise and Logical.
Arithmetic class containing methods to perform arithmetic operations.
Similarly Bitwise and Logical classes.
Let the two classes Arithmetic and Bitwise be public and Logical be without
any access specifier.
Declare some of the methods of Arithmetic class to public and other to
private.
Declare some methods of Bitwise class to protected and other without
access specifier.
Declare the methods of Logical class each with one access specifier.
Now write two java applications using the methods of classes in the
above package.
One program outside the package and the other in the same package.
UNIT-II 14
Arithmetic class:
package pack1;
public class Arithmetic {
public int add(int a,int b) {
return a+b;
}
public int sub(int a,int b) {
return a-b;
}
public int mul(int a,int b) {
return a*b;
}
private int div(int a,int b) {
return a/b;
}
private int mod(int a,int b) {
return a%b;
}
}
UNIT-II 15
Bitwise class:
package pack1;
public class Bitwise {
protected int and(int a,int b) {
return a&b;
}
protected int or(int a,int b) {
return a|b;
}
protected int not(int a) {
return ~a;
}
int xor(int a,int b) {
return a^b;
}
int rightShift(int a,int b) {
return a>>b;
}
}
UNIT-II 16
Logical class:
package pack1;
class Logical {
public boolean shortAnd(boolean x, boolean y) {
return x&&y;
}
private boolean shortOr(boolean x, boolean y) {
return x||y;
}
protected boolean not(boolean x) {
return !x;
}
boolean xor(boolean x, boolean y) {
return x^y;
}
}
UNIT-II 17
Hierarchy of packages:
package pkg1[.pkg2[.pkg3]];
UNIT-II 18
static import:
Enable to refer to imported static members as if they were declared in the class
that uses them.
UNIT-II 19
Forms of Inheritance:
UNIT-II 20
Forms of Inheritance:
Inheritance for Specialization: The child is special case of the parent class.
Inheritance for Specification: The parent class defines behavior that is
implemented in the child class but not in the parent class.
Inheritance for Construction: The child class makes use of the behavior
provided by the parent class but is not a subtype of the parent class.
Inheritance for Extension: The child class adds new functionality to the
parent class, but does not change any inherited behavior.
Inheritance for Limitation: The child class restricts the use of some of the
behavior inherited from the parent class.
Inheritance for Combination: The child class inherits features from more
than one parent class.
UNIT-II 21
Benefits of Inheritance:
UNIT-II 22
Costs of Inheritance:
Although the benefits of inheritance are great, almost nothing is without
cost of one sort or another.
Some of the costs of inheritance are:
Execution Speed
Program Size
Message-Passing Overhead
Program Complexity
UNIT-II 23
UNIT-II 24
The Java I/O Classes and Interfaces:
UNIT-II 25
The Java I/O Classes and Interfaces:
UNIT-II 26
File:
The File class does not specify how information is retrieved from or
stored in files; it describes the properties of a file itself.
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
UNIT-II 27
Some methods in File class:
UNIT-II 28
File: Program 01
import java.io.*;
class File01
{
public static void main(String[] args)
{
File f1 = new File("d1.txt");
System.out.println("File Name: " + f1.getName( ));
System.out.println("Path: " + f1.getPath( ));
System.out.println("Abs Path: " + f1.getAbsolutePath( ));
System.out.println("Length: " + f1.length( ));
System.out.println("IsFile: " + f1.isFile( ));
System.out.println("Exists: " + f1.exists( ));
}
} Output:
File Name: d1.txt
Path: d1.txt
Abs Path: D:\GDR\Java 2021-22\Programs\IO\d1.txt
Length: 106
IsFile: true
UNIT-II 29
Exists: true
File: Program 02
import java.io.*;
class File02
{ Output:
public static void main(String[ ] args)
File Name: Programs
{
Path: D:\Java\Programs
File f1 = new File("D:/Java/Programs"); IsDir: true
System.out.println("File Name: " + f1.getName( )); Files in the Directory
System.out.println("Path: " + f1.getPath( )); AbstractClass.java
System.out.println("IsDir: " + f1.isDirectory( )); AbstractClass2.java
String s[ ]=f1.list(); AbstractClass3.java
System.out.println("Files in the Directory"); AdapterDemo.java
for(int i=0;i<s.length;i++) AdapterKeyDemo.java
System.out.println(s[i]); AdapterMouseDemo.java
Arith.java
}
Arithmetic.java
} Arithmetic1.java
Banner.java
Bitwise.java
UNIT-II 30
The Java I/O Streams:
In Java, input and output is defined in terms of an abstract concept
called "stream".
byte streams
character streams
UNIT-II 31
Byte streams and Character streams:
InputStream
OutputStream
Reader
Writer
UNIT-II 32
The Java I/O Classes and Interfaces:
UNIT-II 33
InputStream class:
UNIT-II 34
OutputStream class:
UNIT-II 35
Reader class:
UNIT-II 36
Writer class:
UNIT-II 37
InputStream class:
UNIT-II 38
Methods of InputStream class:
int available( )
void close( )
void mark(int readlimit)
boolean markSupported( )
abstract int read( )
int read(byte[ ] b)
int read(byte[ ] b, int off, int len)
void reset( )
long skip(long n)
UNIT-II 39
Class FileInputStream:
Constructors:
FileInputStream(File file)
FileInputStream(String name)
Some methods:
int available( )
void close( )
protected void finalize( )
int read( )
int read(byte[ ] b)
int read(byte[ ] b, int off, int len)
long skip(long n)
UNIT-II 40
FileInputStream: Example program
import java.io.*;
class FileInputStreamDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream f1=new FileInputStream("abc.txt");
int a=f1.available();
System.out.println("Total Available bytes:"+a);
for(int i=1;i<=10;i++)
System.out.print(" "+f1.read());
a=f1.available();
System.out.println("\nTotal Available bytes:"+a);
f1.close();
FileInputStream f2=new FileInputStream("abc.txt");
byte b[]=new byte[20]; Output:
int x=f2.read(b,3,8); Total Available bytes:52
System.out.println("Byte array:"); 65 66 67 68 69 70 71 72 73 74
for(int i=0;i<20;i++) Total Available bytes:42
System.out.print(" "+b[i]); Byte array:
f2.close(); 0 0 0 65 66 67 68 69 70 71 72 0 0 0 0 0 0 0 0 0
}
UNIT-II 41
}
Class ByteArrayInputStream:
A ByteArrayInputStream contains an internal buffer(byte array) that
contains bytes that may be read from the stream.
Constructors:
ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)
Some methods:
int available( )
void close( )
void mark(int readAheadLimit)
boolean markSupported( )
int read( )
int read(byte[ ] b, int off, int len)
void reset( )
long skip(long n)
UNIT-II 42
ByteArrayInputStream: Example Program
import java.io.*;
class ByteArrayInputStreamDemo
{
public static void main(String args[ ]) throws IOException
{
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[ ] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0,3);
int c;
while ((c = input1.read( )) != -1)
{
System.out.print((char) c); Output:
} abcdefghijklmnopqrstuvwxyz
while ((c = input2.read( )) != -1) abc
{
System.out.print((char) c);
}
}
UNIT-II 43
}
Filtered Byte Streams:
This class is the superclass of all classes that filter input streams.
UNIT-II 44
BufferedInputStream:
The data is read by blocks into a buffer; subsequent reads can access
the data directly from the buffer.
Constructors:
BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)
UNIT-II 45
BufferedInputStream: Example Program
import java.io.*;
class BufferedInputStreamDemo
{
public static void main(String args[]) throws IOException
{
String s = "THIS ON BUFFEREDINPUTSTREAM CLASS";
byte buf[ ] = s.getBytes( );
ByteArrayInputStream in = new ByteArrayInputStream(buf);
BufferedInputStream f = new BufferedInputStream(in);
boolean m=f.markSupported( );
System.out.println("Mark:"+m);
}
}
UNIT-II 46
PushbackInputStream:
This class is an input stream filter that provides a buffer into which data
can be "unread."
An application may unread data at any time by pushing it back into the buffer.
Constructors:
PushbackInputStream(InputStream inputStream)
PushbackInputStream(InputStream inputStream, int numBytes)
PushbackInputStream provides
UNIT-II 47
PushbackInputStream: Example Program
import java.io.*;
class PushbackDemo
{
public static void main(String args[]) throws IOException
{
byte b[ ]={65,66,67,68,69,70,71,72,73,74,75,76,77,78};
ByteArrayInputStream bs1=new ByteArrayInputStream(b);
PushbackInputStream p1=new PushbackInputStream(bs1);
System.out.println("Total Available bytes in p1:"+p1.available( ));
int ch=p1.read( );
System.out.println((char)ch);
ch=p1.read( );
System.out.println((char)ch);
p1.unread(ch);
ch=p1.read( );
System.out.println((char)ch);
p1.close( );
}
} UNIT-II 48
SequenceInputStream:
Constructors:
SequenceInputStream(InputStream first, InputStream second)
SequenceInputStream(Enumeration streamEnum)
UNIT-II 49
SequenceInputStream: Example Program
import java.io.*;
class SequenceStreamsDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream f2=new FileInputStream(“xyz.txt");
byte buf[ ]={65,66,67,68,69,70,71,72,73,74,75,76,77,78};
ByteArrayInputStream bs2=new ByteArrayInputStream(buf);
SequenceInputStream s1=new SequenceInputStream(f2,bs2);
System.out.println("Total Available bytes in s1:"+s1.available( ));
for(int i=1;i<=20;i++)
System.out.print((char)s1.read( ));
} Output:
}
Total Available bytes in s1:15
JavaProgrammingABCDE
UNIT-II 50
OutputStream class:
UNIT-II 51
Methods of OutputStream class:
void close( )
void flush( )
void write(byte[ ] b)
void write(byte[ ] b, int off, int len)
abstract void write(int b).
UNIT-II 52
FileOutputStream:
Constructors:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
UNIT-II 53
FileOutputStream: Example program
import java.io.*;
class FileOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
FileOutputStream f1=new FileOutputStream("Sample.java");
byte b[ ]={65,66,67,68,69,70,71,72,73,74,75,76,77,78};
f1.write(65);
f1.write(b);
f1.close();
FileOutputStream f2=new FileOutputStream("Sample.java",true);
f2.write(65);
f2.write(b);
f2.close();
}
}
UNIT-II 54
ByteArrayOutputStream:
ByteArrayOutputStream is an implementation of an output stream
that uses a byte array as the destination.
Constructors:
ByteArrayOutputStream( )
ByteArrayOutputStream(int numBytes)
In the first form, a buffer of 32 bytes is created.
UNIT-II 55
ByteArrayOutputStream: Example program
import java.io.*;
class ByteArrayOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
ByteArrayOutputStream bs1 = new ByteArrayOutputStream( );
String s = "This should end up in the array";
byte buf[ ] = s.getBytes( );
bs1.write(buf);
System.out.println("Buffer as a string");
System.out.println(bs1.toString( ));
bs1.close( );
}
}
UNIT-II 56
BufferedOutputStream:
The data is written into a buffer, and then written to the underlying stream
if the buffer reaches its capacity, the buffer output stream is closed,
or the buffer output stream is explicity flushed.
Constructors:
BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int bufSize)
UNIT-II 57
PrintStream:
Constructors:
PrintStream(OutputStream outputStream)
PrintStream(OutputStream outputStream, boolean flushOnNewline)
If an argument is not a simple type, the PrintStream methods will call the
object’s toString( ) method and then print the result.
UNIT-II 58
Reader class:
UNIT-II 59
Reader class:
UNIT-II 60
Writer class:
UNIT-II 61
Writer class:
UNIT-II 62
Serialization:
Serialization is the process of saving an object in a storage medium
(such as a file, or a memory buffer) or to transmit it over a network connection
in binary form.
In this case the "in memory" java objects state are converted into a
byte stream.
UNIT-II 63
Serialization:
Some of the classes and interfaces related to serialization.
Interfaces:
Serializable
ObjectOutput (extends DataOutput)
DataOutput
ObjectInput (extends DataInput)
DataInput
Classes:
ObjectOutputStream(extends OutputStream implements ObjectOutput)
ObjectInputStream (extends InputStream implements ObjectInput)
UNIT-II 64
ObjectInputStream:
ObjectOutputStream:
UNIT-II 65
Serialization: Example Program
import java.io.*;
class SerializationDemo{
public static void main(String args[]) throws IOException {
Sample s1=new Sample( );
System.out.println(""+s1);
s1.a=10; s1.b=20; s1.c=30; s1.d=40;
FileOutputStream f1=new FileOutputStream(“abc.txt");
ObjectOutputStream o1=new ObjectOutputStream(f1);
o1.writeObject(s1);
o1.flush( );
o1.close( );