0% found this document useful (0 votes)
4 views

OOP-Java_Unit-2

The document discusses key concepts of Object Oriented Programming (OOP) in Java, focusing on inheritance, packages, and interfaces. It explains various forms of inheritance, such as single, multilevel, and hierarchical inheritance, along with the use of the super keyword and method overriding. Additionally, it covers the benefits and disadvantages of inheritance, as well as how to create and import Java packages.

Uploaded by

amreen2825
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

OOP-Java_Unit-2

The document discusses key concepts of Object Oriented Programming (OOP) in Java, focusing on inheritance, packages, and interfaces. It explains various forms of inheritance, such as single, multilevel, and hierarchical inheritance, along with the use of the super keyword and method overriding. Additionally, it covers the benefits and disadvantages of inheritance, as well as how to create and import Java packages.

Uploaded by

amreen2825
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

www.youtube.

com/@SravanKumarGurram
OBJECT ORIENTED
PROGRAMMING THROUGH JAVA
UNIT-2
Inheritance, Packages and Interfaces

1
www.youtube.com/@SravanKumarGurram
INHERITANCE
CHAPTER – 1

2
INHERITANCE IN JAVA
 Inheritance is one of the key features of Object Oriented
Programming.

 Inheritance provided mechanism that allowed a class to

m
www.youtube.com/@SravanKumarGurra
inherit properties of another class.

 When a Class extends another class it inherits all non-


private members including fields and methods.

 Inheritance in Java can be best understood in terms of


Parent and Child relationship, also known as Super
class(Parent) and Sub class(child) in Java language.
3
www.youtube.com/@SravanKumarGurra
m
4
m
www.youtube.com/@SravanKumarGurra
see how extends keyword is used to achieve
Inheritance. It shows super class and sub-class
relationship.

Now based on above example. In OOPs term we can


say that,
Vehicle is super class of Car.
5
Car is sub class of Vehicle.
www.youtube.com/@SravanKumarGurra
m
6
Parent method
Child method
Output:
FORMS OF INHERITANCE
 The inheritance concept used for the number of purposes
in the java programming language. One of the main
purposes is substitutability.

m
www.youtube.com/@SravanKumarGurra
 The substitutability means that when a child class
acquires properties from its parent class, the object of the
parent class may be substituted with the child class object.
For example, if B is a child class of A, anywhere we expect
an instance of A we can use an instance of B.

 The substitutability can achieve using inheritance,


whether using extends or implements keywords. 7
Different forms of inheritance in java
 Specialization

 Specification

m
www.youtube.com/@SravanKumarGurra
 Construction

 Extension

 Limitation

 Combination

8
Specialization:

 It is the most ideal form of inheritance.


The subclass is a special case of the parent class.

m
www.youtube.com/@SravanKumarGurra

 Ex1:

Parent Class: Vehicle


Child Class: Car
 Ex2:

Parent Class: B.Tech


Child Class: CSE 9
Specification:

 This is another commonly used form of


inheritance.

m
www.youtube.com/@SravanKumarGurra
 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. 10
Construction:
 This is another form of inheritance where the child
class may change the behavior defined by the

m
www.youtube.com/@SravanKumarGurra
parent class (overriding).

Extension
 This is another form of inheritance where the child
class may add its new properties.

11
Limitation

 This is another form of inheritance where the subclass restricts


the inherited behavior.
 The final keyword in java is used to restrict the user. The java

m
www.youtube.com/@SravanKumarGurra
final keyword can be used in many context. Final can be:
 Variable Ex: final int speedlimit=90; //final variable
 Method. If you make any method as final, you cannot
override it.
Ex: final void run()
{
System.out.println("running");
} 12
final class Bike
{
void run() {…..}
} Output:

class Honda1 extends Bike Compile Time Error


{

m
www.youtube.com/@SravanKumarGurra
void run( )
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[ ])


{
Honda1 honda= new Honda1();
honda.run(); 13
}
}
Combination

 This is another form of inheritance where the


subclass inherits properties from multiple

m
www.youtube.com/@SravanKumarGurra
parent classes.

 Java does not support multiple inheritance type


through classes.

14
www.youtube.com/@SravanKumarGurra
m
15
TYPES OF INHERITANCE
m
www.youtube.com/@SravanKumarGurra
Note: Multiple inheritance is not supported in
Java through class. 16
SINGLE INHERITANCE EXAMPLE
 When a class is created from single base class, it is
known as a single inheritance.

m
www.youtube.com/@SravanKumarGurra
Output:
a=10

17
MULTILEVEL INHERITANCE

 When a class extends to another class that also


extends some other class forms a multilevel

m
www.youtube.com/@SravanKumarGurra
inheritance.

 For example

a class C extends to class B that also extends to class


A and all the data members and methods of class A
and B are now accessible in class C.

18
www.youtube.com/@SravanKumarGurra
m
19
Output:
a=10
b=10
HIERARCHICAL INHERITANCE
When a class is extended by two or
more classes, it forms hierarchical
inheritance.
For example, class B extends to

m
www.youtube.com/@SravanKumarGurra
class A and class C also extends to
class A in that case both B and C
share properties of class A.

Output:
a = 10
a = 10 20
SUPER KEYWORD

 In Java, super keyword is used to refer to immediate


parent class of a child class.

m
www.youtube.com/@SravanKumarGurra
21
SUPER KEYWORD CONTD…

 The super keyword in Java is used in subclasses to access


superclass members (attributes, constructors and methods).

Uses of super keyword:

m
www.youtube.com/@SravanKumarGurra
 To call methods of the superclass that is overridden in the
subclass.

 To access attributes (fields) of the superclass if both


superclass and subclass have attributes with the same
name.

 To explicitly call superclass default constructor or


22
parameterized constructor from the subclass constructor.
Ex: Accessing Parent Class Method Using Super Keyword

class Animal
{
void eat()
{
System.out.println("Animal is eating");
}

m
www.youtube.com/@SravanKumarGurra
}

class Dog extends Animal


{
void eat()
{
System.out.println("Dog is eating");
}

void display()
{ 23
super.eat(); // Calls the parent class eat() method
}
Ex: Accessing Parent Class Method Using Super Keyword contd..

public static void main(String[] args)


{
Dog d = new Dog();
d.display();

m
www.youtube.com/@SravanKumarGurra
}
}
Output:
Animal is eating

24
Ex: Accessing Parent Class Field using Super keyword

class Animal
{ Output:
String color = “White"; Black
} White

class Dog extends Animal

m
www.youtube.com/@SravanKumarGurra
{
String color = “Black";

void printColor()
{
System.out.println(color); // Prints color of Dog class (black)
System.out.println(super.color); // Prints color of Animal class (white)
}

public static void main(String[] args)


{
Dog d = new Dog();
d.printColor(); 25
}
}
Ex: Accessing Parent Class Constructor Using Super keyword
class Animal
{
Animal() Output:
{ Animal is created
System.out.println("Animal is created"); Dog is created
}
}

m
www.youtube.com/@SravanKumarGurra
class Dog extends Animal
{
Dog()
{
super(); // Calls the parent class constructor
System.out.println("Dog is created");
}

public static void main(String[] args)


{
Dog d = new Dog();
} 26
}
www.youtube.com/@SravanKumarGurra
m
27
METHOD OVERRIDING IN JAVA

 Method overriding is a process of overriding base


class method by derived class method with more

m
www.youtube.com/@SravanKumarGurra
specific definition.

 It is performed between two classes using


inheritance relation.

 In overriding, method of both


class must have same name and equal number
of parameters and same type of the arguments.
28
METHOD OVERRIDING IN JAVA CONTD..

 Method overriding is also referred to as runtime


polymorphism because calling method is decided
by JVM during runtime.

m
www.youtube.com/@SravanKumarGurra
 The key benefit of overriding is the ability to define
