0% found this document useful (0 votes)
38 views46 pages

Java II Unit 2020

Uploaded by

sudharani.am
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
38 views46 pages

Java II Unit 2020

Uploaded by

sudharani.am
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 46

II UNIT

Inheritance
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).
Types of inheritance:

1
1. Single Inheritance : In single inheritance, subclasses inherit the features of
one superclass. In image below, the class A serves as a base class for the
derived class B.

// A simple example of inheritance.


// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.

2
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();

3
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
The output from this program is shown here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24

2.Multilevel Inheritance : In Multilevel Inheritance, a derived class will be


inheriting a base class and as well as the derived class also act as the base
class to other class. In below image, the class A serves as a base class for the
derived class B, which in turn serves as a base class for the derived class C. In
Java, a class cannot directly access the grandparent’s members.

Program for MultiLevel Inheritance:


class Animal

4
{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
classTestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();

}}
Output:
weeping...
barking...
eating...

3. Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as


a superclass (base class) for more than one sub class.In below image, the class
A serves as a base class for the derived class B,C and D.

5
Program for Hierarchical Inheritance:

class A
{
private void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}

Output:

6
method of Class A
method of Class A
method of Class A

4. MultipleInheritance (Through Interfaces) : I


To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
n Multiple inheritance ,one class can have more than one superclass and
inherit features from all parent classes. Please note that Java does not support
multiple inheritance with classes. In java, we can achieve multiple inheritance
only through Interfaces. In image below, Class C is derived from interface A
and B.

Program for MultipleInheritance Inheritance:


Consider a scenario where A, B and C are three classes. The C class inherits A
and B classes. If A and B classes have same method and you call it from child
class object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile
time error if you inherit 2 classes. So whether you have same method or
different, there will be compile time error now.

class A{
void msg(){System.out.println("Hello");}

7
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

output:
Compile by: javac C.java
java:7: error: '{' expected
class C extends A,B{//suppose if it were
^
1 error

5. Hybrid Inheritance(Through Interfaces) : It is a mix of two or more of the


above types of inheritance. Since java doesn’t support multiple inheritance with
classes, the hybrid inheritance is also not possible with classes. In java, we can
achieve hybrid inheritance only through Interfaces.

8
Program for Hybrid Inheritance:

public class A
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class B extends A
{
public void show()
{
System.out.println("show() method of ClassB");
}
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class C extends A
{
public void show()
{
System.out.println("show() method of ClassC");
}
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class D extends B,C
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
public static void main(String args[])
{
ClassD d = new ClassD();
d.dispD();
d.show();//Confusion happens here which show method to call

9
}}

Output :
Error!!

Member Access and Inheritance


Access modifiers are simply a keyword in Java that provides accessibility of a
class and its member. They set the access level to methods, variable, classes
and constructors.

Types of access modifier


There are 4 types of access modifiers available in Java.

 public
 default
 protected
 private

public
The member with public modifiers can be accessed by any classes. The public
methods, variables or class have the widest scope.

default

When we do not mention any access modifier, it is treated as default. It is


accessible only within same package.

protected

The protected modifier is used within same package. It lies between public and
default access modifier. It can be accessed outside the package but through
inheritance only.
A class cannot be protected.

private

The private methods, variables and constructor are not accessible to any other
class. It is the most restrictive access modifier. A class except a nested class
cannot be private.
Methods declared public in a superclass also must be public in all subclasses.

10
Methods declared protected in a superclass must either be protected or public
in subclasses; they cannot be private.
Methods declared private are not inherited at all, so there is no rule for them.
Private Example:

/* In a class hierarchy, private members remain


private to their class.
This program contains an error and will not
compile.
*/
// Create a superclass.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
This program will not compile because the reference to j inside the sum( )
method of B
causes an access violation. Since j is declared as private, it is only accessible
by other members
of its own class. Subclasses have no access to it.
Protected Example:

Addition.java

11
package abcpackage;
public class Addition {

protected int addTwoNumbers(int a, int b){


return a+b;
}
}

Test.java

package xyzpackage;
import abcpackage.*;
class Test extends Addition{
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.addTwoNumbers(11, 22));
}
}

Output:

33

The scope of access modifiers in tabular form

private No modifier protected public

same class yes yes yes yes

same package subclass No yes yes yes

same package non- No yes yes yes


subclass

Different package No No yes yes


subclass

12
Different package non- No No No yes
subclass

Forms of Inheritance

The choices between inheritance and overriding, subclass and subtypes, mean
that inheritance can be used in a variety of different ways and for different
purposes. Many of these types of inheritance are given their own special
names. We will describe some of these specialized forms of inheritance.

 Specialization
 Specification
 Construction
 Generalization or Extension
 Limitation
 Combination

Specialization Inheritance
By far the most common form of inheritance is for specialization.
A good example is the Java hierarchy of Graphical components in the AWT:

 Component
o Label
o Button
o TextComponent
 TextArea
 TextField
o CheckBox
o ScrollBar

Each child class overrides a method inherited from the parent in order to
specialize the class in some way.

Specification Inheritance

If the parent class is abstract, we often say that it is providing a specification


for the child class, and therefore it is specification inheritance (a variety of
specialization inheritance).
Example: Java Event Listeners

13
ActionListener, MouseListener, and so on specify behaviour, but must be
subclassed.

Inheritance for Construction

If the parent class is used as a source for behavior, but the child class has no
is-a relationship to the parent, then we say the child class is using inheritance
for construction.
An example might be subclassing the idea of a Set from an existing List class.
Generally not a good idea, since it can break the principle of substituability,
but nevertheless sometimes found in practice. (More often in dynamically typed
languages, such as Smalltalk).

Inheritance for Generalization or Extension

If a child class generalizes or extends the parent class by providing more


functionality, but does not override any method, we call it inheritance for
generalization.
The child class doesn't change anything inherited from the parent, it simply
adds new features.
An example is Java Properties inheriting form Hashtable.

Inheritance for Limitation

If a child class overrides a method inherited from the parent in a way that
makes it unusable (for example, issues an error message), then we call it
inheritance for limitation.
For example, you have an existing List data type that allows items to be
inserted at either end, and you override methods allowing insertion at one end
in order to create a Stack.
Generally not a good idea, since it breaks the idea of substitution. But again, it
is sometimes found in practice.

combination

This types of inheritance is known as multiple inheritance in Object Oriented


Programming.
Although the Java does not permit a subclass to be formed be inheritance from
more than one parent class, several approximations to the concept are
possible.
Example of this type is Hole class defined as;
class Hole extends Ball implements PinBallTarget{
// body of class
14
}

Two or more classes that seem to be related, but its not clear who should be
the parent and who should be the child.
Example: Mouse and TouchPad and JoyStick
Better solution, abstract out common parts to new parent class, and use
subclassing for specialization.

Benefits of Inheritance

 Software Reusability (among projects)


 Increased Reliability (resulting from reuse and sharing of well-tested code)
 Code Sharing (within a project)
 Consistency of Interface (among related objects)
 Software Components
 Rapid Prototyping (quickly assemble from pre-existing components)
 Polymorphism and Frameworks (high-level reusable components)
 Information Hiding

Cost of Inheritance

 Execution speed
 Program size
 Message Passing Overhead
Program Complexity (in overuse of inheritance)

This does not mean you should not use inheritance, but rather than you must
understand the benefits, and weigh the benefits against the costs.

polymorphism
Adhoc polymorphism
Adhoc polymorphism refers to polymorphic functions that can be applied to
different argument types known by the same name in a programming
language. Adhoc polymorphism is also known as function overloading or
operator overloading because a polymorphic function can represent a number
of unique and potentially heterogeneous implementations depending on the
type of argument it is applied to.
Adhoc polymorphism defines operators that can be used for different argument
types. It follows a dispatch mechanism in which the control moving from one
named function is dispatched to several other functions without specifying the
function being called. This function overloading permits multiple functions

15
taking different argument types to be known by the same name as the compiler
and interpreter calls the right function.

For example in the following code:

int a, b;

float x, y;
String s1=”hello”;
String s2=”world”;

System.out.println(“sum of two varariables a+b and x+y:”, a+b, x+y);


System.out.println(“s1 is concatenated to s2”+(s1+s2));

The symbol ‘+’ is used in two different ways. In the expression a+b, it stands for
the function that adds two integers. In the expression x+y, it stands for the
function that adds two floats. In the concatenation of two strings, we are using
‘+’ .
Thus, ad hoc polymorphism refers to the use of a single function name to
indicate two or more unique functions. The compiler decides which function to
call depending on the type of arguments.

Ad hoc polymorphism is supported by almost all programming languages for


built-in operations such as ‘+’, ‘-‘, ‘*’, etc.

Pure polymorphism:
Pure Polymorphism is a single function can be applied to arguments of a variety of types.

Polymorphism is derived from 2 greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many
forms.

There are two types of polymorphism in java: compile time polymorphism and
runtime polymorphism.

We can perform polymorphism in java by method overloading and method


overriding.

1. Method Overloading in Java – This is an example of compile time (or static


polymorphism)
2. Method Overriding in Java – This is an example of runtime time (or
dynamic polymorphism)

Runtime Polymorphism in Java


16
Runtime polymorphism or Dynamic Method Dispatch is a process in which
a call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable


of a superclass. The determination of the method to be called is based on the
object being referred to by the reference variable.

Method overriding: This allows us to have more than one method having the same
name, if the parameters of methods are same in number, sequence and data types of
parameters.

Example1:

class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splender();//upcasting
b.run();
}
}

