0% found this document useful (0 votes)
4 views50 pages

Java Unit-2

Hi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views50 pages

Java Unit-2

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

OOP THROUGH JAVA

CSE II-I
BY
Dr.N.Lingareddy
Associate professor
UNIT-II
Java Inheritance Basics
Inheritance Concept
The inheritance is a very useful and powerful concept of object-oriented programming. In java, using the
inheritance concept, we can use the existing features of one class in another class. The inheritance
provides a greate advantage called code re-usability. With the help of code re-usability, the commonly
used code in an application need not be written again and again.
The inheritance can be defined as follows.
The inheritance is the process of acquiring the properties of one class to another class.

Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class, superclass, and
subclass.
The Parent class is the class which provides features to another class. The parent class is also known
as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also known
as the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the parent class never
acquires the features from its child class.

There are five types of inheritances, and they are as follows.

 Simple Inheritance (or) Single Inheritance


 Multiple Inheritance
 Multi-Level Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance
The following picture illustrates how various inheritances are implemented.

The java programming language does not support multiple inheritance type. However, it
provides an alternate with the concept of interfaces.

Creating Child Class in java


In java, we use the keyword extends to create a child class. The following syntax used
to create a child class in java.

Syntax
class <ChildClassName> extends <ParentClassName>{
...
//Implementation of child class
...
}

In a java programming language, a class extends only one class. Extending multiple
classes is not allowed in java.

Let's look at individual inheritance types and how they get implemented in java with an
example.

Single Inheritance in java


In this type of inheritance, one child class derives from one parent class. Look at the
following example code.

Example

class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Value of a is " + a);
}
}
public class SingleInheritance {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.setData(100);
obj.showData();

Multi-level Inheritance in java


In this type of inheritance, the child class derives from a class which already derived from another class.
Look at the following example java code.

Example

class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Value of a is " + a);
}
}
class ChildChildClass extends ChildClass{
void display() {
System.out.println("Inside ChildChildClass!");
}
}
public class MultipleInheritance {

public static void main(String[] args) {

ChildChildClass obj = new ChildChildClass();


obj.setData(100);
obj.showData();
obj.display();

}
Hierarchical Inheritance in java
In this type of inheritance, two or more child classes derive from one parent class. Look
at the following example java code.

Example

class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Inside ChildClass!");
System.out.println("Value of a is " + a);
}
}
class ChildClassToo extends ParentClass{
void display() {
System.out.println("Inside ChildClassToo!");
System.out.println("Value of a is " + a);
}
}
public class HierarchicalInheritance {

public static void main(String[] args) {

ChildClass child_obj = new ChildClass();


child_obj.setData(100);
child_obj.showData();

ChildClassToo childToo_obj = new ChildClassToo();


childToo_obj.setData(200);
childToo_obj.display();

Hybrid Inheritance in java


The hybrid inheritance is the combination of more than one type of inheritance. We may
use any combination as a single with multiple inheritances, multi-level with multiple
inheritances, etc.,

Java Constructors in Inheritance


It is very important to understand how the constructors get executed in the inheritance concept. In the
inheritance, the constructors never get inherited to any child class.
In java, the default constructor of a parent class called automatically by the constructor of its child class.
That means when we create an object of the child class, the parent class constructor executed, followed
by the child class constructor executed.
Let's look at the following example java code.

Example
class ParentClass{
int a;
ParentClass(){
System.out.println("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass{

ChildClass(){
System.out.println("Inside ChildClass constructor!!");
}
}
class ChildChildClass extends ChildClass{

ChildChildClass(){
System.out.println("Inside ChildChildClass constructor!!");
}
}
public class ConstructorInInheritance {

public static void main(String[] args) {

ChildChildClass obj = new ChildChildClass();

Java Access Modifiers


In Java, the access specifiers (also known as access modifiers) used to restrict the scope or
accessibility of a class, constructor, variable, method or data member of class and interface. There are
four access specifiers, and their list is below.

 default (or) no modifier


 public
 protected
 private

In java, we can not employ all access specifiers on everything. The following table describes where we
can apply the access specifiers.
Let's look at the following example java code, which generates an error because a class does not allow
private access specifier unless it is an inner class.

Example
private class Sample{
...
}

In java, the accessibility of the members of a class or interface depends on its access specifiers. The
following table provides information about the visibility of both data members and methods.
The public members can be accessed everywhere.
🔔 The private members can be accessed only inside the same class.
🔔 The protected members are accessible to every child class (same package or other
packages).
🔔 The default members are accessible within the same package but not outside the
package.

Let's look at the following example java code.

Example
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

class ChildClass extends ParentClass{

void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}

}
public class AccessModifiersExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.showData();
obj.accessData();

Java Forms of Inheritance


The inheritance concept used for the number of purposes in the java programming language. One of the
main purposes is substitutability. 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.
The following are the differnt forms of inheritance in java.

 Specialization
 Specification
 Construction
 Eextension
 Limitation
 Combination

Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It holds the
principle of substitutability.

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.

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.

Eextension
This is another form of inheritance where the child class may add its new properties. It holds the
principle of substitutability.

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

Combination
This is another form of inheritance where the subclass inherits properties from multiple parent classes.
Java does not support multiple inheritance type.

Benefits and Costs of Inheritance in


java
The inheritance is the core and more usful concept Object Oriented Programming. It proWith
inheritance, we will be able to override the methods of the base class so that the meaningful
implementation of the base class method can be designed in the derived class. An inheritance leads to
less development and maintenance costs.vides lot of benefits and few of them are listed below.
Benefits of Inheritance
 Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.
 Inheritance can save time and effort as the main code need not be written again.
 Inheritance provides a clear model structure which is easy to understand.
 An inheritance leads to less development and maintenance costs.
 With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class. An
inheritance leads to less development and maintenance costs.
 In inheritance base class can decide to keep some data private so that it cannot be altered by
the derived class.

Costs of Inheritance
 Inheritance decreases the execution speed due to the increased time and effort it takes, the
program to jump through all the levels of overloaded classes.
 Inheritance makes the two classes (base and inherited class) get tightly coupled. This means
one cannot be used independently of each other.
 The changes made in the parent class will affect the behavior of child class too.
 The overuse of inheritance makes the program more complex.

Java super keyword


In java, super is a keyword used to refers to the parent class object. The super keyword came into
existence to solve the naming conflicts in the inheritance. When both parent class and child class have
members with the same name, then the super keyword is used to refer to the parent class version.
In java, the super keyword is used for the following purposes.

 To refer parent class data members


 To refer parent class methods
 To call parent class constructor

🔔 The super keyword is used inside the child class only.

super to refer parent class data members


When both parent class and child class have data members with the same name, then the super
keyword is used to refer to the parent class data member from child class.
Let's look at the following example java code.

Example

class ParentClass{

int num = 10;


}

class ChildClass extends ParentClass{

int num = 20;

void showData() {
System.out.println("Inside the ChildClass");
System.out.println("ChildClass num = " + num);
System.out.println("ParentClass num = " + super.num);
}
}

public class SuperKeywordExample {

public static void main(String[] args) {


ChildClass obj = new ChildClass();

obj.showData();

System.out.println("\nInside the non-child class");


System.out.println("ChildClass num = " + obj.num);
//System.out.println("ParentClass num = " + super.num); //super can't be used here

super to refer parent class method


When both parent class and child class have method with the same name, then the
super keyword is used to refer to the parent class method from child class.
Let's look at the following example java code.

Example

class ParentClass{
int num1 = 10;

void showData() {
System.out.println("\nInside the ParentClass showData method");
System.out.println("ChildClass num = " + num1);
}
}

class ChildClass extends ParentClass{

int num2 = 20;

void showData() {
System.out.println("\nInside the ChildClass showData method");
System.out.println("ChildClass num = " + num2);

super.showData();

}
}

public class SuperKeywordExample {

public static void main(String[] args) {


ChildClass obj = new ChildClass();

obj.showData();
//super.showData(); // super can't be used here

}
}
super to call parent class constructor
When an object of child class is created, it automatically calls the parent class default-
constructor before it's own. But, the parameterized constructor of parent class must be
called explicitly using the super keyword inside the child class constructor.
Let's look at the following example java code.

Example

class ParentClass{

int num1;

ParentClass(){
System.out.println("\nInside the ParentClass default constructor");
num1 = 10;
}

ParentClass(int value){
System.out.println("\nInside the ParentClass parameterized
constructor");
num1 = value;
}
}

class ChildClass extends ParentClass{

int num2;

ChildClass(){
super(100);
System.out.println("\nInside the ChildClass constructor");
num2 = 200;
}
}

public class SuperKeywordExample {

public static void main(String[] args) {


ChildClass obj = new ChildClass();

}
}

Java final keyword


In java, the final is a keyword and it is used with the following things.

 With variable (to create constant)


 With method (to avoid method overriding)
 With class (to avoid inheritance)

Let's look at each of the above.

final with variables


When a variable defined with the final keyword, it becomes a constant, and it does not allow us to
modify the value. The variable defined with the final keyword allows only a one-time assignment, once a
value assigned to it, never allows us to change it again.
Let's look at the following example java code.

Example

public class FinalVariableExample {

public static void main(String[] args) {

final int a = 10;

System.out.println("a = " + a);

a = 100; // Can't be modified

}
final with methods
When a method defined with the final keyword, it does not allow it to override. The final
method extends to the child class, but the child class can not override or re-define it. It
must be used as it has implemented in the parent class.
Let's look at the following example java code.

Example

class ParentClass{

int num = 10;

final void showData() {


System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}

class ChildClass extends ParentClass{

void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}

public class FinalKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.showData();
}
}

final with class


When a class defined with final keyword, it can not be extended by any other class.
Let's look at the following example java code.

Example

final class ParentClass{

int num = 10;

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

class ChildClass extends ParentClass{

public class FinalKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

}
}
Java Pylymorphism
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.

There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here, we
will focus on runtime polymorphism in java.

Runtime Polymorphism in Java


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

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:

1. class A{}
2. class B extends A{}

1. A a=new B();//upcasting

For upcasting, we can use the reference variable of class type or an interface type. For
Example:

1. interface I{}
2. class A{}
3. class B extends A implements I{}

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and
overrides its run() method. We are calling the run method 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.

1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }

Java Runtime Polymorphism Example: Shape


1. class Shape{
2. void draw(){System.out.println("drawing...");}
3. }
4. class Rectangle extends Shape{
5. void draw(){System.out.println("drawing rectangle...");}
6. }
7. class Circle extends Shape{
8. void draw(){System.out.println("drawing circle...");}
9. }
10. class Triangle extends Shape{
11. void draw(){System.out.println("drawing triangle...");}
12. }
13. class TestPolymorphism2{
14. public static void main(String args[]){
15. Shape s;
16. s=new Rectangle();
17. s.draw();
18. s=new Circle();
19. s.draw();
20. s=new Triangle();
21. s.draw();
22. }
23. }
Output:

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

Java Method Overriding


The method overriding is the process of re-defining a method in a child class that is already defined in
the parent class. When both parent and child classes have the same method, then that method is said to
be the overriding method.
The method overriding enables the child class to change the implementation of the method which
aquired from parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time. The method binding
which happens at run time is known as late binding. So, the method overriding follows late binding.
The method overriding is also known as dynamic method dispatch or run time
polymorphism or pure polymorphism.
Let's look at the following example java code.

Example
class ParentClass{

int num = 10;

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

class ChildClass extends ParentClass{

void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}

public class PurePolymorphism {

public static void main(String[] args) {


ParentClass obj = new ParentClass();
obj.showData();

obj = new ChildClass();


obj.showData();

}
}

Interface in Java

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the methods declared in the interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

The relationship between classes and


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

Java Interface Example

In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Java Interface Example: Drawable

In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by someone else.
The implementation part is hidden by the user who uses the interface.

File: TestInterface1.java

1. //Interface declaration: by first user


2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
16. d.draw();
17. }}

Extending an Interface in java


In java, an interface can extend another interface. When an interface wants to extend another interface,
it uses the keyword extends. 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, otherwise, it needs to be
defined as abstract class.
🔔 An interface can extend another interface.
🔔 An interface can not extend multiple interfaces.
🔔 An interface can implement neither an interface nor a class.
🔔 The class that implements child interface needs to provide code for all the methods defined in both
child and parent interfaces.

Let's look at an example code to illustrate extending an interface.

Example
interface ParentInterface{
void parentMethod();
}

interface ChildInterface extends ParentInterface{


void childMethod();
}

class ImplementingClass implements ChildInterface{

public void childMethod() {


System.out.println("Child Interface method!!");
}

public void parentMethod() {


System.out.println("Parent Interface mehtod!");
}
}

public class ExtendingAnInterface {

public static void main(String[] args) {

ImplementingClass obj = new ImplementingClass();

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

}
Nested Interface in Java
Note: An interface can have another interface which is known as a nested interface. We
will learn it in detail in the nested classes chapter. For example:

1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }

Java Abstract Class


An abstract class is a class that created using abstract keyword. In other words, a class prefixed with
abstract keyword is known as an abstract class.
In java, an abstract class may contain abstract methods (methods without implementation) and also non-
abstract methods (methods with implementation).

Syntax
abstract class <ClassName>{
...
}

Let's look at the following example java code.

Example
import java.util.*;

abstract class Shape {


int length, breadth, radius;
Scanner input = new Scanner(System.in);

abstract void printArea();

}
class Rectangle extends Shape {
void printArea() {
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}

class Triangle extends Shape {


void printArea() {
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
}
}

class Cricle extends Shape {


void printArea() {
System.out.println("\n*** Finding the Area of Cricle ***");
System.out.print("Enter Radius: ");
radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius * radius);
}
}

public class AbstractClassExample {


public static void main(String[] args) {
Rectangle rec = new Rectangle();
rec.printArea();

Triangle tri = new Triangle();


tri.printArea();

Cricle cri = new Cricle();


cri.printArea();
}
}

An abstract class can not be instantiated but can be referenced. That means we can not create an
object of an abstract class, but base reference can be created.
In the above example program, the child class objects are created to invoke the overridden abstract
method. But we may also create base class reference and assign it with child class instance to invoke
the same. The main method of the above program can be written as follows that produce the same
output.

Example
public static void main(String[] args) {
Shape obj = new Rectangle(); //Base class reference to Child class instance
obj.printArea();

obj = new Triangle();


obj.printArea();

obj = new Cricle();


obj.printArea();
}

Rules for method overriding


An abstract class must follow the below list of rules.

 An abstract class must be created with abstract keyword.


 An abstract class can be created without any abstract method.
 An abstract class may contain abstract methods and non-abstract methods.
 An abstract class may contain final methods that can not be overridden.
 An abstract class may contain static methods, but the abstract method can not be static.
 An abstract class may have a constructor that gets executed when the child class object created.
 An abstract method must be overridden by the child class, otherwise, it must be defined as an
abstract class.
 An abstract class can not be instantiated but can be referenced.

Java Object Class


In java, the Object class is the super most class of any class hierarchy. The Object class in the java
programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't know. Because it is
the superclass of all other classes in java, it can refer to any type of object.
Methods of Object class
The following table depicts all built-in methods of Object class in java.

Return
Method Description Value

getClass() Returns Class class object object

hashCode() returns the hashcode number for object being used. int

equals(Object compares the argument object to calling object. boolean


obj)

clone() Compares two strings, ignoring case int

concat(String) Creates copy of invoking object object

toString() eturns the string representation of invoking object. String

notify() wakes up a thread, waiting on invoking object's monitor. void

notifyAll() wakes up all the threads, waiting on invoking object's monitor. void

wait() causes the current thread to wait, until another thread notifies. void

wait(long,int) causes the current thread to wait for the specified milliseconds and void
nanoseconds, until another thread notifies.

finalize() It is invoked by the garbage collector before an object is being garbage


collected.

JAVA - PACKAGES:

What is package:
Packages are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of
classes, interface, enumeration or sub-package.
Using package it becomes easier to locate the related classes and it also
provides a good structure for projects with hundreds of classes and other files.

Benefits of using package in java:


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
4) This packages can be provide reusability of code.
5) We can create our own package or extend already available package.

Java Packages: Types:


 Built-in Package: Existing Java package for
example java.lang, java.util ,java.io etc.
 User-defined-package: Java package created by user to categorize their
project's classes and interface.

How to Create a package:


Creating a package in java is quite easy. Simply include a package command followed by
name of the package as the first statement in java source file.

package mypackage;
public class student
{

Statement;
}

The above statement will create a package name mypackage in the project directory.
Java uses file system directories to store packages. For example the .java file for any class
you define to be part of mypackage package must be stored in

a directory called mypackage. Additional


points about package:

 A package is always defined as a separate folder having the same name as the
package name.
 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 within the package must have the package statement as its first line.
 All classes of the package must be compiled before use (So that they are error
free)
Example of Java packages:
Package mypack;

public class Simple

{
public static void main(String args[])

{
System.out.println("Welcome to package");
}
}

How to compile Java packages:


This is just like compiling a normal java program. If you are not using any IDE, you need
to follow the steps given below to successfully compile your packages:
1. java -d directory javafilename

For example

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).

How to run java package program:


You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java

To Run: java mypack.Simple

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.
}

How to access package from another


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

1. import package.*;
2. import package.classname;
3. fully qualified name.

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.

Example of package that import the


packagename.*:
//save by A.java
package
pack; public
class A

{
public void msg()

{
System.out.println("Hello java");}
}

//save by
B.java
package
mypack;
import pack.*;

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

{
A obj = new
A();
obj.msg();
}
}
Output: Hello java

2) Using packagename.classname:
If you import package.classname then only declared class of this package will be
accessible.