method that's specific to a particular subclass
type.

29
RULES FOR METHOD OVERRIDING
 1. Method name must be same for both parent and child
classes.

 2. Private, final and static methods cannot be overridden.

m
www.youtube.com/@SravanKumarGurra
 3. There must be an IS-A relationship between classes
(inheritance).

 4. Access modifier of child method must not restrictive


than parent class method.

NOTE: Static methods cannot be overridden because, a


static method is bounded with class where as instance
30
method is bounded with object.
Output:

Dog like to eat meat

m
www.youtube.com/@SravanKumarGurra
As you can see here Dog class gives it own implementation of eat() method.
31
For method overriding, the method must have same name and same type
signature in both parent and child class.
class Animal
{
public void eat()
{
System.out.println("Eat all eatables");
}
}

m
www.youtube.com/@SravanKumarGurra
class Dog extends Animal
{
protected void eat() //error
{
System.out.println("Dog like to eat meat");
}

public static void main(String[] args)


{
Dog d = new Dog(); Output:
d.eat();
32
} Cannot reduce the visibility of the
} inherited method from Animal.
www.youtube.com/@SravanKumarGurra
m
33
USING FINAL WITH INHERITANCE

 When a class defined with final keyword, it


can not be extended by any other class.

m
www.youtube.com/@SravanKumarGurra
 simply we can’t create a child class for final
class.

34
Example program to implement final keyword with inheritance

final class ParentClass


{
int num = 10;
void showData()
{
System.out.println("Inside ParentClass showData() method");

m
www.youtube.com/@SravanKumarGurra
System.out.println("num = " + num);
}
}

class ChildClass extends ParentClass


{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();

} Error: 35
} ChildClass.java: error: cannot
inherit from final ParentClass
BENEFITS OF INHERITANCE IN JAVA
❖ The biggest advantage of inheritance is code
reusability, since the fields and methods of parent class
get's inherited in child class, the child class won't have to

m
www.youtube.com/@SravanKumarGurra
create it again. It can access those features of parent
class from the child class, that is what the code
reusability is.

❖ It also help's to reduce code redundancy. If


inheritance is not used, multiple classes may need to
write similar methods/logic in their body.
36
BENEFITS OF INHERITANCE IN JAVA CONTD..

❖ Another advantages of inheritance


is extensibility, you can add new features or
change the existing features easily in subclasses.

m
www.youtube.com/@SravanKumarGurra
❖ Using inheritance we can achieve runtime
polymorphism(method overriding).

❖ Inheritance makes easy to maintain the code, as


the common codes are written at one place.

37
COSTS OF INHERITANCE/DISADVANTAGES

❖ No Independence:

One of the main disadvantages of Inheritance in Java

m
www.youtube.com/@SravanKumarGurra
is that two classes, both the base and inherited class,
get tightly bounded by each other.

In simple terms, Programmers can not use these


classes independently of each other.

38
COSTS OF INHERITANCE/DISADVANTAGES
CONTD..

❖ Decreases Execution Speed: Another cost of


Inheritance is that it decreases the execution

m
www.youtube.com/@SravanKumarGurra
speed because Inheritance execution takes time
and effort.

❖ Refactoring the Code: If the user deletes the


Super Class, then they have to refactor it if they
have used it.

39
www.youtube.com/@SravanKumarGurram
CHAPTER-2
PACKAGES
40
JAVA PACKAGE
 Package is a collection of related classes. Java uses
package to group related classes, interfaces and sub-
packages in any Java project.

m
www.youtube.com/@SravanKumarGurra
 We can assume package as a folder or a directory
that is used to store similar files.
 In Java, packages are used to avoid name conflicts
and to control access of class, interface etc.
 Using package it becomes easier to locate the related
classes and it also provides a good structure for projects
41
with hundreds of classes and other files.
TYPES OF JAVA PACKAGE

 Package can be built-in and user-defined, Java


provides rich set of built-in packages.

