Unit II Java

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 60

Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269

banand.cool@gmail.com

Hierarchical abstractions:
A powerful way to manage abstraction is through the use of hierarchical classification. This
allows to break the complex tasks into manageable pieces.

Abstraction in Java is the process in which we only show essential details/functionality to the
user. The non-essential implementation details are not displayed to the user.

Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of a car or applying brakes will stop the car, but he does not
know how on pressing the accelerator the speed is actually increasing, he does not know about
the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car.
This is what abstraction is.

Consider the Stack data structure, it has methods push(), pop(), display(), peek(). Here Stack
ADT will show these methods to the user rather than how it is implemented. These methods may
be implemented by the Arrays or LinkedList is unknown to the end user.

Important Terminologies Used in Java Inheritance

 Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
 Sub Class/Child Class: The class that inherits the other class is known as a subclass (or
a derived class, extended class, or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.

Subtype:

The term subtype often refers to a subclass relationship in which the principle of substitutability
is maintained, statically typed languages (C/C++/Java) place much more emphasis on principle
of substitutability than dynamically typed languages (Python/Small Talk)

The reason for this is the statically typed languages tend to characterize objects by their class
and dynamically typed languages tend to characterize by behavior.

That is the subtype us determined in statically typed languages by their class and dynamically
typed languages by their behaviour.

Why Do We Need Java Inheritance?


Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

 Code Reusability: The code written in the Superclass is common to all subclasses. Child
classes can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through Inheritance. It is one
of the ways by which Java achieves Run Time Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.

Substitutability:

"The principle of substitutability" says that if we have two classes 'A' and 'B' such that class
B is sub-class of A class, it should be possible to substitute instances of class B for instance of
class A in any situation with no observable effect.

Inheritance: Acquiring the properties of one class another one or classes is called inheritance.
(or)

Deriving new class from already existing class is called inheritance. Here already existing class
is called parent class/base class/super class. Newly derived class is called sub/child class.

 The main advantage with inheritance is code reusability.


 That means all the properties of a class can be reused many number of times in a class
without redeclaration .
 In java by inheriting one class into another class we can reuse the properties, inheritance
can be achieved using extends keyword.

Most people naturally view the world as made up of ojects that are related to each other in a
hierarchical way.

Inheritance: A new class (subclass, child class) is derived from the existing class(base class,
parent class).

Syntax:
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

class A{

Class B extends A{

A subclass is a specialized version of a super class. It inherits all of the instance variables and
methods defined by the super class and add its own, unique elements.
extends: To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword.
The “extends” keyword indicates that the properties of the super class name are extended to the
subclass name. The sub class now contain its own variables and methods as well those of the
super class. This kind of situation occurs when we want to add some more properties to an
existing class without actually modifying the super class members.
To see how, let’s begin with a short example. The following program creates a super class called
A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.
Inheritance Hierarchies:
In any object oriented programming language inheritance should be done from top to
bottom. That means base class properties inherited into child class but not derived class
properties into base class.

Types of inheritance :

It is many classified into 5 types

1.simple/single inheritance

2.multilevel

3.hierarchial

4. multiple

5.hybrid

Single Inheritance: Simple Inheritance is also called as single Inheritance. Here One subclass is
deriving from one super class.
A SUPER CLASS A
extends
SUB CLASS B
B
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Multiple Inheritance: Deriving one subclass from more than one super classes is called
multiple inheritance.

We know that in multiple inheritance, sub class is derived from multiple super classes. If two
super classes have sane names for their members then which member is inherited into the sub
class is the main confusion in multiple inheritance. This is the reason, Java does not support the
concept of multiple inheritance,. This confusion is reduced by using multiple interfaces to
achieve multiple inheritance.

Hierarchical Inheritance: Multiple classes derived from single class i.e; there exist single super
class multiple sub classes.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Multilevel Inheritance: Whenever multiple classes are participated in inheritance in sequential


order is called multi level inheritance.

Example: As mentioned, it is perfectly acceptable to use a subclass as a superclass of another.


For example, given three classes called A, B, and C, C can be a subclass of B, which is a
subclass of A. When this type of situation occurs, each subclass inherits all of the traits found in
all of its super classes. In this case, C inherits all aspects of B and A. To see how a multilevel
hierarchy can be useful, consider the following program.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
Hybrid Inheritance: It is a combination of one or types of other inheritances.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

super keyword:

super is a keyword in java language represents super class(or) base class object. The 'super' keyword
allows referencing the parent class or superclass of a subclass in Java. It is often employed to access
members (fields or methods) of the superclass that have been overridden in the subclass. You can call the
superclass's method from within the subclass using "super.methodName()". Additionally, super() is
used to call the constructor of the superclass from the subclass constructor, which is essential for
initializing inherited members. In short, if any programmers want to maintain inheritance hierarchies and
enable the reuse of code in object-oriented programming, this super keyword is crucial.

class Vehicle {

int maxSpeed = 113;

void speed() {

System.out.println("Speed vary from vehicle to vehicle");

class Bike extends Vehicle {

int maxSpeed = 170;

void speed() {

super.speed(); //Calling super class method

System.out.println("CBZ MaxSpeed: "+ super.maxSpeed); //Calling super class variable

System.out.println("Royal enfield MaxSpeed: "+ maxSpeed);

public class SuperTest {

public static void main(String[] args) {

Vehicle v = new Bike();

v.speed();

}
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

super():

When ever we want to call base class constructor with in the derived class constructor then super() can be
used.

Syntax:

super() used to call no parameterized constructor of super class in to derived class constructor.

super(value1,value2---)used to call parameterized constructor of base / super class into sub/derived class
constructor.

class Person {

Person() {

System.out.println("Person class Constructor 1");

Person(String str) {

System.out.println("Person class Constructor 2");

class Student extends Person {

Student() {

super();

System.out.println("Student class Constructor 1");

Student(String str) {

super(str);

System.out.println("Student class Constructor 2");

public class SuperWithConstructors {

public static void main(String[] args) {

Student obj1 = new Student();


Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Student obj2 = new Student();

this ():

Constructor chaining can be done in two ways:

With in same class : It can be done using this() keyword for constructors in the same class. Whenever we
want to call one constructor in another constructor of the same class we this().
From base class : by using super() keyword to call the constructor from the base class.

class Animal{

String type;

String color;

public Animal() {

System.out.println("No Param constructor");

public Animal(String type, String color) {

this();

System.out.println("Two Param constructor");

public Animal(String color) {

this("Lion", "Yellow");

System.out.println("Single Param constructor");

public class ThisOfExample {

public static void main(String[] args) {

Animal obj =new Animal("Yellow");

}
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Preventing Inheritance:

To prevent the inheritance in java we use the keyword final.

final: final keyword in java used restrict the inheritance. The java final keyword can be used in
many context. Final can be:

1. variable
2. method
3. class

final class A

final void show()

System.out.println("This is show()");

class B extends A //Error occured

void showmsg()

System.out.println("Hello");

If you compile the above program we will get the error because class A is declared as final.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

class Vehicle{

void run()

System.out.println("It is running...");

final void shape()

System.out.println("It has good shape…");

class Bike extends Vehicle{

public static void main(String args[]){

Bike i=new Bike();

i.run();

i.shape();//Error

If you compile the above program we will get the error because method run is declared as final.

Base class Object or The Object class:

Object class: Super class for all the classes in java including user defined classes directly or
indirectly.
Importing Object class: Java API
Java.lang package
Object class
Object class is implicitly(automatically) imported into our source code, because it is in "java.
lang" package. "java.lang" package is also implicitly imported into every java program.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Object class reference can store any reference of any object. This means that a reference variable
of type Object can refer to an object of any other class.
Advantage: When we want to write a method that needs to handle objects if unknown type. If we
define a parameter of object type, any class object can be passed to the method. Thus the method
can receive any type of object and handle it.

Method Description
boolean This method compares the references of two objects and if they are equal,
equals(Object obj) it returns true, otherwise false.
String toString() This method returns a string representation of an object.
Class getClass() This method gives an object that contains the name of a class to which an
object belongs. Obtains the class of an object at run time.
int hashCode( ) Returns the hash code associated with the invoking object. This method
returns hash code number of an object.
void notify( ) This method sends a notification to a thread which is waiting for an
object.
void notifyAll( ) This method sends a notification for all waiting threads for the object.
void wait( ) This method causes a thread to wait till a notification is received from a
notify() or notifyAll() methods.
Object clone( ) This method creates a bitwise exact copy of an existing object. Creates a
new object that is the same as the object being cloned.
void finalize( ) Called before an unused object is recycled. This method is called by the
garbage collector when an object is removed from memory.

Note: The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may
override the others.
Example programs:
class Parrot{
public void fly() {
System.out.println("Parrot fly");
}
}
class Dog {
public void bark() {
System.out.println("Dog bark");
}
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

}
class Fish{
public void swim() {
System.out.println("Fish swim");
}
}
public class ObjectExample {
public static void getBehavior(Object obj) {
if(obj instanceof Parrot) {
Parrot p = (Parrot)obj;
p.fly();
}
if(obj instanceof Fish) {
Fish f = (Fish)obj;
f.swim();
}
if(obj instanceof Dog) {
Dog d = (Dog)obj;
d.bark();
}
}
public static void main(String[] args) {
getBehavior(new Parrot());
getBehavior(new Fish());
getBehavior(new Dog());
}
}
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Example 2:
class Point{
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public boolean equals(Point p) {
if((this.x == p.x) && (this.y == p.y)) {
return true;
}
return false;
}
}
public class EqualsExample {
public static void main(String[] args) {
Point p1 = new Point(10.23, 56.32);
Point p2 = new Point(10.23, 56.32);
System.out.println(p1.equals(p2));
}
}
Forms of inheritance:

Inheritance is used in a variety of way and for a variety of different purposes.


• Specialization

• Specification
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

• Construction

• Extension

• Limitation

• Combination.

Specialization:
It is the most ideal form of inheritance. In this the derived class is specialized form of the parent
class and satisfies the specifications of the parent in all relevant aspects. It holds the principle of
substitutability.
Example: A class Window provides general windowing operations such as moving, resizing etc.
A specialized sub class TextEditWindow inherits the window opens and in addition provides the
windows to display textual material.

Specification:

This is another commonly used form of inheritance. In this form of inheritance, the parent class
just specifies which methods should be available to the child class but doesn't implement them.
The java provides concepts like abstract and interfaces to support this form of inheritance. It
holds the principle of substitutability.

abstract class Shape{


public abstract void draw();
}
class Rectangle extends Shape{
public void draw() {
System.out.println("You can draw rectangle shape");
}
}
class Circle extends Shape{
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

public void draw() {


System.out.println("You can draw circle shape");
}
}
class Triangle extends Shape{
public void draw() {
System.out.println("You can draw triangle shape");
}
}
public class Specification {
public static void main(String[] args) {
Shape s;
s = new Circle();
s.draw();
}
}
Construction:

This is another form of inheritance where the child class may change the behavior defined by the
parent class (overriding). It does not hold the principle of substitutability. This type of
inheritance is also widely used for code reuse purposes.

Extension:

This is another form of inheritance where the child class may add its new properties and does not
modify or alter any of the inherited attributes. It holds the principle of substitutability.

Subclasses are always subtypes, and substitutability can be used.

Example of this type of inheritance is done in the definition of the class Properties which is an
extension of the class HashTable.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Limitation:

This is another form of inheritance where the subclass restricts the inherited behavior. It does not
hold the principle of substitutability.

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
}

Benefits Of Inheritance

 S/w code Reusability:


Many programmers spend much of their time in rewriting code they have written many
times before. So with inheritance code once written can be reused.
 code sharing
Code sharing occurs at two levels. At first level many users or projects can use the same
class. In the second level sharing occurs when two or more classes developed by a single
programmer as part of a project which is being inherited from a single parent class. Here
also code is written once and reused. This is possible through inheritance.
 Consistency of inheritance:
When two or more classes inherit from the same super class, we are assured that the
behavior they inherit will be the same in all cases. Thus, we can guarantee that interfaces
to similar objects are in fact similar.
 Software components:
Inheritance provides programmers the ability to construct reusable s/w components. The
goal behind these is to provide applications that require little or no actual coding. Already
such libraries and packages are commercially available.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

 Polymorphism and Framework:


Generally, s/w is written from the bottom up, although it may be designed from top-
down. This is like building a wall where every brick must be laid on top of another brick
i.e., the lower level routines are written and on top of these slightly higher abstraction are
produced and at last more abstract elements are generated. polymorphism permits the
programmer to generate high level reusable components.
 Information Hiding:
A Programmer who reuses a software need only to understand the nature of the
component and its interface. There is no need to have detailed information of the
component and it is information hiding.

Costs of Inheritance:

Although they are benefits with object-oriented programming, we must also consider the cost of
inheritance.

 Execution Speed: The inherited methods which must deal with orbitary sub-classes are
often slower than specialized code. Here efficiency is often misplaced. It is far better to
develop a working system and monitor it.
 Program Size: The use of any s/w library imposes a size penalty not imposed by systems
constructed for a specific project. Although the expense may be substantial and size of
program becomes less important.
 Message passing overhead: Message passing is costly by nature a more costly operation
than simple procedure invocation
 Program Complexity: Although object-oriented programming is often touched as a
solution to s/w complexity. the complexity increases when we use inheritance. But it is
not considerable.

Polymorphism:
Polymorphism is nothing but "Ability to take more than one form".

(or)

The polymorphism is the process of defining same method with different implementation. That
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

means creating multiple methods with different behaviors.

Types of Java polymorphism

The Java polymorphism is mainly divided into two types:

1. Compile-time Polymorphism(Method Overloading)

2. Runtime Polymorphism(Method Overriding)

Ad Hoc Polymorphism(Method Overloading) / Compile-time Polymorphism/ Static method


binding:

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

Same method in a class exist multiple times with different parameters is known as method
overloading.

Method Overloading is done in following ways

 Different order of parameters


 Different types of parameters
 Different number of parameters

class Addition{
void add(int a, int b) {
int c = a + b;
System.out.println("Two int numbers addition: "+c);
}
void add(float a, float b) {
float c = a + b;
System.out.println("Two float numbers addition: "+c);
}
void add(int a, int b, int c) { //calle
int d = a + b + c;
System.out.println("Three int numbers addition: "+d);
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

}
}
public class MethodOverloading {
public static void main(String[] args) { //caller
Addition obj = new Addition();
obj.add(10,52,45);
obj.add(10,53);
obj.add(53.4f, 63.5f);
}
}

Pure Polymorphism(Method Overriding)/Runtime Polymorphism/ Dynamic method


binding:
Whenever same method name is existing in both base class and derived class with same types of
parameters or same order of parameters is known as method Overriding.
In a java programming language, pure polymorphism carried out with a method overriding
concept.
Note: Without Inheritance method overriding is not possible.
class KeyPadPhone{

public void textmessage() {

System.out.println("Text message with basic symbols");

class SmartPhone extends KeyPadPhone{

public void textmessage() { // Overridden method

super.textmessage(); // Calls super class textmessage();

System.out.println("Text message with special symbols and emojis");


Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

public class InheritanceExample2 {

public static void main(String[] args) {

KeyPadPhone obj = new SmartPhone();

obj.textmessage(); //called from Smartphone class

Dynamic Method Dispatch:

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved
at run time, rather than compile time.

Dynamic method dispatch is important because this is how Java implements run-time
polymorphism.

class Bank{
float getRateOfInterest(){
return 0;
}
}
class SBI extends Bank{
float getRateOfInterest(){
return 8.4f;
}
}
class ICICI extends Bank{
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

float getRateOfInterest(){
return 7.3f;
}
}
class AXIS extends Bank{
float getRateOfInterest(){
return 9.7f;
}
}
public class DynamicMethodDispatch{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

Packages:

Package is a special container which is collection of classes, Interfaces and sub packages.

 The main advantage of package is common reusability that all the class ,interface
properties can be used at a time diff other programs.
 In java language every package will be treated as one folder and every sub-package will
be treated as sub-folder.
 Package are mainly classified into 2 types
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

1)Built-in Packages/ Predefined Packages


2)User defined Packages

Bulit-in Packages/ Predefined Packages:

These are the packages which are already available in Java API. These packages provide
all most all necessary classes, interfaces and methods for the programmer to perform any task in
his programs. Since, Java has an extensive library of packages, a programmer need not think
about logic for doing any task. Following are the mostly used packages in core java application.

java.lang: This package got primary classes and interfaces essential for developing a basic Java
program, this is default package for every java program. It consists of wrapper classes(Integer,
Character, Float etc), which are useful to convert primitive data types into objects. There are
classes like String, StringBuffer, StringBuilder classes to handle strings. There is a thread class
to create various individual processes.

java.util: util stands for utility. Contains utility classes which implement data structures like
Linked List, Dictionary,Stack,Vector and support ; for Date / Time operations..

java.io: io stands for input and output. This package contains streams. A stream represents flow
of data from one place to another place. Streams are useful to store data in the form of files and
also to perform input-output related tasks.

java.awt: awt stands for abstract window toolkit. This helps to develop GUI(Graphical user
Interfaces) where programs with colorful screens, paintings and images etc., can be developed. It
consists of an important sub package, java.awt.event, which is useful to provide action for
components like push buttons, radio buttons, menus etc.

java.awt.event: This package has the classes and interfaces are used to perform operations
behind the GUI screens.

javax.swing: this package helps to develop GUI like java.awt. The ‘x’ in javax represents that it
is an extended package which means it is a package developed from another package by adding
new features to it. In fact, javax.swing is an extended package of java.awt.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

java.net : net stands for network. Client-Server programming can be done by using this package.
Whenever we want to develop network based applications we use this package.

java.applet: This package contain only one class Applet is used to create the applet programs.

java.sql: sql stands structured query language. This package helps to connect to databases like
Oracle or Sybase, retrieve the data from them and use it in a Java program.

User-Defined packages:

Just like the built in packages shown earlier, the users of the Java language can also create their
own packages. They are called user-defined packages. User-defined packages can also be
imported into other classes and used exactly in the same way as the Built-in packages.

Creating User Defined Packages:

To create user defined packages we have to follow the following rules:

1.Create a package using the keyword “package”. This should be first statement in the package
program.

2.Create a class or interface that should be public.

3.Declare a method or data member that should be public.

4.Package program should not contain main().

Example:

First write the package program Areas.java

Areas.java:

package area;

public class Areas


{
public void carea(float r)
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

{
double area=3.14*r*r;
System.out.println("Area of circle is="+area);
}
public void tarea(float b,float h)
{
double area=0.5*b*h;
System.out.println("Area of circle is="+area);
}
}
Now compile the above program like following:

javac –d . Areas.java

The –d option tells the Java compiler to create a separate directory and place the .class file in that
directory (package). The (.) dot after –d indicates that the package should be created in
the current directory. So, out package area with Areas class is ready.

Now write another class to use it named it as Use.java

Use.java:

import area.Areas;
class Use
{
public static void main(String[] args)
{
Areas oa=new Areas();
oa.carea(1.2f);
oa.carea(0.36f);
oa.tarea(10.3f, 4.5f);
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

oa.tarea(1.302f, 3.024f);
}
}
Output:
Area of circle is=4.52160035934449
Area of circle is=0.4069440323410041
Area of circle is=23.175000429153442
Area of circle is=1.968624023271559
UNDERSTANDING CLASSPATH:

CLASSPATH: CLASSPATH is an environment variable which is used by Application


ClassLoader to locate and load the .class files. It includes all the directories which contain .class
files and JAR files when setting the CLASSPATH.

You need to set the CLASSPATH if:


 You need to load a class that is not present in the current directory or any sub-directories.
 If a JAR or zip, the file contains class files, the CLASSPATH end with the name of the
zip or JAR file.
CLASSPATH can be set by any of the following ways:
1. CLASSPATH can be set permanently in the environment variables:
 In Windows, choose control panel
 Choose System and security
 Choose system
 Search for View Advanced System settings
 Advanced
 Environment Variables
 choose "System Variables" (for all the users) or “User Variables” (only the currently
login user)
 choose "Edit" (if CLASSPATH already exists) or "New"
 Enter "CLASSPATH" as the variable name
 Enter the required directories and JAR files (separated by semicolons) as the value
".;c:\javaproject\classes;D:\mysql-connector-java-5.1.10.jar"
2. CLASSPATH can be set temporarily in the command prompt:
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

We are setting the classpath to c:\javaproject\classes directory and mysql-connector-


java-5.1.10.jar, here current directory (.) .

Creating Sub package in a package: We can create sub package in a package in the format:
package packagename.subpackagename;
e.g.: package pack1.pack2;
Here, we are creating pack2 subpackage which is created inside pack1 package. To use
the classes and interfaces of pack2, we can write import statement as:
import pack1.pack2;
Importing Packages:
There two ways to importing the packages:
 using fully qualified name
 using import statement

Using fully qualified name:

If we want to access any class properties of a package in other user defined class we must create
an object with a fully qualified name.
package1. package2….. classname object = new package1.packaage2…classname();

Write a java program to use package properties with a fully qualified name.

For example, if you to import Scanner class which is available in "java.util" package you can
import it using fully qualified name given below:
java.util.Scanner sc = new java.util.Scanner();

Using import statement:


Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Properties of any package also can be accessed using import statement import is a keyword in
java language and these statements can be used in two different ways.

Syntax:

1.import package1.package2..class/interface

2.import package1,package2..*;

First syntax can be used to import only one class (or) interface properties at a time.

Second syntax can be used to import all classes and interface properties at a time.

Example: import java.util.ArrayList; --->Import only ArrayList class from java.util package

Import java .util.*; --->Import only all classes and interfaces from java.util package, but not
subpackages.

Abstract classes:
 A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).
 An abstract class must be declared with an abstract keyword.
 It cannot be instantiated. It can have constructors and static methods also.

Syntax
abstract class className {
......
}
Abstract Method:
 An abstract method contains only declaration or prototype but it never contains body or
definition.
 In order to make any undefined method as abstract whose declaration is must be
predefined by abstract keyword.

Syntax
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

abstract returntype methodName(List of formal parameter);


Note: Whenever you extends any abstract class, you must override all abstract methods from the
abstract class otherwise your class also become abstract.
abstract class Animal{

public void eat(){

System.out.println("This animal eat everyday");

public void sleep(){

System.out.println("This animal sleep everyday");

public abstract void sound();

class Cat extends Animal {

public void sound(){

System.out.println("This animal make sound like meowwww...");

class Dog extends Animal {

public void sound(){

System.out.println("This animal make sound like Bowwwww...");

class Gri{

public static void main(String args[]){

Cat oc=new Cat();


Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

System.out.println("===this is Cat Animal========");

oc.eat();

oc.sleep();

oc.sound();

Dog od=new Dog();

System.out.println("===this is Dog Animal========");

od.eat();

od.sleep();

od.sound();

Output:

===this is Cat Animal========

This animal eat everyday

This animal sleep everyday

This animal make sound like meowww...

===this is Dog Animal========

This animal eat everyday

This animal sleep everyday

This animal make sound like Bowwwww...

In above example Animal is a base class is having sound() is an abstract method with no
implementation because all animals eat every day and sleep everyday but make sound is
different. So here sound() is declared as abstract method now its sub classes implement their own
implementation by overriding it.

Example 2:
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

abstract class Shape {


abstract void draw();
}
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");
}
}
public class AbstractExample {
public static void main(String args[]) {
Shape s;
s =new Circle();
s.draw();
s =new Rectangle();
s.draw();
s =new Triangle();
s.draw();
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

}
}
Example 3:
abstract class FoodOrder{
abstract void order();
}
class Swiggy extends FoodOrder{
public void order() {
System.out.println("You got food from Swiggy");
}
}
class Zomato extends FoodOrder{
public void order() {
System.out.println("You got food from Zomato");
}
}
class FoodPanda extends FoodOrder{
public void order() {
System.out.println("You got food from FoodPanda");
}
}
class User{
public void getFood(FoodOrder obj) {
obj.order();
}
}
public class AbstractExample {
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

public static void main(String[] args) {


User obj = new User();
obj.getFood(new Swiggy());
obj.getFood(new FoodPanda());
obj.getFood(new Zomato());
}
}
Interfaces
 Interface is similar to class which is collection of public static final variables (constants)
and abstract methods.
 The interface is a mechanism to achieve fully abstraction in java. There can be only
abstract methods in the interface. It is used to achieve fully abstraction and multiple
inheritance in Java.
 If we want to use the properties of an interface then that must be implements in any user
defined class. And every abstract method of an interface should be overridden in it’s
implemented class otherwise that class becomes abstract class.

Note : From jdk1.8 version onwards Java interfaces are extended to allow the static and default
methods.

Why do we use an Interface?

 It is used to achieve total abstraction.


 Since java does not support multiple inheritances in the case of class, by using an
interface it can achieve multiple inheritances.
 Any class can extend only 1 class but can any class implement infinite number of
interface.
 Interfaces are used to implement abstraction. So the question arises why use interfaces
when we have abstract classes?
 The reason is, abstract classes may contain non-final variables, whereas variables in the
interface are final, public and static.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Defining Interfaces
The "interface" keyword is used to declare an interface.
Syntax
interface interface_name {
declare constant fields
declare methods that abstract
}
Example
interface A {
public static final int a = 10;
public abstract void display();
}
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

interface B {
int x = 100; // by default x is public static final
void show(); // by default show() is public abstract
}
In interface every data member by default "public static final" and methods are "public abstract".

Implementing Interfaces

Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create the
methods defined by the interface.

interface Flyable{
public abstract void fly();
}
interface Walkable{
public abstract void walk();
}
interface Swimmable{
public abstract void swim();
}
interface Jumpable{
public abstract void jump();
}
class KingFisher implements Flyable{
public void fly() {
System.out.println("KingFisher is Flyable");
}
}
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

class Frog implements Swimmable, Jumpable{


public void jump() {
System.out.println("Frog Jumpable");
}
public void swim() {
System.out.println("Frog Swimmable");
}
}
class Tortoise implements Swimmable, Walkable{
public void walk() {
System.out.println("Tortoise Walkable");
}
public void swim() {
System.out.println("Tortoise Swimmable");
}
}
public class ImplementingInterfaces {
public static void main(String[] args) {
Frog obj1 = new Frog();
obj1.jump();
obj1.swim();
Tortoise obj2 = new Tortoise();
obj2.swim();
obj2.walk();
KingFisher obj3 = new KingFisher();
obj3.fly();
}
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

}
Applying Interfaces:

To understand the use of interfaces let us consider to developed two classes "FixedStack" and
"GrowableStack" that implemented a simple "IntStack". There are many ways to implement a
stack. For example, the stack can be of a fixed size(Implement using Arrays) or it can be
growable(Implement using Linkedlist). The stack can and so on. No matter how the stack is
implemented, the interface to the stack "IntStack" remains the same. That is, the methods
push() and pop() define the interface to the stack independently of the details of the
implementation. Because the interface to a stack "IntStack" is separate from its implementation,
it is easy to define a stack interface "IntStack", leaving it to each implementation to define the
specific. First, here is the interface that defines an integer stack "IntStack". Put this in a file
called IntStack.java. This interface will be used by both stack implementations(FixedStack and
GrowableStack).

// Define an integer stack interface.


interface IntStack {
void push(int item); // store an item into the stack
int pop(); // retrieve an item from the stack
}
class FixedStack implements IntStack {
public void push(int item) {
//Code to implement the push() for FixedStack
}
public int pop() {
//Code to implement the pop() for FixedStack
}
}
class GrowableStack implements IntStack {
public void push(int item) {
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

//Code to implement the push() for GrowableStack


}
public int pop() {
//Code to implement the pop() for GrowableStack
}
}
Variables In Interface
 Variables can be declared inside of interface declarations. They are implicitly final and
static, meaning they cannot be changed by the implementing class.
 You can use interfaces to import shared constants into multiple classes by simply
declaring an interface that contains variables that are initialized to the desired values.
import java.util.Scanner;
interface SharedConstants{
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int NEVER = 4;
}
class Question implements SharedConstants{
Scanner sc = new Scanner(System.in);
int ask() {
System.out.println("would u like to have a cup of coffee?");
String ans = sc.nextLine();
if (ans.equals("no"))
return NO;
else if (ans.equals("yes"))
return YES;
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

else if (ans.equals("notnow"))
return LATER;
else
return NEVER;
}
}
public class InterfaceVariables {
public static void main(String args[]) {
Question q = new Question();
System.out.println(q.ask());
}
}
Extending Interfaces:

One interface can inherit another by use of the keyword extends. The syntax is the same as
for inheriting classes. When a class implements an interface that inherits another interface,
it must provide implementations for all methods defined within the interface inheritance
chain.
interface A{
void meth1();
void meth2();
}
interface B extends A{
void meth3();
}
class MyClass implements B{
public void meth1(){
System.out.println("Implement meth1().");
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

}
public void meth2(){
System.out.println("Implement meth2().");
}
public void meth3(){
System.out.println("Implement meth3().");
}
}
public class ExtendingInterfaces {
public static void main(String[] args) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Multiple Inheritance in Java by Interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Member access rules:


An access specifier is a keyword that is used to specify how to access a member of a class. Java
provides many levels of protection to allow fine-grained control over the visibility of variables
and methods within classes, subclasses, and packages using access specifiers.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

protected Y Y Y N

Public Y Y Y Y
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

We can protect the data from unauthorized access. To do this ,we are using access specifiers.

There are four access specifiers in java:

private: private members of a class are not available outside the class. You can access private
members of a class inside the class only.

public: public members of a class are available anywhere outside the class and package.

protected: Protected members accessed by any member in the same package and sub class of
other package.

default: If no access specifier is used then default specifier is used by java compiler.
default members of a class are available with in the same package in which it is defined.

Example For Private:

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 Time Error
obj.msg();//Compile Time Error
}
}
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Example for default:

//save by A.java
package pack;
class A{
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();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Example for Protected:

//save by A.java
package pack;
public class A{
protected void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Example for public:

//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();
}
}
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Exploring java.io:
Streams : Stream means continuous flow of data. Java performs I/O through Streams. In
general, It has a source (of data) and a destination (for that data) as depicted in below figure.
Both the source and the destination may be physical devices or programs or other streams in the
same program.

I/O Streams : – Java streams are classified into two basic types input stream and output stream.
An input stream extracts (i.e. reads) data from the source (i.e. file) and sends it to the program.
Similarly, an output stream takes data from the program and sends (i.e. writes) it to the
destination (file).

In Java, 3 streams are created for us automatically. All these streams are attached with the
console.

1. System.in: This is the standard input stream that is used to read characters from the keyboard
or any other standard input device.

2. System.out: This is the standard output stream that is used to produce the result of a program
on an output device like the computer screen.

3. System.err: This is the standard error stream that is used to output all the error data that a

program might throw, on a computer screen or any standard output device.


Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Java Stream Classes:

Byte Streams:

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.

Input Stream : Input stream classes are used to read 8-bit bytes include a super class called as
InputStream and a number of subclasses for supporting various input related functions. Below
figure shows the class hierarchy of input stream classes.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

The super class InputStream is an abstract class and we cannot create instances of super class. So
we must use the subclasses that inherit from super class.

The InputStream class defines methods for performing input functions.

Example: FileInputStream

import java.io.*;
class InputStreamEx{
public static void main(String[] args) throws Exception {
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

FileInputStream fis = new FileInputStream("anand.txt");


DataInputStream dis = new DataInputStream(fis);
String d=" ";
while((d = dis.readLine()) != null){
System.out.println(d);
}
fis.close();
dis.close();
}
}
Output Stream : Output stream classes are derived from the base class OutputStream. Like
InputStream, the OutputStream is an abstract class and we cannot instantiate it. The several
subclasses of the OutputStream can be used for performing the output operations.

Below figure shows the class hierarchy of output stream classes.

Some output stream methods are below : –


Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Example 2: FileOutputStream:
import java.io.*;
class OutputStreamEx
{
public static void main(String[] args) throws Exception
{
FileOutputStream fos=new FileOutputStream("harish.txt");
DataOutputStream dos=new DataOutputStream(fos);
String data="Anurag Engineering College";
byte arr[] = data.getBytes();
dos.write(arr);
fos.close();
dos.close();
}
}
Character Streams:

Character stream is used to read and write a single character of data. There are two kinds of
character stream classes’ reader stream classes and writer stream classes. Though there are many
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

classes related to character streams but the most frequently used classes are, FileReader and
FileWriter.

Reader Stream Classes : These classes are used to read characters from the files. Reader class
is the super class for all other Reader classes. These classes are functionally very similar to the
input stream classes, except input stream use bytes, while reader stream use characters.

Hierarchy of reader stream classes: –

Methods of Reader

The Reader class provides different methods that are implemented by its subclasses. Here are

some of the commonly used methods:

 ready() - checks if the reader is ready to be read


 read(char[] array) - reads the characters from the stream and stores in the specified
array
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

 read(char[] array, int start, int length) - reads the number of characters equal to length
from the stream and stores in the specified array starting from the start
 mark() - marks the position in the stream up to which data has been read
 reset() - returns the control to the point in the stream where the mark is set
 skip() - discards the specified number of characters from the stream

FileReader Example:
import java.io.*;
class FileReaderEx{
public static void main(String[] args) throws Exception
{
FileReader fr=new FileReader("F:\\ramya.txt");
int c=0;
while((c=fr.read())!=-1) {
System.out.println((char)c);
}
fr.close();
}
}
Writer Stream Classes : The writer stream classes are used to perform all output operations on
files. Only difference is that while output stream classes are used for write bytes, the writer
stream classes are designed to write characters.

Hierarchy of writer stream classes: –


Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Methods of Writer

The Writer class provides different methods that are implemented by its subclasses. Here are

some of the methods:

 write(char[] array) - writes the characters from the specified array to the output stream
 write(String data) - writes the specified string to the writer
 append(char c) - inserts the specified character to the current writer
 flush() - forces to write all the data present in the writer to the corresponding destination
 close() - closes the writer

FileWriter Example:
import java.io.*;
class FileWriterEx {
public static void main(String[] args) throws Exception {
FileWriter fw = new FileWriter("F:\\rose.txt");
String data="Rose is a beautiful flower";
char arr[] = data.toCharArray();
fw.write(arr);
System.out.println("Data written successfully");
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

fw.close();
}
}
Ways to read input from console in Java:

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

Java Reading Console Input Methods

1. Using BufferedReader Class

2. Using Scanner Class

3. Using Console Class

1.Using Buffered Reader Class

 This is the Java classical method to take input, Introduced in JDK1.0. This method is
used by wrapping the System.in (standard input stream) in an InputStreamReader which
is wrapped in a BufferedReader, we can read input from the user in the command line.
 The BufferedReader class has defined in the java.io package.
 We can use read() method in BufferedReader to read a character.
 We can use readLine() method in BufferedReader to read a line of text.

Syntax: int read() throws IOException

import java.io.*;
public class ReadingConsoleInputTest {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a line");
String data = br.readLine();
System.out.println("Enter a integer");
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

int x = Integer.parseInt(br.readLine());
System.out.println("Enter a float");
float y = Float.parseFloat(br.readLine());
System.out.println(data);
System.out.println(x);
System.out.println(y);
}
}
2. Using the Scanner Class

Scanner is one of the predefined class which is used for reading the data dynamically from the
keyboard.

Import Scanner Class in Java

java.util.Scanner

Constructor of Scanner Class

Scanner(InputStream)

This constructor create an object of Scanner class by talking an object of InputStream class. An
object of InputStream class is called "in" which is created as a static data member in the
"System" class.

Syntax of Scanner Class in Java

Scanner sc=new Scanner(System.in);

Here the object 'in' is use the control of keyboard

import java.util.Scanner;

public class ScannerExample {

public static void main(String[] args) {


Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Scanner sc = new Scanner(System.in);

byte a = sc.nextByte();

short b = sc.nextShort();

int c = sc.nextInt();

long d = sc.nextLong();

float e = sc.nextFloat();

double f = sc.nextDouble();

boolean h = sc.nextBoolean();

3. Using the Console Class


Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

 This is another way of reading user input from the console in Java.
 The Java Console class is be used to get input from console. It provides methods to read
texts and passwords.
 If you read password using Console class, it will not be displayed to the user.
 The Console class is defined in the java.io class which needs to be imported before using
the console class.

import java.io.Console;
public class ConsoleExample {
public static void main(String[] args) {
String name;
char[] password;
Console c = System.console();
System.out.println ("Enter your name: ");
name = c.readLine();
System.out.println ("Your name is: " + name);
password = c.readPassword();
System.out.println ("Your password is: " + new String(password));
}
}
Writing Console Output

print() and println() methods in System.out are mostly used for console output.

These methods are defined by the class PrintStream which is the type of object referenced by

System.out.

System.out is the byte stream.

PrintStream is the output derived from OutputStream. write method is also defined in
PrintStream for console output.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

void write(int byteval)

//Java code to Write a character in Console Output

import java.io.*;

class WriteCharacterTest {

public static void main(String args[]) {

int byteval;

byteval = 'J';

System.out.write(byteval);

System.out.write('\n');

Random access file operations:


The Java.io.RandomAccessFile class file behaves like a large array of bytes stored in the file
system . Instances of this class support both reading and writing to a random access file.

 Reading and writing using the FileInputStream and FileOutputStreams are a sequential
process.
 Using a random access file, we can read or write at any position within the file.
 An object of the RandomAccessFile class can do the random file access. We can
read/write bytes and all primitive types values to a file.
 RandomAccessFile can work with strings using its readUTF() and writeUTF() methods.

Mode

A random access file can be created in four different access modes. The access mode value is a
string. They are listed as follows:
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Mode Meaning

"r" The file is opened in a read-only mode.

"rw" The file is opened in a read-write mode. The file is created if it does not exist.

"rws" The file is opened in a read-write mode. Any modifications to the file's content and its metadata are
written to the storage device immediately.

"rwd" The file is opened in a read-write mode. Any modifications to the file's content are written to the
storage device immediately.

Methods:
int read():
This method reads a byte of data from this file.
int read(byte[] b):
This method reads up to b.length bytes of data from this file into an array of bytes.
void seek(long pos):

This method sets the file-pointer offset, measured from the beginning of this file, at which the
next read or write occurs.

void write(byte[] b):

This method writes b.length bytes from the specified byte array to this file, starting at the current
file pointer.

void write(byte[] b, int off, int len):

This method writes len bytes from the specified byte array starting at offset off to this file.
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

String readUTF():

This method reads in a string from this file.

void writeUTF(String str):

This method writes a string to the file using modified UTF-8 encoding in a machine-independent
manner.

Reading data from file Randomly

import java.io.*;

class RandRead{

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

RandomAccessFile file=new RandomAccessFile("f:\\anand.txt","rw");

file.seek(11);

System.out.println(file.readLine());

file.close();

Writing data to file Randomly.

import java.io.*;

class RandWrite{

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

RandomAccessFile file=new RandomAccessFile("f:\\anand.txt","rw");

String data="Kodad";

byte[] arr=data.getBytes();

file.seek(22);
Java UNIT II(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

file.write(arr);

file.close();

You might also like