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

U3 Java

1. Polymorphism allows performing the same action in different forms. An example is a person taking on different roles like customer, employee, family member. 2. There are two types of polymorphism in Java - static (compile time) and dynamic (runtime). Static polymorphism includes method overloading while dynamic includes method overriding. 3. The final keyword can finalize classes, methods, and variables. Finalizing a class prevents inheritance, finalizing a variable makes it a constant, and finalizing a method prevents overriding in subclasses.

Uploaded by

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

U3 Java

1. Polymorphism allows performing the same action in different forms. An example is a person taking on different roles like customer, employee, family member. 2. There are two types of polymorphism in Java - static (compile time) and dynamic (runtime). Static polymorphism includes method overloading while dynamic includes method overriding. 3. The final keyword can finalize classes, methods, and variables. Finalizing a class prevents inheritance, finalizing a variable makes it a constant, and finalizing a method prevents overriding in subclasses.

Uploaded by

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

Page no- 1

UNIT-3, Polymorphism and Typecasting

Q). Polymorphism
The word polymorphism is a combination of two words i.e. ploy and morphs. The word poly
means many and morphs means different forms. In short, a mechanism by which we can perform a
single action in different ways.

Let's understand the meaning of polymorphism with a real-world example.

A person in a shop is a customer, in an office, he is an employee, in the home he is husband/


father/son, in a party he is guest. So, the same person possesses different roles in different places.
It is called polymorphism.

Polymorphism with Variables


When using variables, sometimes inherently the data type of the result is decided by the compiler
and accordingly execution proceeds. For example, in the statement:

System.out.println (a+b) ;

Java compiler decides the data type of the result of the expression a+b depending on the data
types of a and b. If a and b are int type, then a + b will also be taken as int type. If a and b are float
type variables, then a+b will be taken as float type. If a is int and b is float, then the compiler
converts a also into float and then sum is found. Thus, the result a + b is exhibiting polymorphic
nature. It may exist as an int or as a float or as some other data type depending on the context.
This is also called 'Coercion'.

Types of Polymorphism
There are two types of polymorphism in Java:
1. Static Polymorphism (Compile Time Polymorphism)
2. Dynamic Polymorphism (Run Time Polymorphism)

1. Static Polymorphism:
The polymorphism exhibited at compilation time is called static polymorphism. Polymorphism that
is resolved during compiler time is known as static polymorphism. Method overloading is an
example of compile time polymorphism.

1. Method overloading :

The process of defining methods with same name but with different functionalities is termed
method overloading.
To create an overloaded method, several different method definitions are created in the class with
the same name but with different parameter lists. Java differentiates overloaded methods based
on the number and type of parameters and not on the return type of the method.
A compiler error would occur when two methods with the same name and same parameter list
but different return types are created.

Example program for Method Overloading:

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 2

class MethodOverload
{
public static void first()
{
System.out.println("without any arguments");
}

public static void first(int a, int b)


{
System.out.println(a+b);
}

public static void main(String args[])


{
first();
first(10,20);
}
}

Output

2. Dynamic Polymorphism:
The polymorphism exhibited at runtime is called dynamic polymorphism. This means when a
method is called, the method call is bound to the method body at the time of running the
program, dynamically. In this case, Java compiler does not know which method is called at the
time of compilation. Only JVM knows at runtime which method is to be executed. Hence, this is
also called 'runtime polymorphism' or 'dynamic binding'.

1. Method Overriding:

Method overriding means both the super class method and sub class methods having the same
name, same signature. i.e., number of parameters and types of parameters should be same.
Method overriding is allowed only in inheritance. Method overriding is an example of
polymorphism.

//Java Program to illustrate the use of Java Method Overriding  
//Creating a parent class.  

class Vehicle
{  
 
  void run()  //defining a method  
{System.out.println("Vehicle is running");}  
}  
//Creating a child class  
class Bike2 extends Vehicle
{  
  
  void run() //defining the same method as in the parent class  
{System.out.println("Bike is running safely");}  
  
  public static void main(String args[])

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 3

{  
  Bike2 obj = new Bike2(); //creating object  
  obj.run(); //calling method  
  }  
}  

Output:
Bike is running safely
Bike is running safely

1. Polymorphism with Static Methods:

A static method is a method, one single copy in memory is shared by all the objects of the class. Static
methods belong to the class rather than to the objects. So they are also called class methods. When
static methods are overloaded or overridden, since they do not depend on the objects, the Java
compiler need not wait till the objects are created to understand which method is called.