m
www.youtube.com/@SravanKumarGurra
 Built-in Package: java.util, java.lang, java.io etc
are the example of built-in packages.

 User-defined-package: Java package created by


user to categorize their project's classes and
interface are known as user-defined packages

42
m
www.youtube.com/@SravanKumarGurra
Hierarchy of Java Built-in Packages

43
HOW TO IMPORT JAVA PACKAGE
 To import java package into a class, we need to use
java import keyword which is used to access package and
its classes into the java program.

m
www.youtube.com/@SravanKumarGurra
 Use import keyword to access built-in and user-defined
packages into your java source file so that your class can
refer to a class that is in another package by directly using
its name.
 import package with specified class
import PackageName.ClassName;
 import package with all classes
44
import PackageName.*;
HOW TO CREATE A USER DEFINED PACKAGE

 Creating a package in java is quite easy,


simply include a package command followed

m
www.youtube.com/@SravanKumarGurra
by name of the package as the first
statement in java source file.

45
ADDITIONAL POINTS ABOUT PACKAGE:
 Package statement must be first statement in the
program even before the import statement.

m
www.youtube.com/@SravanKumarGurra
 Store all the classes in that package folder.

 All classes of the package which we wish to


access outside the package must be declared
public.

 All classes of the package must be compiled


before use.
46
How to compile Java programs inside packages?
This is just like compiling a normal java program.

javac -d . ClassName.java

m
www.youtube.com/@SravanKumarGurra
The -d specifies the destination where to put the
generated class file.

You can use any directory name like d:/abc (in case
of windows) etc.

If you want to keep the package within the same


directory, you can use . (dot)

47
//save by Demo.java
package pack; //Creating a package pack
public class Demo
{ Step-1: Compile Demo.java
public void msg() javac –d . Demo.java
{
Step-2: write the code Test.java
System.out.println("Hello"); code in a new file
}

m
www.youtube.com/@SravanKumarGurra
} Step-3: run Test.java

//save by Test.java
import pack.Demo; //Importing Demo class from pack Packages
class Test
{
public static void main(String args[])
{
Demo obj = new Demo();
obj.msg();
} Output: 48
} Hello
JAVA ABSTRACT CLASS AND METHODS
 A class which is declared using abstract
keyword known as abstract class. We cannot create
object for the abstract class.

m
www.youtube.com/@SravanKumarGurra
 It is used to achieve abstraction but it does not provide
100% abstraction because it can have Non-Abstract
methods also.
 It can have abstract and non-abstract methods.
 Syntax: abstract class class_name
{
.......
49
}
EX: ABSTRACT CLASS DECLARATION

//Declaration using abstract keyword


abstract class A
{

m
www.youtube.com/@SravanKumarGurra
//This is abstract method
abstract void myMethod(); // doesn’t have a body

void anotherMethod() // Non-Abstract method


{
//Does something
}
} 50
ABSTRACT METHOD
 Method that are declared without any body within an abstract
class are called abstract method.
 Use abstract keyword to create abstract method.

m
www.youtube.com/@SravanKumarGurra
 Abstract method can never be final.
 Any class that extends an abstract class must implement all the
abstract methods.
 If any class has even a single abstract method, then it must be
declared abstract.
Syntax:
 abstract return_type Method_name ();
//No definition 51
WHY WE NEED AN ABSTRACT CLASS?

 Lets say we have a class Animal that has a


method sound() and the subclasses(inheritance) of it
like Dog, Lion, Horse, Cat etc.

m
www.youtube.com/@SravanKumarGurra
 Since the animal sound differs from one animal to another,
there is no point to implement this method in parent class.

 This is because every child class must override this


method to give its own implementation details,
like Lion class will say “Roar” in this method
and Dog class will say “Woof”.
52
Program to implement abstract class and abstract method

//abstract parent class


abstract class Animal
{
//abstract method
public abstract void sound();
}
Output:

