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

Java Unit III Answers

The document explains various concepts of Java programming, including inheritance types such as single and multi-level inheritance, method overriding, and the use of abstract and final classes. It also covers the creation and usage of packages, interfaces, and threads, detailing how to implement the Runnable interface and the lifecycle of threads. Additionally, it lists built-in Java API packages and methods associated with threads.

Uploaded by

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

Java Unit III Answers

The document explains various concepts of Java programming, including inheritance types such as single and multi-level inheritance, method overriding, and the use of abstract and final classes. It also covers the creation and usage of packages, interfaces, and threads, detailing how to implement the Runnable interface and the lifecycle of threads. Additionally, it lists built-in Java API packages and methods associated with threads.

Uploaded by

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

1. Explain how a superclass reference can refer to a subclass object with Suitable example?

2. Explain single inheritance with suitable example


Single inheritance ( only one super class)

Defining a subclass
 A subclass is defined as follows:

class subclassname extends superclassname


{
variable declarations;
methods declarations;
}
 The keyword extends specifies that the properties of the superclassname are extended to
the subclassname
 The subclass will now contains its own variables and methods as well those of the
superclass

Ex:
class Room
{
int length, breadth;
Room(int x, int y)
{
length=x;
breadth=y;
}
int area()
{
return(length*breadth);
}
}
class BedRoom extends Room
{
{
int height;
BedRoom(int x, int y, int z)
{
super(x, y);
height=z;
}
int volume()
{
return(length*breadth*height);
}
}
class InherTest
{
public static void main(String args[])
{
BedRoom room1 = new BedRoom(14, 12, 10);
int area1 = room1.area();
int volume1 = room1.volume();
System.out.println(“Area1 = “ + area1);
System.out.println(“Volume = “ + volume);
}
}

3. Explain method overriding with suitable example

Defining a method in the subclass that has the same name, same arguments and
same return type as a method in the superclass.
 When that method is called, the method defined in the subclass is invoked and
executed instead of the one in the superclass .This process is known as method
overriding
Ex
class Super
{
int x;
Super(int x)
{
this.x = x;
}
void display() // Method Defined
{
System.out.println(“Super x = “ + x);
}
}
class Sub extends Super
{
int y;
Sub(int x, int y)
{
super(x);
this.y=y;
}
void display() //Method defined again
{
System.out.println(“Super x = “ + x);
System.out.println(“Sub y = “ + y);
}
}
class OverrideTest
{
public static void main(String args[])
{
Sub s1 = new Sub(100, 200);
s1.display();
}

4. Explain multi-level inheritance with suitable example


class A serves as a base class for the derived class B which in turn serves as a base class for
the derived class C

A derived class with multilevel base classes is declared as follows:


class A
{
--- `
}
class B extends A // First level
{
---
}
class C extends B // Second level
{
--
}

 This process may be extended to any number of levels


 The class C inherit the members of both A and B

// Java Program to Illustrate Unsupportance of


// Multiple Inheritance

// Importing input output classes


import java.io.*;

// Class 1
// First Parent class
class Parent1 {

// Method inside first parent class


void fun() {

// Print statement if this method is called


System.out.println("Parent1");
}
}
// Class 2
// Second Parent Class
class Parent2 {

// Method inside first parent class


void fun() {

// Print statement if this method is called


System.out.println("Parent2");
}
}

// Class 3
// Trying to be child of both the classes
class Test extends Parent1, Parent2 {

// Main driver method


public static void main(String args[]) {

// Creating object of class in main() method


Test t = new Test();

// Trying to call above functions of class where


// Error is thrown as this class is inheriting
// multiple classes
t.fun();
}
}

5. Explain the purpose abstract and final classes

A class that can not be subclassed is called final class


 This is achieved by using the keyword final as follows:
final class A { ……… }
final class B extends C { ………. }
 Any attempt to inherit these classes will cause an error and the compiler
will not allow it
 Declaring a class final prevents any unwanted extensions to the class

Example for Final Class


final class A
{
void meth()
{
System.out.println("This is a final class");
}
}
class B extends A //Error can’t extend final class
{
void method1()
{
System.out.println("Illegal");
}
}
public class FinalClass
{
public static void main(String[] args)
{
B b =new B();
b.method1();
}
}
Abstract methods and classes
 The use of final method ensures that the method is not redefined in a subclass
which means that the method can never be subclassed
 The opposite of this is, we can indicate that a method must always be redefined in
a subclass, thus making overriding compulsory
 This can be done by using the modifier keyword abstract in the method definition

Ex:
abstract class A
{
-----
abstract void display();
-----
}

While using the abstract classes, the following conditions must be satisfied
 We can not use abstract classes to instantiate objects directly
Ex:
A a = new A();
is illegal because A is an abstract class
 The abstract methods of an abstract class must be defined in its subclass
 We cannot declare abstract constructors or abstract static methods

Example for Abstract Class and Abstract Method


abstract class A
{
abstract void callme();
void callmetoo()
{
System.out.println("THIS IS A CONCRETE METHOD");
}
}
class B extends A
{
void callme()
{
System.out.println("'B's IMPLEMENTATION OF CALLME.");
}
}
class abstractdemo
{
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}

6. Explain how to create and use a package in JAVA with suitable example

To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to
the specified package. The package statement defines a name space in which
classes are stored. If you omit the package statement, the class names are put into
the default package, which has no name.
This is the general form of the package statement: package pkg;
Here, pkg is the name of the package.
For example, the following statement creates a package called MyPackage:
package MyPackage;
Java uses file system directories to store packages. For example, the .class files
for any classes you declare to be part of MyPackage must be stored in a directory
called MyPackage. Remember that case is significant, and the directory name
must match the package name exactly. More than one file can include the same
package statement.
The package statement simply specifies to which package the classes defined in a
file belong. It does not exclude other classes in other files from being part of that
same package. Most real-world packages are spread across many files. You can
create a hierarchy of packages. To do so, simply separate each package name
from the one above it by use of a period. The general form of a multileveled
package statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java
development system. For example, a package declared as
package java.awt.image;
Example: Package demonstration package pack;
public class Addition
{
int x,y;
public Addition(int a, int b)
{
x=a; y=b;
}
public void sum()
{
System.out.println("Sum :"+(x+y));
}
}
Step 1: Save the above file with Addition.java
package pack;
public class Subtraction
{
int x,y;
public Subtraction(int a, int b)
{
x=a; y=b;
}
public void diff()
{
System.out.println("Difference :"+(x-y));
}
}
Step 2: Save the above file with Subtraction.java
Step 3: Compilation
To compile the java files use the following commands
javac -d directory_pathname_of_the_java file
Javac –d name_of_the_java file
Note: -d is a switching options creates a new directory with package name.
Directory path represents in which location you want to create package and . (dot)
represents current working directory.
Step 4: Access package from another package
There are three ways to use package in another package:
With fully qualified name.
class UseofPack
{
public static void main(String arg[])
{
pack.Addition a=new pack.Addition(10,15); a.sum();
pack.Subtraction s=new pack.Subtraction(20,15); s.difference();
}
}
import package.classname;
import pack.Addition; import pack.Subtraction; class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15); a.sum();
Subtraction s=new Subtraction(20,15); s.difference();
}
}
import package.*;
import pack.*; class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15); a.sum();
Subtraction s=new Subtraction(20,15); s.difference();
}
}
Note: Don’t place Addition.java, Subtraction.java files parallel to the pack
directory. If you place JVM searches for the class files in the current working
directory not in the pack directory.

7. List and explain different API packages available in Java

A package in Java is used to group related classes. Think of it as a folder in a file directory.
We use packages to avoid name conflicts, and to write a better maintainable code. Packages
are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

Built-in Packages

The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.

The library contains components for managing input, database programming, and much
much more. The complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes. Meaning you can either import a single class
(along with its methods and attributes), or a whole package that contain all the classes that
belong to the specified package.

To use a class or a package from the library, you need to use the import keyword:

SyntaxGet your own Java Server

import package.name.Class; // Import a single class

import package.name.*; // Import the whole package

Import a Class

If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:

Example

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:

Example

Using the Scanner class to get user input:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter username");

String userName = myObj.nextLine();

System.out.println("Username is: " + userName);

8. Explain how to create and implement interface using suitable example

A named collection of method declarations.


A Java interface is a collection of constants and abstract methods
Since all methods in an interface are abstract, the abstract modifier is usually left off
Using interface, you can specify what a class must do, but not how it does.
Interface fields are public, static and final by default, and methods are public and abstract.

Syntax:
access_specifier interface interfae_name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Implementing Interfaces:
Once an interface has been defined, one or more classes can implement that interface.
To implement an interface, include the implements clause in a class definition, and
then create the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface1 [,interface2...]] {
// class-body
}
If a class implements more than one interface, the interfaces are separated with a
comma.
The methods that implement an interface must be public. Also, the type signature of
implementing method must match exactly the type signature specified in interface
definition.
Example 1: Write a java program to implement interface.
interface Moveable
{
int AVG_SPEED=30;
void Move();
}
class Move implements Moveable
{
void Move(){
System .out. println ("Average speed is: "+AVG_SPEED );
}
}
class Vehicle
{
public static void main (String[] arg)
{
Move m = new Move(); m.Move();
}
}
9. Explain the process of creating a thread by implementing Runnable interface with suitable
example

The Runnable interface declares the run() method that is

required for implementing threads in our programs

 To do this, we must perform the steps listed below:

1. declare the class as implementing the Runnable interface


2. implement the run() mehtod
3. create a thread by defining an object that is instantiated from this
runnable class as the target of the thread
4. call the thread’s start() method to run the thread

Implementing the Runnable Interface

class NewThread implements Runnable

Thread t;

NewThread()

{
t=new Thread(this, "Demo Thread");

System.out.println("Child Thread:" + t);

t.start();

public void run()

try

for(int i=5;i>0;i--)

System.out.println("Child Thread:"+i);

Thread.sleep(500);

catch(InterruptedException e)

System.out.println("Child Inrerrupted");

System.out.println("Exiting child thread.");

}}

class RunnableDemo1

public static void main(String args[])

new NewThread();

try

for(int i=5;i>0;i--)

System.out.println("main Thread:"+i);

Thread.sleep(1000);
}

catch(InterruptedException e)

System.out.println("main thread interrupted");

System.out.println("Main thread exiting.");

10. List and explain any five thread methods


getName - Obtain a thread’s name.
getPriority - Obtain a thread’s priority.
isAlive - Determine if a thread is still running.
join - Wait for a thread to terminate.
run - Entry point for the thread.
sleep - Suspend a thread for a period of time.
start - Start a thread by calling its run method.

11. Explain the life cycle of a Thread with diagram


During the life time of a thread, there are many states it can enter
They are
1) newborn state
2) runnable state
3) running state
4) blocked state
5) dead state
 A thread is always in one of these 5 states
 It can move from one state to another via a variety of ways.
Newborn:
When we create a thread object, the thread is born and is said to be in newborn state
The thread is not yet scheduled for running
At this state, we can do only one of the following
 Schedule it for running using start() method
 Kill it using stop() method
If we attempt to use any other method at this stage, an exception will be thrown
If scheduled, it moves to the runnable state as shown below

Runnable State
This state means that the thread is ready for execution and is waiting for the availability of
the processor
That is, the thread has joined the queue of threads that are waiting for execution
If all threads have equal priority, then they are given time slots for execution in round robin
fashion, i.e. first-come, first-serve mannerRunnable state
The thread that relinquishes control joins the queue at the end and again waits for its turn
This process of assigning time to threads is known as time-slicing
Running State
Running means that the processor has given its time to the thread for its execution
The thread runs until it relinquishes control on its own or it is preempted by a higher priority
threadA running thread may relinquish its control in one of the following situations:
1. It has been suspended using suspend() method. A suspended thread can be
revived by using the resume() method. This approach is useful when we want to
suspend a thread for some time due to certain reason, but do not want to kill it

2. It has been made to sleep. We can put a thread to sleep for a specified time
period using the method sleep(time) where time is in milliseconds.
This means that the thread is out of the queue during this time period. The thread

re-enters the runnable state as soon as this time period is elapsed


3. It has been told to wait until some event occurs. This is done using the
wait() method.. The thread can be scheduled to run again using the notify() method
Blocked Thread
a thread is said to be blocked when it is prevented from entering into the runnable
state and subsequently the running state
This happens when the thread is suspended, sleeping or waiting in order to satisfy
certain requirements
A blocked thread is considered not runnable but not dead and therefore fully
qualified to run again
Dead state
A running thread ends its life when it has completed executing its run() method
It is a natural death
However, we can kill it by sending the stop message to it at any state thus causing a
premature death to it
A thread can be killed as soon it is born, or while it is running, or even when it is in
not runnable condition

12. Explain exception handling in Java with suitable example

Introduction
An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instruction.
Or
An abnormal condition that disrupts Normal program flow.
There are many cases where abnormal conditions happen during program
execution, such as
 Trying to access an out - of –bounds array elements.
 The file you try to open may not exist.
 The file we want to load may be missing or in the wrong format.
 The other end of your network connection may be non –existence.
 If these cases are not prevented or at least handled properly, either the
program will be aborted abruptly, or the incorrect results or status will be
produced.
 When an error occurs with in the java method, the method creates an
exception object and hands it off to the runtime system.
 The exception object contains information about the exception including its
type and the state of the program when the error occurred. The runtime system
is then responsible for finding some code to handle the error.
 In java creating an exception object and handling it to the runtime system is
called throwing an exception.
 Exception is an object that is describes an exceptional ( i.e. error) condition
that has occurred in a piece of code at run time.
 When a exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error. That method may
choose to handle the exception itself, or pass it on. Either way, at some point,
the exception is caught and processed.
 Exceptions can be generated by the Java run-time system, or they can be
manually generated by your code.
 System generated exceptions are automatically thrown by the Java runtime
system

General form of Exception Handling block


try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed before try block ends
}
For Example:
class Exc0 {
public static void main(String args[])
{ int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs
a
new exception object and then throws this exception. This causes the execution of
Exc0 to stop, because once an exception has been thrown, it must be caught by an
exception handler and dealt
with immediately. In this example, we haven’t supp the exception is caught by the
default handler provided by the Java run-time system. Any
exception that is not caught by your program will ultimately be processed by the
default handler. The default handler displays a string describing the exception,
prints a stack trace from the point at which the exception occurred, and terminates
the program. Here is the output generated when this example is executed.
java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
Notice how the class name, Exc0; the method name, main; the filename,
Exc0.java; and the line number, 4
13. Illustrate the use of multiple catch statements with suitable example

Multiple Catch Blocks


In some cases, more than one exception could be raised by a single piece of code. To
handle this type of situation, you can specify two or more catch clauses, each
catching a different type of exception. When an exception is thrown, each catch
statement is inspected in order, and the first one whose type matches that of the
exception is executed. After one catch statement executes, the others are bypassed,
and execution continues after the try/catch block. The following example traps two
different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[])
{
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 }; c[42] = 99;
} catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

14. List and explain different methods of Throwable class


Java Throwable class provides several methods like addSuppressed(), fillInStackTrace(),
getMessage(), getStackTrace(), getSuppressed(), toString(), printStackTrace() etc.

The getMessage() method of Java Throwable class is used to get a detailed message of the
Throwable.

Syntax

public String getMessage()

Return

It returns a detailed message string of the Throwable instance (which may be


NULL).

Example 1

public class ThrowableGetMessageExample1 {


public static void main(String[] args)throws Throwable {
try{
int i=10/0;
}catch(Throwable t){
System.out.println(t.getMessage());
}
}
}

The getSuppressed() method of Java Throwable class is used to return an array of all the
exceptions that were suppressed to deliver this exception. If no exception were suppressed,
an empty array will be returned.

Syntax

public final Throwable[] getSuppressed()

Return
An array of exceptions that were suppressed to deliver this exception.

Example 1

public class ThrowableGetSuppressedExample1 {

public static void function1() throws Exception{


throw new Exception();
}
public static void function2() throws Throwable{
try{
function1();
}catch(Exception e){
throw e.fillInStackTrace();
}
}
public static void main(String[] args)throws Throwable {
try{
function2();
}catch(Exception e){
System.err.println("Caught inside Main:");
Throwable[] suppress = e.getSuppressed();
System.out.println(suppress[0].toString());
}
}
}
The getStackTrace() method of Java Throwable class is used to
return an array of StackTraceElement given by printStackTrace()
method. Some virtual machines may omit one or more frames from
the stack trace

getLocalizedMessage() method

It is used to get a localized (or locale-specific) description of the


Throwable. It modifies the description of Throwable according to the
system's locale. It converts the message's language, date, time,
numbers, etc. according to the region

15. Illustrate the use of finally with suitable example


Java finally block is a block used to execute important code such as closing the connection,
etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.

The finally block follows the try-catch block.

Flowchart of finally block

16.

Let's see the below example where the Java program does not throw any
exception, and the finally block is executed after the try block.

TestFinallyBlock.java

class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of phe code...");


}
}

Output:

17. Explain how to createuser defined exceptions in Java with example

We can create our own exception by extending exception class.


The throw and throws keywords are used while implementing user defined
exceptions
Class ownExcepion extends Exception
{
ownException(String msg)
{
Super(msg);
}
}
Class test
{
Public static void main(String args[]) Int mark=101;
Try
{
if(mark>100)
{
Throw new ownException(―Marks>100‖);
}
}
Catch(ownException e)
{
System.out.println (―Exception caughtr‖); System.out.println.
(―e.getMessage());
}
Finally
{
System.out.println(―End of prg‖);
}
}
}
Output:
Exception caught Marks is > 100 End of program

You might also like