Program: Write a program to use super class reference to call the calculate () method.

//static polymorphism

class One
{
static void calculate (double x)
{
system.out.println("square value="+(x*x));
}
}
class Two extends One
{
static void calculate (double x)
{
System.out.println("square root="+ Math.sqrt(x));
}
}

class Poly
{
public static void main(String args[])
{
one o= new Two ();
o.calculate (25);
}
}
Output:

C:\> javac poly.java


C:\>javac poly
square value =625.0

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 4

2. Polymorphism with Private Methods:

Private methods are the methods which are declared by using the access specifier 'private. This
method is not to be available outside the class. So other programmers cannot access the private
methods.

Even private methods are not available in the sub_classes. This means there is no possibility to
override the private methods of the super_class in its sub_classes. So only method overloading is
possible in case of private methods.

Example:
class Hello
{
private void call ()
{
system.out.println (“Hello world!”);
}
public static void main (String args [])
{
Hello h1=new Hello();
h1.call ();
}
}
Here in this code we have a private method -call() and we try to access this method under the main
method which lies in the same class Hello. Hence we get the desired output.

But if you try to call this private method - call() in some other class then you won't get the desired
output. Because when you write a method as private then it's accessibility is limited to that
particular class only.

3. Polymorphism with final methods and classes :

The Specifier final is used to finalize classes, methods and variables. Finalizing a thing effectively
'freezes the implementation or value of that thing. More specifically, here is how final works with
classes, variables and methods, respectively:

1. When the Specifier final is applied to a class, it means that the class cannot be inherited.
2. When final is applied to a variable, it means that the variable is constant.
3. When final is applied to a method in a class, it means that the method cannot be overridden in
the sub-classes. .

1. Finalizing classes:
In order to finalize a class, the Specifier final is added to the class definition. Typically, it is added
after protection Specifiers such as private (or) public. This is done as shown below:

public final class FinalClass1


{
………………
}
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 5

A class is declared final for the following reasons:


 To prevent inheritance
 For better efficiency. Final classes allow programmers to rely on instances of only that class
and optimize those instances

2. Finalizing variables:
The value of a finalized variable cannot be changed. It is then, effectively, a constant. To declare
constants in Java, final variables with initial values are used. This declaration can be done in a
program as follows:

public class FinalClass2


{
public static final int ConstantInteger = 100;
public final String ConstantString = “JAVA BOOK”;
}
Local variables (those inside blocks of code surrounded by braces; for example, in while or for
loops) cannot be declared final.

3. Finalizing methods:
Methods that cannot be overridden are known as finalized methods. The implementations of
final methods cannot be redefined in sub-classes. The syntax for declaring a method final is the
following.

public class FinalMethodClass


{
public final void One ()
{
……
}
}
Declaring methods final improves their efficiency.

Q). Explain about casting primitive data types?


Casting Primitive Data Types:

It is possible to convert one primitive data type into another primitive data type. This is done in
two ways, widening and narrowing. The primitive data types are classified into two types, lower
types and higher types naturally, the lower types are the types which use less memory and which
can represent lesser number of digits in the value. The higher types use more memory and can
represent more number of digits. To recognize the lower and higher types, the following diagram
is useful:

byte, short, char, int, long, float, double

Lower ------------------------------higher

Thus, char is a lower type than int. float is a higher type than long, boolean is not included earlier,
because it cannot be converted into any other type.

1. Widening in Primitive Data Types:

Converting a lower data type into a higher data type is called wide examples:

char ch = 'A' ;
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 6

int num= (int)ch; //num contains 65, the ASCII value

Here, we are converting char type variable 'ch' into used the cast operator by writing 'int' in the
simple. Now that ch is converted into int type, it can be is an example for widening.

int x=9500;

float sal = (float)x; //sal contains

Here, we are converting int type variable 'x' into float. So, we wrote (float) before the variable x.
Widening is safe because there will not be any loss of data or precision or accuracy.

2. Narrowing in Primitive Data Types:

Converting a higher data type into a lower data type is called 'narrowing'. Take the examples:

int n=66;

char ch= (char) n; //ch contains 'B'.

Here, we are converting int type n value into char type. The value of n is 66 which is when
converted into char type represents the character 'B', since 66 is the ASCII value of 'B'. This
character is stored into ch.

