Java Unit III Answers
Java Unit III Answers
Defining a subclass
A subclass is defined as follows:
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);
}
}
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();
}
// Class 1
// First Parent class
class Parent1 {
// Class 3
// Trying to be child of both the classes
class Test extends Parent1, Parent2 {
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
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.
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
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:
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
import java.util.Scanner;
class MyClass {
System.out.println("Enter username");
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
Thread t;
NewThread()
{
t=new Thread(this, "Demo Thread");
t.start();
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");
}}
class RunnableDemo1
new NewThread();
try
for(int i=5;i>0;i--)
System.out.println("main Thread:"+i);
Thread.sleep(1000);
}
catch(InterruptedException e)
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
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
The getMessage() method of Java Throwable class is used to get a detailed message of the
Throwable.
Syntax
Return
Example 1
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
Return
An array of exceptions that were suppressed to deliver this exception.
Example 1
getLocalizedMessage() method
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.
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");
}
Output: