Unit 2 Java Notes
Unit 2 Java Notes
1
UNIT-2
1. Inherirance Concept
Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new
class is known as subclass. The subclass inherits all of its instances variables and methods defined by the
superclass and it also adds its own unique elements. Thus we can say that subclass are specialized version of
superclass.
1. Reusability of code
2. Code Sharing
3. Consistency in using an interface
1. Inherirance Basics
Defination:The process by which one class acquires the properties(data members) and functionalities
(methods) of another class is called inheritance.
The aim of inheritance is to provide the reusability of code so that a class has to write only the unique
features and rest of the common properties and functionalities can be extended from the another class.
Child Class:
The class that extends the features of another class is known as child class, sub class or derived class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another class is known as parent class,
super class or Base class.
• Inheritance is a process of defining a new class based on an existing class by extending its common
data members and methods.
• Inheritance allows us to reuse of code, it improves reusability in your java application.
Note: The biggest advantage of Inheritance is that the code that is already present in base class
2
need not be rewritten in the child class.This means that the data members(instance variables) and
methods of the parent class can be used in the child class as.
To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent
class. The class XYZ is inheriting the properties and methods of ABC class.
Types of inheritance
1. Single Inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple Inheritance
1.Single Inheritance: refers to a child and parent class relationship where a class extends the another class.
2.Multilevel inheritance: refers to a child and parent class relationship where a class extends the child
class. For example class C extends class B and class B extends class A.
3
3.Hierarchical inheritance: refers to a child and parent class relationship where more than one classes extends
the same class. For example, classes B, C & D extends the same class A.
4.Multiple Inheritance: refers to the concept of one class extending more than one classes, which means a
child class has two parent classes. For example class C extends both classes A and B. Java doesn’t support
multiple inheritance.
5.Hybrid inheritance: Combination of more than one types of inheritance in a single program. For example
class A & B extends class C and another class D extends class A then this is a hybrid inheritance example
because it is a combination of single and hierarchical inheritance.
4
1. Member Access
An instance variable of a class will be declared private to prevent its unauthorized use or tampering.
Inheriting a class does not overrule the private access restriction. Thus, even though a subclass includes all
of the members of its superclass, it cannot access those members of the superclass that have been
declared private. For example, if, as shown here, width and height are made private in TwoDShape,
then Triangle will not be able to access them:
5
The Triangle class will not compile because the reference to width and height inside the area( ) method
causes an access violation. ...
6
1. Creating Multilevel Hierarchy
It is nothing but the enhancement of the Simple Inheritance. From the type name, it is pretty much clear that
Inheritance is done at ‘n’ number of levels, where n>1.
In simple inheritance, a subclass or derived class derives the properties from its parent class, but in
multilevel inheritance, a subclass is derived from a derived class. One class inherits the only single class.
Therefore, in multilevel inheritance, every time ladder increases by one. The lowermost class will have the
properties of all the superclass.
7
class A{
public A()
{
System.out.println("class A constructor");
}
public void hai()
{
System.out.println("hai method");
}
}
class B extends A{
public B()
{
System.out.println("class B constructor ");
}
public void hello()
{
System.out.println("hello method");
}
public void welcome()
{
System.out.println("class B welcome");
}
}
public class C extends B
{
public C()
{
System.out.println("class C constructor");
}
public void welcome()
{
System.out.println("class C welcome");
}
public static void main(String args[])
Output: {
C obj=new C();
obj.hai();
class A constructor obj.hello();
obj.welcome();
class B constructor }
}
class C constructor
hai method
hello method
8
class C welcome
Note: Multilevel inheritance is not multiple inheritances where one class can inherit more than one class at a
time. Java does not support multiple inheritances.
1. Super Uses
The super keyword in java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable
We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.
The super keyword can also be used to invoke parent class method. It should be used if subclass contains the
same method as parent class. In other words, it is used if method is overridden.
Example program to demonstrating invoking of parent class instance variable and parent class method
9
class Base
{
String color="white";
void display()
{
System.out.println("have a nice day");
}
}
Class Sub extends Base
{
String color="black";
void display()
{
System.out.println("Hello CMREC...");
}
void printColor()
{
System.out.println(color);//prints color of sub class
System.out.println(super.color);//prints color of Base class
}
void work()
{
display();
super.display();
}
}
class TestSuper2
{
public static void main(String args[])
{
Sub ob=new Sub();
ob. printColor();
ob.work();
}
}
Output
black
10
white
Hello CMREC…
The super keyword can also be used to invoke the parent class constructor.
class Parentclass
{
Parentclass()
{
System.out.println("Constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass()
{
//Compile implicitly adds super() here as the first statement of this
constructor.
System.out.println("Constructor of child class");
}
Subclass(int num)
{
// Even though it is a parameterized constructor The compiler still adds the super() here
System.out.println("arg constructor of child class");
}
void display()
{
System.out.println("Hello!");
}
public static void main(String args[])
{
Subclass obj= new Subclass();
//Calling sub class method
obj.display();
Subclass obj2= new Subclass(10);
obj2.display();
}
}
11
Output:
Constructor of parent class
Constructor of child class
Hello!
Constructor of parent class
arg constructor of child class
Hello!
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
• variable
• method
• class
class Honda1 extends Bike //error since Bike is final we can’t inherit it properties
{
void run()
{
System.out.println("running safely with 100kmph");
}
12
1. Polymorphism-ad hoc polymorphism
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
If you overload a static method in Java, it is the example of compile time polyymorphism.
13
1. Compile-time polymorphism or Ad hoc polymorphism:
The term ad hoc in this context is not intended to be pejorative; it refers simply to the fact that this type of
polymorphism is not a fundamental feature of the type system.
i)operator overloading:
Java also provide option to overload operators. For example, we can make the operator (‘+’) for string class
to concatenate two strings. We know that this is the addition operator whose task is to add two operands. So
a single operator ‘+’ when placed between integer operands, adds them and when placed between string
operands, concatenates them.
class Operatoroverloading {
class Main {
public static void main(String[] args)
{
Operatoroverloading obj = new Operatoroverloading ();
obj.operator(2, 3);
obj.operator("CMR", "EC");
}
}
14
Output:
Sum = 5
ii)Method Overloading:
When there are multiple functions with same name but different parameters then these functions are said to
be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of
arguments. Overloaded methods are generally used when they conceptually execute the same task but with a
slightly different set of parameters.
For example:
class A{}
A a=new B();//upcasting .
In this example, we are creating two classes A and B. B class extends A class and overrides its
display ()method. We are calling the display ()by the reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent class method, the subclass method is invoked at
runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
class A
{
void display ()
{
System.out.println(" A class display ");
}
}
class B extends A
{
void display ()
{
System.out.println(" B class display ");
}
public static void main(String args[])
{
A obj = new B();//upcasting
obj. display ();
}
}
16
Output:
B class display
Advantages of dynamic binding along with polymorphism with method overriding are.
1 When a class have same method name with Method overriding - Method of superclass is
different argument, than it is called method overridden in subclass to provide more specific
overloading. implementation.
2 Method overloading is generally done in Method overriding is always done in subClass in java.
same class but can also be done in
SubClass .
3 Both Static and instance method can be Only instance methods can be overridden in java.
overloaded in java. Static methods can’t be overridden in java.
4 Main method can also be overloaded in Main method can’t be overridden in java, because
java main is static method and static methods can’t be
overridden in java (as mentioned in above point)
5 private methods can be overloaded in java. private methods can’t be overridden in java, because
private methods are not inherited in subClass in java.
6 final methods can be overloaded in java. final methods can’t be overridden in java, because
final methods are not inherited in subClass in java.
8 Method overloading concept is also known Method overriding concept is also known as runtime
as compile time polymorphism or ad hoc time polymorphism or pure polymorphism or
polymorphism or static binding in java. Dynamic binding in java.
17
1. Method Overriding
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.variable of the current object.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting
1. Abstract Classes
• A class that is declared with abstract keyword, is known as abstract class in java.
• It can have abstract and non-abstract methods (method with body).
• It needs to be extended and its method implemented.
18
• It cannot be instantiated.
abstract class A
Abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
19
Output:hello
1.
Object Class
The Object class is the parent class of all the classes in java by default.
Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an
object of any other class.
The parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned from this method
20
Methods of Object class
Method Description
public final Class getClass() returns the Class class object of this object. The Class
class can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws causes the current thread to wait for the specified
InterruptedException milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. So we cannot override this
methods and rest of the methods can be overridden.
21
1. Forms of Inheritance-Specialization
Forms of Inheritance :
All objects eventually inherit from Object, which provides useful methods such as equals and toString.
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).
Specialization inheritance:
The superclass just specifies which methods should be available but doesn't give code.
Construction inheritance
The superclass just specifies which methods should be available but doesn't give code.
Extension inheritance
The superclass is just used to provide behavior, but instances of the subclass don't really act like the
superclass. Violates substitutability. Exmample: defining Stack as a subclass of Vector. This is not clean --
better to define Stack as having a field that holds a vector
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. subclass adds new methods, and perhaps redefines
inherited ones as well
22
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. the subclass restricts the inherited behavior. Violates substitutability. Example: defining Queue as a
subclass of Dequeue.
Combination
The child class inherits features from more than one parent class. This is multiple inheritance .
Specialization. The child class is a special case of the parent class; in other words, the child class is a
subtype of the parent class.
Specification. The parent class defines behavior that is implemented in the child class but not in the parent
class.
Construction. The child class makes use of the behavior provided by the parent class, but is not a subtype
of the parent class.
Generalization. The child class modifies or overrides some of the methods of the parent class.
Extension. The child class adds new functionality to the parent class, but does not change any inherited
behavior.
Limitation. The child class restricts the use of some of the behavior inherited from the parent class.
Variance. The child class and parent class are variants of each other, and the class-subclass relationship is
arbitrary.
Combination. The child class inherits features from more than one parent class. This is multiple inheritance
.
23
1. Benefits of Inheritance
• Software Reuse
• Code Sharing
• Improved Reliability
• Consistency of Interface
• Rapid Prototyping
• Polymorphism
• Information Hiding
1. Cost of Inheritance
➢ Execution speed
➢ Program size
➢ Message Passing Overhead
➢ Program Complexity
This does not mean you should not use inheritance, but rather than you must understand the benefits, and
weigh the benefits against the costs.
24
2.1 Packages
Built-in package:
Collection of classes & interfaces which are already defined are called as Build-in
packages. There are many built-in packages such as java, lang, awt, javax, swing,
user-defined packages:
25
2.1.2 Defining a user-defined package
“package” Syntax:
package packagename[.subpackage1][.subpackage2]…[.subpackageN];
//save as Simple.java
package mypack;
System.out.println("Welcome to package");
If you are not using any IDE, you need to follow the syntax given below:
Syntax:
For example
26
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows)
etc. If you want to keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
CLASS PATH environment variable setting is used by java run time system to know
where to look for package that is created.
package MyPack
27
It must simply specify the path to MyPack. For example, in a Windows environment,
if the path to MyPack is
C:\MyPrograms\Java\MyPack
Then the class path to
MyPack is
C:\MyPrograms\Java
Example:
package
MyPack; class
Demo
{
…….
…….
}
class classpathdemo
{
public static void main(String args[])
{
Demo obj=new Demo();
………
}
Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory.
Then, try executing the classpathdemo class, using the following command line:
java MyPack.classpathdemo
Remember, you will need to be in the directory above MyPack when you execute this
command.
28
2.1.4 Importing packages
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
1) Using packagename.*
• If you use package.* then all the classes and interfaces of this package will
be accessible but not subpackages.
• The import keyword is used to make the classes and interface of another
package accessible to the current package.
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
28
Compile as: D:/pack>javac –d . A.java
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
Output:Hello
2) Using packagename.classname
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully qualified name
• If you use fully qualified name then only declared class of this package will
be accessible. Now there is no need to import. But you need to use fully
qualified name every time when you are accessing the class or interface.
• It is generally used when two packages have same class name e.g. java.util
and java.sql packages contain Date class.
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully
qualified name
obj.msg();
}
}
Output:Hello
If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages. Hence, you need
to import the subpackage as well.
Implicit imports give access to all visible types in the type (or package) that
precedes the ".*"; types imported in this way never shadow other types.
Explicit imports give access to just the named type; they can shadow other types
that would normally be visible through an implicit import, or through the normal
package visibility rules.
Example
The following example uses implicit imports. This means that it is not clear to a
programmer where the List type on line 5 is imported from.
10
2.1.5 Access protection or Access Modifiers
There are two types of modifiers in java: access modifier and non-access modifier. The access
modifiers specifies accessibility (scope) of a datamember, method, constructor or class.
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc.
In this example, we have created two classes ‘A’ and ‘Simple’. ‘A’ class contains private data member and
private method. We are accessing these private members from outside the class, so there is compile time
error.
class A
{
private int
data=40; private
void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile
1 Time
1
Error obj.msg();//Compile Time Error
}
Role of Private Constructor:
If you make any class constructor private, you cannot create the instance of that class from outside the
class. For example:
class A
{
private A( )
{
}//private constructor
void msg( )
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A( );//Compile Time Error
}
}
In this example, We are accessing the A class from outside its package, since A class is not public, so it
cannot be accessed from outside the package.
1
2
//save by A.java
package pack;
class A
{
void msg( )
{
System.out.println("Hello");
}
}
//save by B.java
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
1
3
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages “pack” and “ mypack”. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package is declared
as protected, so it can be accessed from outside the class only through inheritance.
package pack;
public class A
protected
{ void System.out.println("Hello");
msg()
}
}
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output:Hello
1
4
4) public access modifier:
The public access modifier is accessible
everywhere. It has the widest scope among all
other modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
1
5
Output:Hello
2.2 INTERFACES
(or)
(or)
An interface in java is a blueprint of a class. It has static final constants and abstract methods.
They are mainly three reasons to use interface. They are given below.
1
6
2.2.2 Defining an Interface
Syntax:
public interface NameOfInterface
In other words, Interface fields are public, static }and final by default, and methods are public and abstract.
As shown in the figure given below, a class extends another class, an interface extends another interface but a
class implements an interface
1
7
Example on class implementing interface
interface MyInterface
{
public void method();
}
class Demo implements MyInterface
{
public void method()
{
System.out.println("Implementation of method");
}
public static void main(String arg[])
{
1
8
Multiple inheritance is not supported through class in java but it is possible by interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class
because of ambiguity. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class.
For example:
interface Printable
{
void print();
}
interface Showable
{
void show();
}
Output:
Hello
Welcome
1
9
Difference between abstract class and interface
• Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods.
But there are many differences between abstract class and interface that are given below.
2
0
2.2.4 Nested Interfaces
• An interface which is 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 by 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.
interface interface_name
...
...
2
1
-Example of nested interface which is declared within the interface
interface Outerinterface
void show();
void show()
Test obj=new
Test();
obj.show();
obj.message();
}
2
2
}
Output:
...
interface nested_interface_name
...
}
class A
{
public interface innerinterface
{
public void message();
}
}
class NestedTest implements A.innerinterface
{
public void message()
{
System.out.println("implementation of nestedinterface message method");
}
public static void main(String args[])
{
NestedTest obj=new NestedITest();
obj.message();
}
}
2
3
Output:
Example2:
If class have any members and methods ,then to access this members and methods
• First extend the class and implement the interfaces
So that you will have access to members and methods of class also.
class A
{
void show()
{
System.out.println("Hello");
}
public interface innerinterface
{
public void message();
}
}
class NestedTest extends A implements A.innerinterface
{
public void message()
{
System.out.println("implementation of nestedinterface message method");
}
public static void main(String args[])
{
NestedTest obj=new NestedTest();
obj.show();
obj.message();
}
}
Output:
Hello
If we define a class inside the interface, java compiler creates a static nested class. Let's see how can we
define a class within the interface:
interface interface_name
{
class class_name
{
…..
}
}
interface MyInterface
{
public void method();
}
class Demo implements MyInterface
{
public void method()
{
System.out.println("Implementation of method");
}
public static void main(String arg[])
{
Demo obj=new Demo();
obj. method();
}
}
2
5
2.2.6 Variables in Interface
• An interface can also contain variables just as classes but the variable in interface must be of
• Public,static and final access modifiers.
• If the variable are not specified with access specifier then during compilation process compiler will
provide this access specifier.
interface interface_name
….
}
Example for declaring a variable in interface:
interface hai
{
public static final min=5;
}
class demo impliments hai
{
public static void main(string args[])
{
demo obj=new demo();
System.out.println (“minimum value
is”); System.out.println (obj.min);
}
}
2
6
2.2.7 Extension of Interface
Interface inheritance
Output:
Hello
Welcome
2
7
2.3 STREAM BASED INPUT/OUTPUT
OutputStream: Java application uses an output stream to write data to a destination, it may be a file,an
array, peripheral device or socket.
InputStream:Java application uses an input stream to read data from a source, it may be a
file,an array,peripheral device or socket.
2
8
2.3.1 Stream Class
• Java’s Stream based input/output is built upon 4 abstract classes
1. InputStream
2. OutputStream
3. Reader
4. Writer
Byte stream classes have been designed to provide functional features for creating and manipulating
streams and files for reading and writing Bytes.
1. InputStream class
2. OutputStream class
1. InputStream Class:
➢ Reading Bytes
➢ Closing streams
➢ Marking positions in streams
➢ Skipping ahead in stream
➢ Finding the number of Bytes in a streams
2
9
Below table gives the methods provided by InputStream class
Method Description
int read() Reads a byte form the input stream.and return -1
when end of the file is encountered
int read(byte buffer[ ]) Reads an array of bytes into buffer and return - 1
when end of the file is encountered
int read(byte buffer[ ],int offset , int numbytes) Reads numbytes bytes into buffer starting from
offset.
return -1 when end of the file is encountered
2. OutputStream class:
➢ Writing bytes
➢ Closing streams
➢ Flushing streams
3
0
Below table gives the methods provided by OutputStream class
Method Description
void write(int b) Write a byte to the output stream
void write(byte buffer[]) Write all bytes in the buffer array to the output
stream
write(byte buffer[ ],int offset , int numbytes) Writes numbtes from buffer starting from
offset
void close() Close the output stram
void flush() Flushes the output stream
• The character stream can be used to read and write Unicode characters.
• There are two kinds of character stream classes,namely
1.Reader
2.Writer
Method Description
abstract void close() Closes the input source
int read() Reads the character from the invoking input stream .
return -1 when end of the file is encountered
int read(char buffer[ ]) Reads an array of character into buffer and return -1
when end of the file is encountered
int read(char buffer[ ],int offset , int Reads numchar bytes into buffer starting from offset.
3
1
numchar) return -1 when end of the file is encountered
boolean ready() Returns true if the next input request will not wait
.otherwise it returns false
void mark(int numChars) Places a mark at the current point in the input stram that
will remain valid until numchars characters are read
void reset() Resets the input pointer to the previously set mark
Method Description
abstract void close() Closes the output stream.
abstract void flush() Flushes the output stream
Writer append(char ch) Appends ch to the end of output stream
Writer append(CharSequence chars) Appends the chars to the end of the output stream
Writer append(CharSequence chars,int begin,int end) Appends the subrange of chars specified by begin and
end-1 to the output stream.
void write(int ch) Write a single character to the output stream
void write(char buffer[]) Writes the complete array of characters to the output
stream
void write(String str) Write a string str to the output stream
abstract void write(char buffer[],int offset,int Write the subrange of numchars characters from
numChars) buffer beging of the offset to output stream
3
2
2.3.4 Reading Console Input And Writing Console Output
• Reading data from the console input(keyboard)
• There are many ways to read data from the console input keyboard. For example:
• InputStreamReader
• Console
• Scanner
• DataInputStream etc.
import java.io.*;
class IODemo
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:
Enter your name Abc
Welcome Abc
3
3
Example2:In this example, we are reading and printing the data until the user prints stop.
import java.io.*;
class IODemo2
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(name.equals("stop"))
{
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}
3
4
Output:Enter data:
Amit data is:
Amit
Enter data: 10
data is: 10
Enter data:
stop data is:
stop
The Scanner class breaks the input into tokens using a delimiter which is whitespace
bydefault. It provides many methods to read and parse various primitive values.
3
4
Commonly used methods of Scanner class
Method Description
public String next() returns the next token from the scanner
public String nextLine() moves the scanner position to the next line and returns the value as
a string.
public byte nextByte() scans the next token as a byte.
public short nextShort() scans the next token as a short value.
public int nextInt() scans the next token as an int value
public long nextLong() scans the next token as a long value.
public float nextFloat() scans the next token as a float value.
public double nextDouble() scans the next token as a double value
Example of the Scanner class which reads the int, string and double value as an input:
import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])
{
}
}
3
5
Output:Enter your rollno
111
Enter your
name Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000
The java.io package include a File class for creating files and directories.
The File class contain several methods for supporting the various operations such as
• Creating a file
• Opening a file
• Closing a file
• Deleting a file
• Getting name of the file
• Renaming a file
• Getting the size of the file
• Checking the existence of a file
• Checking whether the file is writable.
• Checking whether the file is
• To perform read or write operation the file must be opened first.This is done by creating a file stream
and then linking it to the filename
• A file stream can be defined using the classes of Reader/InputStream for reading data and
Writer/OutputStream for writing data.
• The constructor of Stream classes may be used to assign the desired filenames to the file stream
objects.
Reading/Writing Characters:
• The subclasses of Reader and Writer implements streams that handle characters.
• The two subclasses used are
3
7
Example to copy contents of file where file name are passed through command prompt (“input.txt” into file
“output.txt”)
ins.close();
outs.close();
}
catch(IOException e)
{
}
}
}
}
C:\>Javac CopyCharacters.java
Reading/Writing Bytes
• The subclasses of Reader and Writer implements streams that handle bytes.
• The two subclasses used are
class CopyBytes
try
byteRead=(byte)ins.read();
outs.write(byteRead);
}while(byteRead!=-1);
catch(IOException e)
System.out.println(e);
finally
3
9
try
{
ins.close();
outs.close();
catch(IOException e)
{
System.out.println(e);
}
}
4
0
2.3.7 Random Access Files
• RandamAccessFile class supported by java.io package allows us to create files that can be used
for reading and writing data with randam access.
• This class implements DataInput,and DataOutput and Closeable Interfaces
• It supports positioning request that means we can position the file pointer with in the file.
• It has two constructors
Access Purpose
r File opened for reading purpose
rw File opened for read-write purpose
rws File opened for read-write purpose and every change to ythe file’s data or ymetadata will be
immediately written to physical device
rwd File opened for read-write purpose and every change to ythe file’s data will be immediately
written to physical device
The method seek() is used to set the current position of the file pointer
Syntax:
4
0
Here,newPos specifies the new position,in bytes,of the file pointer from the beginning of the file.
Output:
x
3
3
3
3.1412
333
False
4
1
Explanation of the program
3
3
3
3.1412
2. Brings the file pointer to the beginning
3. Reads and display all the 3
iteam i.e x
333
3.1412
4. Takes the pointer to the second item and then reads and displays the second
item i.e 333
5. Places thepointer at the end and then adds a Boolean item to the file
6. Finally,takes pointer to the fourth item and display it.
7. At the end,closes the file
4
2
Me Description
tho
d
public String readLine() used to read a single line of text from the console
public String readLine(String fmt,Object... args) it provides a formatted prompt then reads the
single line of text from the console.
public char[] readPassword() used to read password that is not being displayed on
the console.
public char[] readPassword(String fmt,Object... it provides a formatted prompt then reads the
args)
password that is not being displayed on the console.
4
2
Example on Reading Console Input And Writing Console Output
import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
String str;
Console con;
con=System.Console();
if (con==null)
return;
str=con.readLine(“Enter a string:”);
con.printf(“Here is ur string: %s”,str);
}
}
Output:
4
3
Unit_ II previously asked 2 and 3 marks
Questions
1. List the byte stream classes[3 M]
2. Explain about implicit and explicit import statement[3]
3. How to create and access a package? [3]
4. Write about the random access file operations[3]
5. What is a package? How to define it and access it? [3]
6. Differentiate class, abstract class and interface. [2]
7. How to create and use a package in Java program? [3]
8. Define a Package? What is its use in java? Explain. [2]
9. List out the benefits of Stream oriented I/O. [3]
10. How to define a package in Java? [2]
11. Contrast between abstract class and interface. [3]
12. What are the methods available in the character streams? [2]
13. What is the significance of the CLASSPATH environment variable in
creating/using a package?[3]
14. What is Console class? What is its use in java? [2]
5
5
Unit –II previous asked Essay Questions
1. How to define a package? How to access, import a package? Explain with examples[ 5 marks]
2. Explain the various access specifiers are used in java.[5 m]
3. Write a program to implement the operations of random access file [5 m]
4. Explain the file management using File class.[5m]
5. What is a java package?What is CLASSPATH? Explain how to create and access a java package
with an example. .[5m]
6. Create an interface with at least one method and implement that interface by within a method
which returns a reference to your interface.[5m]
7. Write a program to compute an average of the values in a file.[5m]
8. Explain multilevel inheritance with the help of abstract class in your program. .[5m]
9. Can inheritance be applied between interfaces? Justify your answer. .[5m]
10. Differentiate between interface and abstract class. .[5m]
11. Write a program to copy the contents of file1 to file 2. Read the names of files as command line
arguments.[5m]
12. What support is provided by File class for file management? Illustrate with suitable scenarios. .[5m]
13. What is an interface? What are the similarities between interfaces and classes? .[5m]
14. How can you extend one interface by the other interface? Discuss. .[5m]
15. Discuss about CLASSPATH environment variables. [5m]
16. Discuss the different levels of access protection available in Java. [5m]
17. What is type wrapper? What is the role of auto boxing? [5m]
18. Explain the process of defining and creating a package with suitable examples. [5m]
19. Give an example where interface can be used to support multiple inheritance. [5m]
20. Describe the process of importing and accessing a package with suitable examples.[5m]
21. How to design and implement an interface in Java? Give an example[5m]
22. Give an example where interface can be used to support multiple inheritance. [5m]
23. What are the methods available in the Character Streams? Discuss. [5m]
24. Distinguish between Byte Stream Classes and Character Stream Classes. [5m]
25. What is the accessibility of a public method or field inside a nonpublic class or interface?
Explain. [5m]
56