Output: running safely with 60km.

Example2:

class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{

17
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}

Output:

drawing rectangle...
drawing circle...
drawing triangle...

Compile time Polymorphism

Method Overloading on the other hand is a compile time polymorphism


example.
Polymorphism that is resolved during compiler time is known as static
polymorphism. Method overloading is an example of compile time
polymorphism.
Method Overloading: This allows us to have more than one method having the
same name, if the parameters of methods are different in number, sequence
and data types of parameters.
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}

18
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}

Output:

a: 10
a and b: 10,20
double a: 5.5

O/P : 30.25

Packages in Java

 Packages in Java are a way of grouping similar types of classes /


interfaces together. It is a great way to achieve reusability.
 We can simply import a class providing the required functionality from
an existing package and use it in our program. A package basically acts
as a container for group of related classes.
 The concept of package can be considered as means to achieve data
encapsulation.

Packages are categorized as:


1 ) Built-in packages ( standard packages which come as a part of Java
Runtime Environment )
2 ) User-defined packages ( packages defined by programmers to bundle
group of related classes )

Built-in Packages:
These packages consists of a large number of classes which are a part of Java
API.
For e.g: we have used java.io package previously which contain classes to
support input / output operations in Java. Similarly, there are other packages
which provides different functionality.

19
Some of the commonly used built-in packages are shown in the table below :

Package
Description
Name
Contains language support classes ( fore.g classes which defines
java.lang primitive data types, math operations, etc.) . This package is
automatically imported.
java.io Contains classes for supporting input / output operations.
Contains utility classes which implement data structures like
java.util Linked List, Hash Table, Dictionary, etc and support for Date /
Time operations.
java.applet Contains classes for creating Applets.
Contains classes for implementing the components of graphical
java.awt
user interface ( like buttons, menus, etc. ).
java.net Contains classes for supporting networking operations.

Accessing classes in a Built-in package in to a program :


1 ) import java.util.Vector; // import the Vector class from util package
or
2 ) import java.util.*; // import all the class from util package

 First statement imports Vector class from util package which is


contained inside java package.
 Second statement imports all the classes from util package.

User-defined packages:

 Creating a Package:

While creating a package, you should choose a name for the package and
include a package statement along with that name at the top of every
source file that contains the classes, interfaces, enumerations, and
annotation types that you want to include in the package.

forExample: packageMypack;

The package statement should be the first line in the source file. There can be
only one package statement in each source file, and it applies to all types in the
file.

To compile the Java programs with package statements, you have to use -d
option as shown below.

20
javac -d Destination_folder file_name.java

How to run java package program:

You need to use fully qualified name e.g. mypack.Simpleetc to run the class.

Compile:javac -d .file_name.java

Run:java mypack.file_name

 Importing Packages

The general form of the import statement:

importpkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).
There is no practical limit on the depth of a package hierarchy, except that
imposed by the file system.

either an explicit classname or a star (*), which indicates that the Java
compiler should import the entire package.

ForExample:

This code fragment shows both forms in use:

import java.util.Scanner;
import java.io.*;

 The basic language functions are stored in a package inside of the java
package called java.lang. (Default Package)
 This is equivalent to the following line being at the top of all of your
programs:
 Import java.lang.*;

There are three ways to access the package from outside the package.

 import package.*;
 import package.classname;
 fully qualified name.

 Using packagename  Using


packagename.classname

21
//save by A.java
If you import package.classname
package pack; then only declared class of this
public class A{ package will be accessible.
public void msg() //save by A.java
{System.out.println("Hello");} package pack;
}
public class A
//save by B.java {
public void msg()
package mypack; {System.out.println("Hello");} }
import pack.*;
//save by B.java
class B{
public static void main(String package mypack;
args[]){ import pack.A;
A obj = new A();
obj.msg(); class B{
} } public static void main(String a
rgs[]){
A obj = new A();
Complile: javac –d . obj.msg();
B.java //(Because MainMethod }
occurs at B.java) }

Run: java
pack.B //(Because Output:Hello
MainMethod occurs at B.java)

Output:Hello

Interfaces
Defining an Interface

 An interface is a reference type in Java. It is similar to class. It is a


collection of abstract methods.
 A class implements an interface, thereby inheriting the abstract
methods of the interface.
 The interface in Java is a mechanism to achieve abstraction.
 There can be only abstract methods in the Java interface, not method
body.

22
 Along with abstract methods, an interface may also contain constants,
default methods, static methods, and nested types.
 Method bodies exist only for default methods and static methods.

Syntax:
access_specifier interface name {
return-type method-name (parameter-list); //Abstract Method
type final-varname1 = value;
type final-varname2 = value; //variables
default method-name (parameter-list)
{ //default method body; }

staticmethod-name (parameter-list)
{ //method body }

}
In other words, Interface fields are public, static and final by default, and the
methods are public and abstract.

Implementing Interfaces

 Once an interface has been defined, one or more classes can inherit that
interface by using implements Keyword

 To implement an interface, include the implements Keyword in a class


definition, and then create the methods defined by the interface.

 The methods that implement an interface in a class must be declared with


public accessSpecifier.

Syntax:

classclassname[extends superclass] [implements interface[,interface...]]


{
// class-body
}

If a class implements more than one interface, the interfaces are separated
with a comma.

As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.

23
Nested Interfaces

 An interface can be declared a member of a class or another interface. Such


an interface is called a member interface or a nested interface.
 A nested interface can be declared as public, private, or protected. This
differs from a top-level interface, which must either be declared as public or
use the default access level, as previously described.
 When a nested interface is used outside of its enclosing scope, it must be
qualified by the name of the class or interface of which it is a member.
Thus, outside of the class or interface in which a nested interface is
declared, its name must be fully qualified

Here is an example that demonstrates a nested interface:

// A nested interface example.


// This class contains a member interface.

class A {
// this is a nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF { //nested interface Declaration
public boolean isNotNegative(int x)
{
return x < 0 ? false : true;
}

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

24
A.NestedIF nif = new B(); // use a nested interface
reference
if(nif.isNotNegative(10))
{
System.out.println("10 is not negative");
}
if(nif.isNotNegative(-12))
{
System.out.println("this won't be displayed");
}
}
}
Note:
Notice that A defines a member interface called NestedIF and that it is
declared public. Next, B implements the nested interface by specifying
implements A.NestedIF
Notice that the name is fully qualified by the enclosing class name. Inside the
main( ) method, an A.NestedIF reference called nif is created, and it is
assigned a reference to a B object. Because B implements A.NestedIF, this is
legal.

Applying Interfaces
 used to achieve abstraction.
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. g
etDrawable()
d.draw();
}}

Output:
drawing circle

25
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple


interfaces, it is known as multiple inheritance.

interface Printable
{
void print();
}

interface Showable
{
void show();
}

class A implements Printable,Showable


{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");}
}

class A7
{
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}

26
}

Output:Hello Welcome

Interface inheritance

A class implements an interface, but one interface extends another interface.

interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

Output:
Hello
Welcome

Default Method in Interface

interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}

27
Output:
drawing rectangle
default method

Static Method in Interface

interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}

Output:
drawing rectangle
27
Difference between abstract class and interface

Abstract class Interface


Interface can have only abstract
1) Abstract class can have abstract and
methods. Since Java 8, it can have
non-abstract methods.
default and static methods also.
2) Abstract class doesn't support Interface supports multiple
multiple inheritance. inheritance.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
4) Abstract class can provide the Interface can't provide the
implementation of interface. implementation of abstract class.
5) The abstract keyword is used to The interface keyword is used to
declare abstract class. declare interface.
6) An abstract class can extend another
An interface can extend another
Java class and implement multiple Java
Java interface only.
interfaces.
7) An abstract class can be extended An interface class can be
using keyword ?extends?. implemented using keyword ?

28
implements?.
8) A Java abstract class can have class Members of a Java interface are
members like private, protected, etc. public by default.
9)Example:
public abstract class Shape{
public abstract void draw(); Example:
public void display() public interface Drawable{
{ void draw();
System.out.println(“display method”); }
}
}

Stream based I/O (exploring java.io)

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

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

We can perform file handling in Java by Java I/O API.

Streams

Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means
continuous flow of data. Streams are clean way to deal with input/output without
having every part of your code understand the physical.

In Java, 3 streams are created for us automatically. All these streams are
attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream

While File Handling These Streams are processed as two types


They are

 inputStream- The InputStream is used to read data from a source.


 outputStream -The OutputStream is used for writing data to a destination.

Java defines two types of streams:

1. ByteStreams

29
2. CharacterStreams

Java File Class


Java File class represents the files and directory pathnames in an abstract
manner. This class is used for creation of files and directories, file searching,
file deletion, etc.

Constructor Description
File(File parent, String It creates a new File instance from a parent abstract
child) pathname and a child pathname string.
It creates a new File instance by converting the given
File(String pathname)
pathname string into an abstract pathname.
File(String parent, It creates a new File instance from a parent pathname
String child) string and a child pathname string.
It creates a new File instance by converting the given file:
File(URI uri)
URI into an abstract pathname.

Syntax(Constructors):

File(String directoryPath) //directoryPathis the path name of the file

File(String directoryPath, String filename) //filename is the name of the file or


subdirectory

File(File dirObj, String filename) //dirObjis a File object that specifies a


directory

File(URI uriObj) //uriObjis a URI object that describes a file.

For example:

30
File f1 = new File("/");
File f2 = new File("/","abc.txt");
File f3 = new File(f1,"abc.txt");

File defines many methods that obtain the standard properties of a File object.

 getName( ) returns the name of the file,


 getParent( ) returns the name of the parent directory
 exists( ) returns true if the file exists, false if it does not.
 renameTo( )is used for rename the fileshown here:

boolean renameTo(File newName)

the filename specified by newname becomes the new name of the


invoking File object.

 delete( ) useto delete a directory if the directory is empty. delete( )


returns true if it deletes the file and false if the file cannot be removed.

Some more methods is shown by program as below:

// Demonstrate File.
import java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);
}
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT");
p("File Name: " + f1.getName());
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");
p(f1.canWrite() ? "is writeable" : "is not writeable");
p(f1.canRead() ? "is readable" : "is not readable");
p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
p(f1.isFile() ? "is normal file" : "might be a named pipe");
p(f1.isAbsolute() ? "is absolute" : "is not absolute");
p("File last modified: " + f1.lastModified());
p("File size: " + f1.length() + " Bytes");
}
}
Output:

31
File Name: COPYRIGHT
Path: /java/COPYRIGHT
Abs Path: /java/COPYRIGHT
Parent: /java
exists
is writeable
is readable
is not a directory
is normal file
is absolute
File last modified: 812465204000
File size: 695 Bytes

Reading data from File Writting data from File


import java.io.*; import java.io.*;
importjava.util.*; importjava.util.*;
public class fileinput { public class fileinput {
public static void public static void
main(String[] args) main(String[] args)
throws throws
FileNotFoundException,IOExcep FileNotFoundException,IOExcep
tion tion
{ {
File file = new File file = new
File("abc.txt"); File("abc.txt");
BufferedReader br = new FileWriter fw=new
BufferedReader(new FileWriter(file,true);
FileReader(file));
BufferedWriter bw = new
String st; BufferedWriter(fw);
while ((st = br.readLine()) !=
null) String st="Object Oriented
System.out.println(st); Programing ";
} bw.write(st);
bw.close();
} }}

Byte Streams:
 A Byte stream will read a file Byte by Byte.

 Byte stream is defined by using two abstract class at the top of hierarchy,
they are InputStream and OutputStream.

32
 Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.

 These two abstract classes have several concrete classes that handle
various devices such as disk files, network connection etc.

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

ByteArrayInputStream Input stream that reads from a byte array

Output stream that writes to a byte array


ByteArrayOutputStream

Contains method for reading java standard


DataInputStream
datatype

An output stream that contain method for writing


DataOutputStream
java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

ObjectInputStream Input stream for objects

ObjectOutputStream Output stream for objects

OutputStream Abstract class that describe stream output.

Output Stream that contain print() and println()


PrintStream
method

RandomAccessFile Supports random access file I/O

These classes define several key methods. The most important are

33
1. read() : reads byte of data.
2. write() : Writes byte of data.
3. close(): to close allConnections.

FileInputStream Class

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc. You can also
read character-stream data.

Syntax:

FileInputStream(String filepath)
FileInputStream(File fileObj)

Either can throw a FileNotFoundException.


Here, filepathis the full path name of a file, and fileObjis a File object that describes
the file.

forExample:
FileInputStream f0 = new FileInputStream("abc.txt")
or
File f = new File("abc.txt");
FileInputStream f1 = new FileInputStream(f);

read single character


import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);

fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Output: W
read all characters:

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;

34
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output: Welcome to java

FileOutputStream Class:

Java FileOutputStream is an output stream used for writing data to a file.


If you have to write primitive values into a file, use FileOutputStream class. You can
write byte-oriented as well as character-oriented data through FileOutputStream
class.
Syntax:

FileOutputStream(String filePath)
FileOutputStream(File fileObj)

They can throw a FileNotFoundException. Here, filePathis the full path name of a
file, and fileObj is a File object that describes the file. If append is true, the file is
opened in append mode.

Creation of a FileOutputStreamis not dependent on the file already existing.


FileOutputStream will create the file before opening it for output when you create the
object. In the case where you attempt to open a read-only file, an IOException will be
thrown.

write byte:

public class writebyte {


public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){
System.out.println(e);
}
}
}

write string into a file with present data

import java.io.FileOutputStream;

35
public class writestring {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to JAVA.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

Copying From one File to another by using FileInputSream and


FileOutputStream classes:

import java.io.*;
public class CopyFile{

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


FileInputStream in=null;
FileOutputStream out=null;

try{
in=new FileInputStream("input.txt");
out=new FileOutputStream("output.txt");

int c;
while((c =in.read())!=-1){
out.write(c);
}
}finally{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}
}
}
BufferedInputStream class BufferedOutputStream class
Java BufferedInputStream class is used Java BufferedOutputStream class is
to read information from stream. It used for buffering an output stream. It
internally uses buffer mechanism to internally uses buffer to store data. It
make the performance fast. adds more efficiency than to write data

36
directly into a stream. So, it makes the
performance fast.
Syntax: Syntax:

BufferedInputStream(InputStream BufferedOutputStream(OutputStream
inputStream) outputStream)
or or
BufferedInputStream(InputStream BufferedOutputStream(OutputStream
inputStream, int bufSize) outputStream, intbufSize)

import java.io.*; import java.io.*;


public class public class
BufferedInputStreamExample{ BufferedOutputStreamExample{
public static void main(String args[]){ public static void main(String
try{ args[])throws Exception{
FileInputStream fin=new FileOutputStreamfout=new
FileInputStream("D:\\testout.txt"); FileOutputStream("D:\\testout.txt");

BufferedInputStream bin=new BufferedOutputStream bout=new


BufferedInputStream(fin); BufferedOutputStream(fout);
inti; String s="Welcome to JAVA.";
while((i=bin.read())!=-1){ byte b[]=s.getBytes();
System.out.print((char)i); bout.write(b);
} bout.close();
bin.close(); fout.close();
fin.close(); System.out.println("success");
}catch(Exception e) }
{System.out.println(e);} }
}
} Output:
Success
Here, we are assuming that you have
following data in "testout.txt" file: testout.txt
Java programing
Output: Welcome to java.
Java programing

Character Stream Classes


A character stream will read a file character by character. Character Stream is a
higher level concept than Byte Stream .

Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for 16-

37
bit unicode. Though there are many classes related to character streams but
the most frequently used classes are, FileReader and FileWriter.

Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.

Reader
Reader is an abstract class that defines Java’s model of streaming character input. It
implements the Closeable and Readable interfaces. All of the methods in this class
(except for markSupported( )) will throw an IOException on error conditions.

Writer
Writer is an abstract class that defines streaming character output. It implements the
Closeable, Flushable, and Appendable interfaces. All of the methods in this class
throw an IOException in the case of errors.

These two abstract classes have several concrete classes that handle unicode

character.

Some important Character stream classes.


Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

Input stream that reads from a character array


CharArrayReader

CharArrayWriter Output stream that writes to a character array

FileReader Input stream that reads from file.

38
FileWriter Output stream that writes to file.