m
www.youtube.com/@SravanKumarGurra
//Dog class extends Animal class
public class Dog extends Animal Woof
{

public void sound()


{
System.out.println("Woof");
}
public static void main(String args[])
{
Dog obj = new Dog();
obj.sound(); 53
}
}
www.youtube.com/@SravanKumarGurram
INTERFACES
CHAPTER-3

54
JAVA INTERFACES
 Interface is a concept which is used to achieve
abstraction in Java. This is the only way by which we
can achieve full abstraction.
Interfaces are syntactically similar to classes, but you

m
www.youtube.com/@SravanKumarGurra

cannot create instance of an Interface and their


methods are declared without any body.
 It can have When you create an interface it defines what
a class can do without saying anything about how the
class will do it.
 When an interface inherits another
interface extends keyword is used whereas class
55
use implements keyword to inherit an interface.
www.youtube.com/@SravanKumarGurra
m
56
Advantages of Interface:

 It Support multiple inheritance

 It helps to achieve 100% abstraction

• All methods declared inside interfaces are

m
www.youtube.com/@SravanKumarGurra
implicitly public and abstract, even if you don't
use public or abstract keyword.

• Interface cannot implement a class.

57
m
www.youtube.com/@SravanKumarGurra
NOTE:
Compiler automatically converts methods of
Interface as public and abstract.

58
Program to implement interface

Output:
Average speed is 40.

m
www.youtube.com/@SravanKumarGurra
59
MULTIPLE INHERITANCE IN JAVA BY
INTERFACE

 If a class implements multiple interfaces, or an


interface extends multiple interfaces, it is known as
multiple inheritance.

m
www.youtube.com/@SravanKumarGurra
60
interface Printable
{ Ex_1: Program to implement Multiple
void print(); inheritance
}
interface Showable Interface Interface
{
void show();
}
class A7 implements Printable,Showable

m
www.youtube.com/@SravanKumarGurra
{ Class
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome"); Output:
}
public static void main(String args[]) Hello
{ Welcome
A7 obj = new A7();
obj.print(); 61
obj.show();
} }
// Base class Ex_2: Program to implement Multiple
class Animal { inheritance
void eat() {
System.out.println("Animal is eating");
}
}
Class Interface
// Interface
interface Pet {

m
www.youtube.com/@SravanKumarGurra
void play();
}
Class
// Derived class
class Dog extends Animal implements Pet {
public void play() {
System.out.println("Dog is playing");
} Output:
Animal is eating
public static void main(String[] args) { Dog is playing
Dog d = new Dog();
d.eat(); // Calls method from Animal class
d.play(); // Calls method from Pet interface 62
}
}
NESTED INTERFACES
 An interface, declared within another interface
or class, is known as a nested interface.

m
www.youtube.com/@SravanKumarGurra
 The nested interfaces are used to group related
interfaces so that they can be easy to maintain.

 The nested interface must be referred to by the


outer interface or class. It can't be accessed
directly.

63
NESTED INTERFACES
Syntax:

interface interface_name // Outer Interface

m
www.youtube.com/@SravanKumarGurra
{
...
interface nested_interface_name // Inner Interface
{
...
}
}

64
Example Program to implement Nested Interface.
Create an interface within the class
class OuterClass{ Output:
This is InnerInterface
interface InnerInterface{ method
void innerMethod();
}
}

m
www.youtube.com/@SravanKumarGurra
class ImplementingClass implements OuterClass.InnerInterface
{
public void innerMethod() {
System.out.println("This is InnerInterface method");
}
}
public class NestedInterfaceExample {

public static void main(String[] args) {


ImplementingClass obj = new ImplementingClass();
obj.innerMethod();
65
}
}
public interface OuterInterface {
Example Program to
void outerMethod();
implement Nested Interface.
Create an interface within the
interface InnerInterface {
another interface
void innerMethod();
}
}

// Implementing both interfaces