double d=12.6789; //n stores 12.


int n= (int) d:
Observe, we are converting double type into int type by using the cast operator (int) before the
variable d. The value in d is 12.6789. Since it is converted into int type, the fraction part of the
number is lost and only 12 is stored in n. Here, we are losing some digits. So narrowing is not
safe.

Q). Reference Type Casting


Objects of classes also can be type cast into objects of other classes when the source and
destination classes are related by inheritance and one class is a subclass of the other.

The type_cast can be to its own class type or to one of its subclass or super_class types or
interfaces. There are compile-time rules and runtime rules for casting in java. There are two types
of Reference Type Casting in Java, they are:

1. Up Type_casting
2. Down Type_casting

Up Type_casting is casting to a super_type, while down Type_casting is casting to a subtype.


Super Type_casting is always allowed, but sub Type_casting involves a type check and can throw a
ClassCastException.

1. Up Type_casting:

 A subtype object into a supertype and this is called up Type_cast. In Java, we need not add an
explicit cast and you can assign the object directly. Compiler will understand and cast the value to
supertype. By doing this, we are lifting an object to a generic level. If we prefer, we can add an

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 7

explicit cast and no issues.

2. Down Type_casting:

A  supertype to a subtype is called down Type_cast. This is the mostly done cast. By doing this we
are telling the compiler that the value stored in the base object is of a super type. Then we are
asking the runtime to assign the value. Because of down Type_cast, we get access to methods of
the subtype on that object. When performing down Type_casting, that you’re well aware of the
type of object you’ll be casting.

Q). Object class in Java


The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java. The Object class is beneficial if you want to refer any object whose type you
don't know. Notice that parent class reference variable can refer the child class object, known as
upcasting.

Let's take an example, there is getObject () method that returns an object but it can be of any type
like Employee, Student etc, we can use Object class reference to refer that object. For example:

Object obj=getObject (); //we don't know what object will be returned from this method  

The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Methods of Object class


The Object class provides many methods. They are as follows:

Method Description
public final Class getClass() returns the Class class object of this object. The Class
class can further be used to get the metadata of this
class.
public int hashCode() returns the hashcode number for this object.
public boolean equals() compares the given object to this object.
protected Object clone() creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
public final void wait(long timeout) causes the current thread to wait for the specified
milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).

protected void finalize() is invoked by the garbage collector before object is being
garbage collected.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 8

Abstract Classes & Interfaces

What is an abstract method and abstract class?

An abstract method does not contain any body. It contains only the method header, So we can say it
is an incomplete method. An abstract class is a class that generally contains some abstract methods.
Both the abstract class and the abstract methods should be declared by using the key word 'abstract'.

Abstract class in Java


A class which is declared as abstract keyword is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.

Points to Remember

1.An abstract class must be declared with an abstract keyword.


2.It can have abstract and non-abstract methods.
3.It cannot be instantiated.
4.It can have constructors and static methods also.
5.It can have final methods which will force the subclass not to change the body of the
method.
Example of abstract class

abstract class A
{

Abstract Methods:
A method which is declared as abstract and does not have implementation is known as an abstract
method.

abstract void printStatus(); //no method body and abstract 

 abstract keyword is used to declare the method as abstract.

 You have to place the abstract keyword before the method name in the method declaration.

 An abstract method contains a method signature, but no method body. Instead of curly braces
an abstract method will have a semoi colon(;) at the end.

Example program for Abstract Class and Methods:

In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 9

abstract class Bike
{  
  abstract void run();  
}  

class Honda4 extends Bike
{  
void run()
{
System.out.println("running safely");
}  

public static void main(String args[])
{  
 Bike obj = new Honda4();  
 obj.run();  
}  
}  

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 10

Interface in java

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.

Defining Interface

An interface is like a fully abstract class, except that it cannot have any concrete method (or)
instance variables. It is a collection of abstract method declarations and constants that is static
final variables.

 This means that interfaces do not specify any code to implement these methods.
 Any class that implements an interface must implement all of the methods specified in that
interface.
 A class can implement many interfaces but can extend only one class.

The general syntax for defining interface is:

interface InterfaceName
{
variable declaration;
method declaration;
}
Here interface is a keyword and interfaceName is any valid Java variable.

Example:
interface Item
{
static final int code = 1001;
static final String name = "fan";
void display();
}

 Variables are declared as constants using static final keywords.


 Note that the code for display() is not included in the interface. The class that implements this
interface must define the code for the method.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 11

Extending Interfaces

Interfaces can also be extended as a classes. The new sub_interface will inherit all the members of
the super_interface in the manner similar to subclasses.

interface ItemConstants
{
int code = 1000;
String name = "Fan";
}
interface Item extends ItemConstants
{
void display();
}
Output:

 While interfaces are allowed to extend to other interfaces, sub interfaces cannot define the
method declared in the super interface. Instead, it is the responsibility of any class that
implements the derived interface to define all the methods.
 Interfaces can have access Specifiers of public or blank, just like classes.
 An interface can be defined as extending another interface, similar to class hierarchy, but there is
no base interface analogous to the Object class.

Interface - Extending Interface:

import java.io.*;
interface inter1
{
int a = 100;
final static int b = 200;
}
interface inter2 extends inter1
{
void show();
}
class interclass implements inter2
{
public void show()
{
int c = a + b;
System.out.println("Sum="+c);
}
}
class ExtendingInterface
{
public static void main(String args[])
{
interclass obj = new interclass();
obj.show();
}
}
Output :

Implementing Interfaces
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 12

Interfaces are used as "superclasses" whose properties are inherited by classes. It is, therefore,
necessary to create that inherits the given interface.

class classname extends superclass


implements interface1, interface2,.............
{
}

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

Class can extend another class while implementing interface.

Implementing Interface:
import java.io.*;
interface inter //interface define
{
void show();
}
class interclass implements inter // implement the interface
{
public void show()
{
System.out.println("Hello Java - Interface");
}
}
class ImplementingInterface
{
public static void main(String args[])
{
interclass obj = new interclass();
obj.show();
}
}
Output:

Q). Implementing Multiple Inheritances using Interface:

Java does not support multiple inheritances. This means that a class cannot extend more than one
class. Therefore, following is illegal

public class extends Animal, Mammal{}

However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritance. The extends keyword is used once, and the parent interfaces are
declared in a comma-separated list.

For example, if the C interface extended both A and B, it would be declared as −

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 13

public interface C extends A, B

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as


multiple inheritance.

Example:
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A4 implements Printable, Showable
{
public void print()
{System.out.println("Hello");}
public void show()
{System.out.println("Welcome");}

public static void main(String args[])


{
A4 obj = new A4();
obj.print();
obj.show();
}
}

Q). Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface


1) Abstract class can have abstract and 1) Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.
2) Abstract class doesn't support 2) Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, non- 3) Interface has only static and final variables.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 14

final, static and non-static variables.


4) Abstract class can provide the 4) Interface can't provide the implementation
implementation of interface. of abstract class.
5) The abstract keyword is used to 5) The interface keyword is used to declare
declare abstract class. interface.
6) An abstract class can extend another 6) An interface can extend another Java
Java class and implement multiple interface only.
Java interfaces.
7) An abstract class can be extended 7) An interface can be implemented using
using keyword "extends". keyword "implements".
8) A Java abstract class can have class 8) Members of a Java interface are public by
members like private, protected, etc. default.
9) Example: 9) Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 15

PACKAGES
Packages (Putting classes together)

If we need to use classes from other programs without physically copying them into the program
under development, this can be accomplished in java by using packages a concept similar to “class
libraries” in another languages.

A package is a collection of related classes and interfaces. done according to functionality.


Packages are containers for classes.

1. Advantages of packages:

 The classes contained in the packages of other programs can be easily reused.

 Two classes in two different packages can have the same name. They can be uniquely
identified by packagename.classname.

 Packages provide a way to hide classes.

 Packages provide a way for separating design from coding.

Thus a Package is a collection of classes, interfaces and sub-packages. A Sub package in turns
divides into classes, interfaces and sub-sub-packages, etc.

Types of Packages:
In java the packages are classified into two categories. They are

1. Java API packages ( Predefined Packages)


2. User defined Packages.

1. Java API packages (or) Predefined Packages


Java API provides a large number of classes grouped into different packages according to
their functionalities. Most of the time we use the packages available with the Java API.
The packages are divided based on functionality as below.

Fig: Frequently used

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 16

They are shown in below.

Package Name Package Description