FilterReader
Filtered reader

FilterWriter Filtered writer

InputStreamReader Input stream that translate byte to character

LineNumberReader Input stream that counts lines

OutputStreamReader Output stream that translate character to byte.

Output Stream that contain print() and println()


PrintWriter
method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class. It is character-oriented class which is used for file handling
in java.

Syntax:

FileReader(String filePath)
FileReader(File fileObj)

Either can throw a FileNotFoundException. Here, filePathis the full path name of a
file, and fileObjis a File object that describes the file.

import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}

Here, we are assuming that you have following data in "testout.txt" file:

Welcome to JAVA.

39
Output:

Welcome to JAVA.

FileWriter Class

Java FileWriter class is used to write character-oriented data to a file. It is character-


oriented class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array
because it provides method to write string directly.

Syntax:

Its most commonly used constructors are shown here:


FileWriter(String filePath)
FileWriter(String filePath, booleanappend)
FileWriter(File fileObj)
FileWriter(File fileObj, booleanappend)

import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to JAVA.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Output: Success...
testout.txt: Welcome to JAVA.

Copying From one File to another by using FileReader and FileWriter classes:

import java.io.*;
public class CopyFile{

public static void main(Stringargs[]) throws IOException{


FileReader in=null;
FileWriter out=null;

try{
in=new FileReader("input.txt");
out=new FileWriter("output.txt");

40
int c;
while((c =in.read())!=-1){
out.write(c);
}
}finally{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}
}
}

Now let's have a file input.txt with the following content −

This is test for copy file.

BufferedReader Class BufferedWriter Class


Java BufferedReader class is used to Java BufferedWriter class is used to
read the text from a character-based provide buffering for Writer instances. It
input stream. It can be used to read data makes the performance fast. It inherits
line by line by readLine() method. It Writer class. The buffering characters
makes the performance fast. It inherits are used for providing the efficient
Readerclass. writing of single arrays, characters, and
strings.
It has two constructors:
ABufferedWriterhas these two
BufferedReader(Reader inputStream) constructors:
BufferedReader(Reader inputStream,
intbufSize) BufferedWriter(Writer outputStream)
BufferedWriter(Writer outputStream,
The first form creates a buffered intbufSize)
character stream using a default buffer
size. In the second, the size of the buffer The first form creates a buffered stream
is passed in bufSize. using a buffer with a default size. In the
second, the size of the buffer is passed in
bufSize.

import java.io.*; import java.io.*;


public class BufferedReaderExample { public class BufferedWriterExample {
public static void main(String public static void main(String[] args)
args[])throws Exception{ throws Exception {
FileReaderfr=new FileReader("D:\\ FileWriter writer = new FileWriter("D:\\
testout.txt"); testout.txt");

41
BufferedReaderbr=new BufferedWriter buffer = new
BufferedReader(fr); BufferedWriter(writer);
buffer.write("Welcome to JAVA.");
inti; buffer.close();
while((i=br.read())!=-1){ System.out.println("Success");
System.out.print((char)i); }
} }
br.close();
fr.close();
}
}
Output: Output:
Welcome to JAVA. success

Reading console Input and Writing Console Output:

In Java, there are three different ways for reading input from the user in the command
line environment(console).

1. Using Scanner Class


2. Using Buffered Reader Class
3. Using Console Class

Using Scanner Class

This is probably the most preferred method to take input. The main purpose of the Scanner class is to
parse primitive types and strings using regular expressions, however it is also can be used to read input
from the user in the command line.

// Java program to demonstrate working of Scanner in Java

I mport java.util.Scanner;

class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);

String s = in.nextLine();
System.out.println("You entered string "+s);

int a = in.nextInt();
System.out.println("You entered integer "+a);

42
float b = in.nextFloat();
System.out.println("You entered float "+b);
}
}

Using Buffered Reader Class

In Java, console input is accomplished by reading from System.in. To obtain a


character based stream that is attached to the console, wrap System.in in a
BufferedReader object.

BufferedReader supports a buffered input stream. Its most commonly used


constructor is shown here:
BufferedReader(Reader inputReader)

Here, inputReader is the stream that is linked to the instance of BufferedReader that
is being created.
Reader is an abstract class. One of its concrete subclasses is InputStreamReader,
which converts bytes to characters.
To obtain an InputStreamReader object that is linked to System.in, use the following
constructor:

InputStreamReader(InputStreaminputStream)

Because System.in refers to an object of type InputStream, it can be used for


inputStream.

Putting it all together, the following line of code creates a BufferedReaderthat is


connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

BufferedReader to read a charecter BufferedReader read all strings


To read a character from a To read a string from the keyboard, use
BufferedReader, use read( ). The version the version of readLine( ) that is a
of read( ) that we will be using is member of the BufferedReaderclass. Its
general form is shown here:
int read( ) throws IOException String readLine( ) throws IOException

read() method is used with As you can see, it returns a String


BufferedReader object to read object.
characters. As this function returns
integer type value has we need to use The following program demonstrates
typecasting to convert it into char type. BufferedReaderand the readLine( )
method;

the program reads and displays lines of

43
text until you enter the word “stop”:

// Use a BufferedReader to read // Read a string from console using a


characters from the console. BufferedReader.
import java.io.*; import java.io.*;
class BRRead { class BRReadLines {
public static void main(String args[]) public static void main(String args[])
throws IOException throws IOException
{ {
char c; // create a BufferedReader using
BufferedReader br = new System.in
BufferedReader(new BufferedReader br = new
InputStreamReader(System.in)); BufferedReader(new
System.out.println("Enter characters, 'q' InputStreamReader(System.in));
to quit."); String str;
// read characters System.out.println("Enter lines of text.");
do { System.out.println("Enter 'stop' to quit.");
c = (char) br.read(); do {
System.out.println(c); str = br.readLine();
} while(c != 'q'); } while(!str.equals("stop"));
} }
} }

Here is a sample run:

Enter characters, 'q' to quit.


123abcq
1
2
3
a
b
c
q
..

Using Console Class

 Java SE 6 adds the Console class. It is used to read from and write to
the console, if one exists.
 Console is primarily a convenience class because most of its
functionality is available through System.in and System.out.

Syntax:

44
Console supplies no constructors. Instead, a Console object is obtained by
calling System.console( ), which is shown here:

static Console console( )

If a console is available, then a reference to it is returned. Otherwise, null is


returned. A console will not be available in all cases. Thus, if null is returned,
no console I/O is possible

Here is an example that demonstrates the Console class:


// Demonstrate Console.
import java.io.*;
class ConsoleDemo {
public static void main(String args[]) {
String str;
Console con = System.console();// Obtain a reference to the console.

str = con.readLine("Enter a string: ");// Read a string and then display it.

System.out.println(str);
}
}

Here is sample output:


Enter a string: This is a test.
Here is your string: This is a test.

RandomAccessFile
 RandomAccessFile encapsulates a random-access file. It is not derived
from InputStream or OutputStream.
 Instead, it implements the interfaces DataInput and DataOutput, which
define the basic I/O methods. It also implements the Closeable interface.
 RandomAccessFile is special because it supports positioning requests—
that is, you can position the file pointer within the file.
Syntax:
It has these two constructors:
RandomAccessFile(File fileObj, String access)
throws FileNotFoundException
or
RandomAccessFile(String filename, String access)
hrows FileNotFoundException
 herefileObjspecifies the name of the file to open as a File object.
 In the second form, the name of the file is passed in filename.
45
 In both cases, access determines what type of file access is permitted.
File Access parameter as:
 If it is “r”, then the file can be read, but not written.
 If it is “rw”, then the file is opened in read-write mode.

 If it is “rws”, the file is opened for read-write operations and every


change to the file’s data or metadata will be immediately written to the
physical device.
 If it is “rwd”, the file is opened for read-write operations and every change
to the file’s data will be immediately written to the physical device.

 The method seek( ), shown here, is used to set the current position of the
file pointer within the file:

void seek(long newPos) throws IOException

 It also includes some additional methods. One is setLength( ). It has this


signature:

void setLength(long len) throws IOException

RandomAccessFile read example RandomAccessFile write example


import java.io.*; import java.io.*;
public class Randomacsess { public class Randomrw {
public static void main(String public static void main(String
args[])throws Exception args[])throws Exception
{ {
RandomAccessFile raf = new RandomAccessFile raf = new
RandomAccessFile("input.txt", "r"); RandomAccessFile("inputrw.txt",
"rw");
raf.seek(1); raf.seek(5);
raf.write(data.getBytes());
byte[] bytes = new byte[50]; raf.close();
raf.read(bytes);
raf.close(); }
System.out.println(new String(bytes)); }

}
}

46

You might also like