Example of package by import


package.classname:
//save by A.java

package pack;

public class A
{
public void msg()

{
System.out.println("Hello");}
}
}
//save by
B.java
package
mypack;
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.

Example of package by import fully qualified


name:
//save by A.java
package
pack; public
class A

{
public void msg()

{
System.out.println("Hello");}
}
}
//save by
B.java
package
mypack; class
B

{
public static void main(String args[])

}
}

{
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}

Output: Hello

Note: If you import a package, subpackages will not be imported.

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.

Subpackage in java:
Package inside the package is called the subpackage. It should be created to
categorize the package further.

Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as lang, net, io etc. and put
the Input/Output related classes in io package, Server and ServerSocket classes in net
packages and so on.

package com.javatpoint.core;

class Simple{

public static void main(String args[]){


System.out.println("Hello subpackage");

}
}
To Compile: javac -d . Simple.java
}
}

To Run: java com.javatpoint.core.Simple

Output: Hello subpackage

How to send the class file to another


directory or drive:
There is a scenario, I want to put the class file of A.java source file in classes folder of
c: drive.

For example:

//save as
Simple.java
package mypack;
public class
Simple

{
public static void main(String args[])

{
System.out.println("Welcome to package");
}
}

To Compile:

e:\sources> javac -d c:\classes

Simple.java To Run:

To run this program from e:\source directory, you need to set classpath of the directory

where the class file resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple


}
}

Another way to run this program by -


classpath switch of java:
The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch of java that
tells where to look for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple


Output: Welcome to package

Java.io package
Stream in java
In java, the IO operations are performed using the concept of streams. Generally, a
stream means a continuous flow of data. In java, a stream is a logical container of
data that allows us to read from and write to it. A stream can be linked to a data
source, or data destination, like a console, file or network connection by java IO
system. The stream-based IO operations are faster than normal IO operations.
The Stream is defined in the java.io package.
To understand the functionality of java streams, look at the following picture.

}
}

In java, the stream-based IO operations are performed using two separate streams
input stream and output stream. The input stream is used for input operations, and
the output stream is used for output operations. The java stream is composed of
bytes.
In Java, every program creates 3 streams automatically, and these streams are
attached to the console.

 System.out: standard output stream for console output operations.


 System.in: standard input stream for console input operations.
 System.err: standard error stream for console error output operations.

The Java streams support many different kinds of data, including simple bytes,
primitive data types, localized characters, and objects.
Java provides two types of streams, and they are as follows.

 Byte Stream
 Character Stream

The following picture shows how streams are categorized, and various built-in
classes used by the java IO system.

}
}

Both character and byte streams essentially provides a convenient and efficient way
to handle data streams in Java.
In the next tutorial, we will explore different types of streams in java.

Byte Stream in java


In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to
transmit 8 bits of data.
In Java 1.0 version all IO operations were byte oriented, there was no other stream
(character stream).
The java byte stream is defined by two abstract
classes, InputStream and OutputStream. The InputStream class used for byte
stream based input operations, and the OutputStream class used for byte stream
based output operations.
The InputStream and OutputStream classes have several concreate classes to
perform various IO operations based on the byte stream.
The following picture shows the classes used for byte stream operations.
}
}

InputStream class
The InputStream class has defined as an abstract class, and it has the following
methods which have implemented by its concrete classes.

S.No. Method with Description

1 int available()

It returns the number of bytes that can be read from the input stream.

2 int read()
It reads the next byte from the input stream.

3 int read(byte[] b)
}
}

S.No. Method with Description

It reads a chunk of bytes from the input stream and store them in its byte array, b.

4 void close()
It closes the input stream and also frees any resources connected with this input stream

OutputStream class
The OutputStream class has defined as an abstract class, and it has the following
methods which have implemented by its concrete classes.

S.No. Method with Description

1 void write(int n)

It writes byte(contained in an int) to the output stream.

2 void write(byte[] b)

It writes a whole byte array(b) to the output stream.

3 void flush()

It flushes the output steam by forcing out buffered bytes to be written out.

4 void close()

It closes the output stream and also frees any resources connected with this output strea

Reading data using BufferedInputStream


We can use the BufferedInputStream class to read data from the console. The
BufferedInputStream class use a method read( ) to read a value from the console, or
file, or} socket.
}

Let's look at an example code to illustrate reading data using BufferedInputStream.

Example 1 - Reading from console


import java.io.*;

public class ReadingDemo {

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

BufferedInputStream read = new


BufferedInputStream(System.in);

try {
System.out.print("Enter any character: ");
char c = (char)read.read();
System.out.println("You have entered '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
read.close();
}
}

o/p

}
}

Writing data using BufferedOutputStream


We can use the BufferedOutputStream class to write data into the console, file,
socket. The BufferedOutputStream class use a method write( ) to write data.
Let's look at an example code to illustrate writing data into a file using
BufferedOutputStream.

Example - Writing data into a file


import java.io.*;

public class WritingDemo {

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

String data = "Java tutorials by BTech Smart Class";


BufferedOutputStream out = null;
try {
FileOutputStream fileOutputStream = new
FileOutputStream(new File("C:\\Raja\\dataFile.txt"));
out = new BufferedOutputStream(fileOutputStream);

out.write(data.getBytes());
System.out.println("Writing data into a file is success!");

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

}
}

o/p

Character Stream in java


In java, when the IO stream manages 16-bit Unicode characters, it is called a
character stream. The unicode set is basically a type of character set where each
character corresponds to a specific numeric value within the given character set,
and every programming language has a character set.
In java, the character stream is a 16 bits carrier. The character stream in java allows
us to transmit 16 bits of data.
The character stream was introduced in Java 1.1 version. The charater stream

The java character stream is defined by two abstract classes, Reader and Writer.
The Reader class used for character stream based input operations, and the Writer
class used for charater stream based output operations.
The Reader and Writer classes have several concreate classes to perform various
IO operations based on the character stream.
}
}

The following picture shows the classes used for character stream operations.

Reader class
The Reader class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.

S.No
. Method with Description

1 int read()

It reads the next character from the input stream.

2 int read(char[] cbuffer)


It reads a chunk of charaters from the input stream and store them in its byte array, cbuffe

3 int read(char[] cbuf, int off, int len)


It reads charaters into a portion of an array.

4 int read(CharBuffer target)


}
}

S.No
. Method with Description

It reads charaters into into the specified character buffer.

5 String readLine()
It reads a line of text. A line is considered to be terminated by any oneof a line feed ('\n
return ('\r'), or a carriage returnfollowed immediately by a linefeed.

6 boolean ready()
It tells whether the stream is ready to be read.

7 void close()
It closes the input stream and also frees any resources connected with this input stream.

Writer class
The Writer class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.

S.No. Method with Description

1 void flush()

It flushes the output steam by forcing out buffered bytes to be written out.

2 void write(char[] cbuf)

It writes a whole array(cbuf) to the output stream.

3 void write(char[] cbuf, int off, int len)

It writes a portion of an array of characters.

4 void write(int c)

It writes single character.


}
}

S.No. Method with Description

5 void write(String str)

It writes a string.

6 void write(String str, int off, int len)

It writes a portion of a string.

7 Writer append(char c)

It appends the specified character to the writer.

8 Writer append(CharSequence csq)

It appends the specified character sequence to the writer

9 Writer append(CharSequence csq, int start, int end)

It appends a subsequence of the specified character sequence to the writer.

10 void close()

It closes the output stream and also frees any resources connected with this output strea

Reading data using BufferedReader


We can use the BufferedReader class to read data from the console. The
BufferedInputStream class needs InputStreamReaderclass. The BufferedReader
use a method read( ) to read a value from the console, or file, or socket.
Let's look at an example code to illustrate reading data using BufferedReader.

Example 1 - Reading from console


import java.io.*;
}
}

public class ReadingDemo {

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

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader in = new BufferedReader(isr);

String name = "";

System.out.print("Please enter your name: ");

name = in.readLine();

System.out.println("Hello, " + name + "!");


}
}

o/p

Writing data using FileWriter


We can use the FileWriter class to write data into the file. The FileWriter class use a
method write( ) to write data.
Let's look at an example code to illustrate writing data into a file using FileWriter.

Example - Writing data into a file


import java.io.*;

}
}

public class WritingDemo {

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

Writer out = new FileWriter("C:\\Raja\\dataFile.txt");

String msg = "The sample data";

try {
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}

o/p

You might also like