Java.lang.*; Language support classes. These are classes that java compiler itself uses
and therefore they are automatically imported. This package is default
package in java. They include classes for primitive types, strings, math
functions, threads and exceptions.
Java.util.*; Language support classes such as vectors, hash tables, date etc. This
package is used for developing quality or reliable applications in java. This
package contains various classes and interfaces which improves the
performance of J2ME applications.
Java.io.* Input and Output support classes. They provide facilities for the input and
output data.
Java.awt.* Set of classes for implementing graphical user interface. They include
(abstract window
classes for windows, buttons, lists, menus and so on.
toolkit)
Java.applet.*; Classes for creating and implementing applets. This package is used for
developing browser oriented applications. In other words this package is
used for developing distributed applications. An applet is a java program
which runs in the context of www or browser.
Java.net.*; Classes for networking. They include classes for communicating with local
computers as well as with internet servers. This package is used for
developing client server applications.

2. User defined packages:

User-defined packages are those packages that are designed (or) created by the developer
(user) to categorize classes and packages. They are much similar to the built-in that java
offers. It can be imported into other classes and used the same as we use built-in packages

Defining & Creating a package:

Creating our own packages (or) user defined packages involves the following steps:
Step1:
1. To create a package, simply include a package command as the first statement in a Java
source file. First declare the name of the package using package keyword followed by a
package name.

2. This must be first statement in java source file (except any comment or white spaces).

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 17

3. Any class you declare within that file will belong to the specified package.

Example: package mypack;

Step 2:

1. Next define the class that is to be put in the package and declare it as public.
package mypack; // package declaration
public class FirstClass // class definition
{
…………
………… // Body of class
…………
}

Step 3:
1. Now store the classname.java file as same as normal java programs save.
Step 4:
1. File is to be compiled as fallows.

Example: C:\> javac –d . FirstClass.java

Which creates FirstClass.class file and stores it in the mypack directory created under current
directory by -d. Java also supports the package hierarchy, which allows grouping related
classes into a package and then grouping related packages into a larger package. We can
achieve this by specifying multiple names in a package statement, separated by dot.

Using (or) Accessing Package

A java system package can be accessed either by using a fully qualified class name or by using
import statement. We generally use import statement.
Syntax:

Here pack1 is the top level package, pack2 is the package which is inside in pack1 and so on.
In this way we can have several packages in a package hierarchy. We should specify explicit

class name finally. Multiple import statements are valid. * indicates that the compiler should
search this entire package hierarchy when it encounters a class name.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 18

Explain about interfaces in a package?

It is also possible to write interfaces in a package. But whenever, we create an interface the
implementation classes are also should be created. We cannot create object to the interface
but we can create objects for implementation classes and use them. We write an interface to
display system date and time in the package mypack as shown in the following program.

Program: //Create MyDate interface in the package mypack

package mypack;
public interface MyDate
{
void showDate();
}
Output:
C:\> javac -d. MyDate.java

C:\>

Compile the preceding code and observe that the Java compiler creates a sub directory with the
name mypack and stores MyDate.class file there. This MyDate.class file denotes the byte code of
the interface.

Program: Write a program to create an implementation class for the MyDate interface with the
name DateImpl and storing it in the same package mypack.

//This is implementation class of MyDate interface

package mypack; //store DateImpl class also in mypack'


import my pack.MyDate;
import java.util.*;
public class DateImpl implementation MyDate
{
public void showDate()
{
Date d=new Date ();
System Out println(d);
}
}
Output:
C:\> javac -d. DateImpl.java
C:\>

When the preceding code in completed, Datelmpl.class file is created in the same package mypack.
Datelmpl class contained showDate () method which can be called and used in any other program.

Program: Write a program which shows how to use the Datelmpl which is an implementation class
of MyDate interface.

//Using the Datelmpl of mypack

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 19

import mypack.Datelmpl;
class DateDisplay
{
public static void main(String args[])
{
Datelmpl obj= new Datelmpl();
obj.showDate();
}
}

Output:

C:\> javac DateDisplay.java


C:\>java DateDisplay
Tue May 29 21:14:43 IST 2022

Q). How to creating sub package in a package? explain with examples?

Creating Sub Package in a Package

We can create sub package in a package in the format:

package pack1. pack2:

Here, we are creating pack2 which is created inside pack1. To use the classes and interfaces of pack2,
we can write import statement as:

import pack 1.pack2;

This concept can be extended to create several sub packages. In the following program we are
creating tech package inside dream package by writing the statement

package dream.tech;

Program: Let us make a program to learn how to create a sub package in a package.

//Creating a sub package tech in the package dream.

package dream.tech;
public class Sample
{
public void show ()
{
System.out.println ("welcome to Dream tech");
}
}
Output:
C:\>java -d. Sample.
C:\>

When the proceeding program is compiled, the Java compiler creates a sub directory with the name
dream. Inside this, there would be another sub directory with the name tech is created. In this tech
directory, Sample class is stored. Suppose the user wants to use the Sample class of dream.tech

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 20

package, he can write a statement as:

import dream.tech.Sample;

Program: Let us make a program using Sample class of dream.tech package.

//Using the package dream.tech


import dream.tech.Sample;
class Use
{
public static void main (String args[])
{
Sample s= new Sample ();
s.show();
}
}

Output:

C:\> javac Use.java


C:\>java Use
Welcome to Dream tech

Q). Access Specifiers in Java

There are two types of Specifiers in Java: access Specifiers and non-access Specifiers.

The access specifiers in Java specify the accessibility (or) scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access Specifier on it.

There are four types of Java access Specifiers:

1. Private:

The access level of a private specifier is only within the class. It cannot be accessed from
outside the class.

2. Default:

The access level of a default Specifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.

3. Protected:

The access level of a protected Specifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.

4. Public:

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 21

The access level of a public Specifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.

There are many non-access Specifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access Specifiers only.

Understanding Java Access Specifiers

Let's understand the access Specifiers in Java by a simple table.

Access within within outside package by outside


Specifier 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

Q). Creating API Document:

Application Programming Interface (API) document is a Hyper Text Markup language (html) file that
contains description of all the features of software, a product or a technology.

API document is like a reference manual that is useful to all the users of the product to understand all
the features and how to use them. For example, JavaSoft people have created API document
separately for the three parts, Java SE, Java EE and Java ME after they created Java language.

Every feature of Java language is described in API document. We can select any package, any class in
that package and the description of the class along with the fields, constructors, methods will appear.

When we click on any of these features, a detailed description of the feature is displayed. We can also
click on Index of the first row to see the index of all items in alphabetical order. Let us know how to
create an API document for any software:

1. First of all, we should copy all the source code files (.java) into a directory. For example, copy
APIDocEx .java of the package pack into a directory
e:\temp.

2. We should open each of the source code files and provide Java documentation comments by
using /** and */. When documentation comments are written, the APIDocEx .java files look like
shown here:

An example that shows document API


In this example; we can create a simple class that contains a documentation comment and shows how
to create a documented API.
package com.mypack;  
public Class APIDocEx   
{  
  public static void square(int x)   
  {  
   System.out.println(x * x);  
 }  

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 22

}  
Output
To create the document API, we need to use the javadoc tool as in the following.

 In a command prompt write the following:

 javadoc M.java

 
After generating the documented API. We will now see many HTML(browser) files created. Now we
need to open the index.html file to get the information about the classes. The figure below shows the
following.

Q). JAR Files in Java:

JAR (Java Archive) file is a file that contains compressed version of class files, audio files, image files
or directories. We can imagine a jar file as a zipped file (.zip) that is created by using WinZip software.
Even, WinZip software can be used to extract the contents of a jar file. The difference is that a jar file
can be used as it but whereas the .zip file cannot be used directly. The files should be extracted first
from a .zip file, and then used...

Creating a Jar file


You can create a Jar file using the jar command as shown below.
jar cf jar-file input-file(s)
Let us consider an example, create a Sample Java program with name Sample.java
Sample.java
public class Sample {
public static void main(String args[]){
System.out.println("Hi welcome to Tutorialspoint");
}
}

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 23

If you compile this program using Javac command as shown below −


C:\Examples >javac Sample.java
This command compiles the given java file and generates a .class file (byte code)

Now, create a jar file for the generated class as −


C:\Sample>jar cvf sample.jar *.class
added manifest
adding: Sample.class(in = 434) (out= 302)(deflated 30%)
This will generate a jar file for all the classes in the current directory (since we used * instead of name)
with specified name.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 24

Exceptions Handling

Error
It is common to make mistakes while developing as well as typing a program. A mistake leads to an
error. Errors are the wrongs that can make a program go wrong.

An error may produce an incorrect output (or) may terminate the execution of the program
abruptly (o)r even may cause the system to crash. It is therefore important to detect and manage
properly all the possible error condition in the program so that the program will not terminate or
crash during execution.