m
www.youtube.com/@SravanKumarGurra
class ImplementingClass implements OuterInterface,
OuterInterface.InnerInterface {
public void outerMethod() {
System.out.println("Outer method implementation");
}

public void innerMethod() {


System.out.println("Inner method implementation");
}

public static void main(String[] args) {


ImplementingClass obj = new ImplementingClass();
obj.outerMethod(); // Output: Outer method implementation 66

obj.innerMethod(); // Output: Inner method implementation


}}
EXTENDING INTERFACES

 In java, an interface can extend another interface.

 When an interface wants to extend another interface,


it uses the keyword extends.

m
www.youtube.com/@SravanKumarGurra
 The interface that extends another interface has its
own members and all the members defined in its
parent interface too.

 The class which implements a child interface needs


to provide code for the methods defined in both child
and parent interfaces 67
Example Program to implement Extended Interface

interface ParentInterface
{
void parentMethod();
}

m
www.youtube.com/@SravanKumarGurra
interface ChildInterface extends ParentInterface
{
void childMethod(); Parent Interface
}

child Interface

68
Implementing
Class
Example Program to implement Extended Interface Contd..

class ImplementingClass implements ChildInterface


{

public void childMethod()


{

m
www.youtube.com/@SravanKumarGurra
System.out.println("Child Interface method");
}

public void parentMethod()


{
System.out.println("Parent Interface mehtod");
}
69
}
Example Program to implement Extended Interface Contd..

public class ExtendingAnInterface


{

public static void main(String[] args)


{

m
www.youtube.com/@SravanKumarGurra
ImplementingClass obj = new
ImplementingClass();

obj.childMethod();
obj.parentMethod();

} Output:
Child Interface Method 70

} Parent Interface Method


VARIABLES IN INTERFACES

 By default variables in interface are public static


final.
 public: for the accessibility across all the classes, just
like the methods present in the interface

m
www.youtube.com/@SravanKumarGurra
 Interface variables are static because java interfaces
cannot be instantiated on their own. The value of the
variable must be assigned in a static context in which
no instance exists.
 The final modifier ensures the value assigned to the
interface variable is a true constant that cannot be re-
assigned. In other words, interfaces can declare only
71
constants, not instance variables.
interface Moveable
{
int AVG_SPEED = 40; // Implicitly public, static and final
void move();
}

class Vehicle implements Moveable


{
public void move()

m
www.youtube.com/@SravanKumarGurra
{
AVG_SPEED = 50;
System .out. println("Average speed is"+AVG_SPEED);
}
public static void main (String[] arg)
{
Vehicle vc = new Vehicle();
vc.move();
}
}
Output:
Error: 72
Vehicle.java:11: error: cannot assign a value to final variable
AVG_SPEED
I/O STREAMS: JAVA.IO
Accept input from the user
 InputStreamReader Class

www.youtube.com/@SravanKumarGurram
 BufferedReader Class

 We use mainly these two methods

 read ( )Used for reading a single character.

 readLine( )Reads one complete line/Strings.

73
Output:Enter your name Amit Welcome Amit
Output:
import java.io.*;
class Input Enter your name Bose
Welcome Bose
{
public static void main(String args[]) throws Exception
{

m
www.youtube.com/@SravanKumarGurra
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);
74
}
}
www.youtube.com/@SravanKumarGurra
m
75
READING INPUT WITH
JAVA.UTIL.SCANNER CLASS
 We Can use Scanner Class of java.util package to read input
from the keyboard.

m
www.youtube.com/@SravanKumarGurra
 When the Scanner Class receives input, it breaks the input
into several pieces, called tokens.
 These tokens can be retrieved from the Scanner Object using
the following methods
 nextLine( ) ---- to read a string
 nextInt( ) ----- to read Int Values
 nextFloat( ) ----- to read Float Values
 next().charAt(0) ---- to read Char value 76
import java.util.Scanner; Java Program to implement Scanner to class
to read String, int and double values
class InputScan
{
public static void main(String[ ] args)
{
Scanner sc = new Scanner(System.in);

m
www.youtube.com/@SravanKumarGurra
System.out.println("Enter name, age and salary:");

// String input
String name = sc.nextLine(); Output:
Enter name, age and salary:
// Numerical input Ramu
int age = sc.nextInt(); 25
double salary = sc.nextDouble(); 6.5

// Output statements Name: Ramu


System.out.println("Name: " + name); Age: 25
System.out.println("Age: " + age); Salary: 6.5
System.out.println("Salary: " + salary); 77
}
}
Java Program to implement Scanner to class
to read String, int and double values

import java.util.Scanner;
public class ReadCharacter
{

m
www.youtube.com/@SravanKumarGurra
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);
System.out.println("You entered: " + ch);
} 78

}
JAVA FILE CLASS

 The File class of the java.io package is used to perform


various operations on files and directories.

m
www.youtube.com/@SravanKumarGurra
 A file is a named location that can be used to store
related information.

 For example, sample.java is a Java file that contains


information about the Java program.

 A directory is a collection of files and subdirectories.

 A directory inside a directory is known as subdirectory


79
CREATE A JAVA FILE OBJECT
 To create an object of File, we need to import the java.io.
package first. Then create objects of File

// creates an object of File using the path

m
www.youtube.com/@SravanKumarGurra
 File fileObj = new File(String pathName);

 Here, we have created a file object named fileObj.

 The object can be used to work with files and directories.

 Note: In Java, creating a file object does not mean


creating a file. Instead, a file object is an abstract
representation of the file or directory pathname (specified
80
in the parenthesis).
JAVA FILE OPERATION METHODS

Package and
Operation Method
class

m
www.youtube.com/@SravanKumarGurra
To create file createNewFile() java.io.File

To read file read() java.io.FileReader

To write file write() java.io.FileWriter

To delete file delete() java.io.File

81
JAVA CREATE FILES

 To create a new file, we can use the


createNewFile() method.

m
www.youtube.com/@SravanKumarGurra
 It returns true if a new file is created.

 false if the file already exists in the specified


location.

82
// importing the File class
import java.io.File;

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

// create a file object for the current location


File file = new File("newFile.txt");

m
www.youtube.com/@SravanKumarGurra
try {

// trying to create a file based on the object


boolean value = file.createNewFile();
if (value==true) {
System.out.println("The new file is created.");
}
else {
System.out.println("The file already exists.");
}
}
catch(Exception e) {
83
e.getStackTrace();
}
}}
EXPLANATION ABOUT THE PROGRAM
 we have created a file object named file. The file
object is linked with the specified file path.

 File file = new File("newFile.txt");

m
www.youtube.com/@SravanKumarGurra
 Here, we have used the file object to create the new
file with the specified path.

 If newFile.txt doesn't exist in the current location, the


file is created and this message is shown.
The new file is created.
 However, if newFile.txt already exists, we will see
this message.
The file already exists. 84
// importing the FileReader class READ A FILE USING
import java.io.FileReader; FILEREADER
class Main {
public static void main(String[] args) {
Output:
char[] array = new char[100]; Content of the
try { file will be
// Creates a reader using the FileReader

m
www.youtube.com/@SravanKumarGurra
displayed as an
FileReader input = new FileReader("input.txt"); output of this
program
// Reads characters
input.read(array);
System.out.println("Data in the file:");
System.out.println(array);

// Closes the reader


input.close();
}
catch(Exception e) {
e.getStackTrace();
85
}
}
}
// importing the FileWriter class Example: Write to file using
import java.io.FileWriter; FileWriter
class Main {
public static void main(String args[]) {

String data = "This is the data in the output file";


try {

m
www.youtube.com/@SravanKumarGurra
// Creates a Writer using FileWriter
FileWriter output = new FileWriter("output.txt");

// Writes string to the file


output.write(data);
System.out.println("Data is written to the file.");

// Closes the writer


output.close();
}
Output:
catch (Exception e) {
e.getStackTrace(); Data is written to the file.
} 86
}
}

You might also like