Types of Errors
Errors may broadly classified into two categories.
1. Compile-time errors
2. Run-time errors.
1. Compile-Time Errors
All syntax errors will be detected and displayed by the java compiler and therefore these errors
are known as compile-time errors. Whenever the compiler displays an error, it will not create the
.class file.

The following program is the illustration of Compile-time errors

Most of the compile time errors are due to typing mistakes. The most common problems:
 Missing semicolons
 Missing brackets in the classes and methods
 Misspelling of identifiers and keywords
 Missing of double quotes in strings
 Use of undeclared variables
 Incompatible types in assignment / initialization And so on
2. Runtime Errors
Sometimes, a program may compile successfully creating the .class file but may not run properly.
Such programs may produce wrong results due to wrong logic (or) may terminate due to errors
such as stack overflow. Most common Run-time errors are:
 Dividing an integer by zero
 Accessing an element that is out of the bounds of an array
 Trying to store a value into an array of an incompatible class or type
 Passing a parameter that is not in a valid range or value for a method
 Attempting to use a negative size of an array.
 Converting invalid string to a number
 Accessing a character that is out of bounds of a string

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 25

When such errors encountered, java typically generates an error message an aborts the program.
The following program is the illustration of Run-time errors.

Exception
An exception is a condition that is caused by a Run-Time Error in the program. When the java
interpreter encounters an error such as dividing an integer by zero, it creates an Exception Object
and throws it (i.e. informs us that an error has occurred).
 If the exception object is not caught and handled properly, the interpreter will display an
error message and will terminate the program.

 If we want the program to continue with exception of the remaining code, then we should
try to catch the exception object thrown by the error condition and then display an
appropriate message for taking corrective actions. This task is known as Exception Handling.

The purpose of exception handling mechanism is to provide a means to detect and report an
“Exceptional Circumstance” so that appropriate action can be taken.
Exception handling mechanism performs the following tasks:
 Find the problem ( Hit the exception)
 Inform that an error has occurred (throw the exception)
 Receive the error information (catch the exception)
 Take corrective actions (Handle exception)

The error handling mechanism code basically consists of two segments, one detect errors and to
throw exceptions and other to catch exceptions and to take appropriate actions.
Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 26

Suppose there are 10 statements in your program and there occurs an exception at statement 5,
the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform
exception handling, the rest of the statement will be executed. That is why we use exception
handling in Java.

Java exception handling is managed via 5 keywords, try, catch, throw, throws and finally. The
general form of exception handling block is

1. Try:

The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch (or) finally. It means, we can't use try block alone.

2. Catch:

The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.

3. Finally:

The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.

4. Throw:

The "throw" keyword is used to throw an exception.

5. Throws:

The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.

Syntax of Exception Handling Code


The basic concepts of exception handling are throwing an exception and catching it. This illustrates
in the following figure.

Fig: Exception handling mechanism

Java uses the keywords try and catch to handles the exceptions in the java programs.

The following table shows the some common errors that are occurred in the java programs.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 27

Exception Type Cause of Exception


1. ArithemeticException 1.Caused by the math errors such as division by zero.
2. ArrayIndexOutOfBoundsException 2.Caused by bad array indexes.
3. FileNotFoundException 3.Caused by an attempt to access a non existing file.
4. NumberFormatException 4.Caused when a conversion between strings and numbers fails.
5. IOException 5.Caused by general I/O failures

Exceptions in java can be categorized into two types.


1. Checked Exceptions:
These exceptions are explicitly handled in the code itself with the help of try-catch blocks.
Checked exceptions are extended from the java.lang.Exception class.
2. Unchecked Exceptions:

These exceptions are not essentially handled in the program code, instead the JVM handles
such exceptions. Unchecked exceptions are extended from the class
java.lang.RuntimeException.

Java Try Block and Catch Block:


Try Block:
Java uses the keyword try to preface a block of code that is likely to cause an error condition and
“throw” an exception. The try block can have one or more statements that could generate an
exception. If anyone statement generates an exception, the remaining statements in the block are
skipped and execution jumps to the catch block that is placed next to the try block.
catch Block
The catch block is defined by the keyword catch catches the exception thrown by the try block and
handles it appropriately. The catch block is added immediately after the try block. The catch block
can have one or more statements that are necessary to process the exception. The try statement
should be followed at least on catch statement; otherwise compilation error will occur.
catch statement works like method definition. It passed single parameter, which is reference to
exception object thrown (by the try block). If the catch parameter matches with the type of
exception object, then the exception is caught and the exception is handled otherwise program will
be terminated.

Syntax:
try
{
//Statements that causes Exception
}
catch(ExceptionType ex_ob)
{
//Statements that handle Exception
}

Example:
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 28

public class Testtrycatch2{


public static void main(String args[]){
try{
int data=50/0;
}
catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("rest of the code...");
}
}

Multiple catch Statements


Multiple catch statements handle the situation where more than one exception could be raised
by a single piece of code. In such situations specify two or more catch blocks, each specify
different type of exception.
Syntax:
……………………
……………………
try
{
Statements; // Generates an exception
}
catch ( Exception-type-1 e)
{
Statements; // Process exception type-1
}
catch ( Exception-type-2 e)
{
Statements; // Process exception type-2
}
:
:
catch ( Exception-type-N e)
{
Statements; // Process exception type-N
}
…………………………
…………………………
When exception in try block is generated, java checks exception object and catch block
parameter; if it matches, it will execute and remaining statements will be skipped.
Let's see a simple example of java multi-catch block.

Example:
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 29

{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
catch(Exception e)
{System.out.println("common task completed");}
System.out.println("rest of the code...");
} }
Output: task1 completed
rest of the code...

Finally Statement
finally creates a block of code that will be executed after a try/catch block has completed. The finally
block will execute whether or not an exception is thrown. If an exception is thrown, the finally block
will execute even if no catch statement matches the exception. It may be added immediately after the
try block or after the last catch block.
Syntax 1:
try
{
// statements
}
finally
{
// statements
}
Syntax 2:
try
{
// statements
}

catch (…………)
{
// statements
}
catch (…………)
{
// statements
}
finally
{
// statements
}

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 30

Q). Write about throws Clause?


Even if the programmer is not handing runtime exceptions, the Java compiler will not give any error
related to runtime exceptions. But the rule is that the programmer should handle checked
exceptions.

In case the programmer does not want to handle the checked exceptions, he should throw them out
using throws clause. Otherwise, there will be an error flagged by Java complier.

Example program which shows the use of throws clause.

package demo;  
import java.io.*;  
public class Demo
 {  
  void checkout() throws IOException
 {  
  System.out.println("checking machine");  
 }  
 public static void main(String[] args) throws IOException 
{  
   Demo d = new Demo();  
   d.checkout();  
   System.out.println("successfully checked");  
 }  
}  

Q). Write about throw Clause ?


There is also a throw statement available in Java to throw an exception explicitly and catch it. Let us
see how it can be used. In the following program, we are creating an object of Null Pointer Exception
class and throwing it out of try block, as shown here:

throw new Null Pointer Exception ("Exceptiondata");

In the above statement, Null Pointer Exception class object is created and 'Exception data' is stored
into its object. Then it is thrown using throw statement. Now, we can catch it using catch block as:

Catch(Null Pointer Exception)


{
}

Program:Throw a null Pointer exception

//using throw
class Sample
{
static void demo()
{
try
{

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 31

System.out.println(“inseid demo()”);
throw new NullPointerException(“Excception data”);
}
catch(NullPointerException)
{
System.out.println()ne;
}
}
class ThrowDemo
{
public static void main(String args[])
{
Sample.demo();
}
}

Explain Re-throwing an Exception with example?


When an exception occurs in a try block, it is caught by a catch block. This means that the thrown
exception is available to the catch block. The following code shows how to re-throw the same
exception out from catch block:
try {
throw exception;
} catch (Exception job)
{ throw exception; //re-throw the exception out
}

Program: Write a program to throw the StringIndexOutOfBondsException.


//Rethrowing an exception.
class A
{
void methodl ()
{
try {
string str="Hello";
char ch= str.charAt (5);
}
catch(StringIndexOutOfBondsException sie)
{
System.out.println("please see the index is withing the range");
throw sie; // rethrow the exception
}
}
}

class B
{
public static void main (String args[])
{
A a= new A();
try {
a.methodl ()
}
catch(StringIndexOutOfBoundsException sie)
{
System.out.println ("I caught rethrown exception");
}
}
}

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 32

Output:

Please see the index is within the range


I caught rethrow exception.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy