Programming in Java – 18CS653 Module 4 Solutions
MODULE 4
1. Define package. What are the steps involved in creating user defined package with
an example and execution steps. (Mar 2022) (08 Marks) (Mar 2022) (05 Marks)
(July 2021) (06 Marks) (Feb 2021) (05 Marks) (July 2021) (10 Marks) (Feb 2021)
(10 Marks) (Sept 2020) (06 Marks) (Sept 2020) (06 Marks) (July 2019) (08
Marks)(Feb 2023)(6M) (10M)(Aug 2022)(8M)(6M)
Packages are containers for classes that are used to keep the class name space
compartmentalized. Packages are stored in a hierarchical manner and are explicitly
imported into new class definitions.
• Include package command as 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.
• Default package does not have name.
• General form:
package pkg;
o pkg→ name of the package.
• Example,
package myPackage;
• Java uses file system directories to store packages.
i.e. .class files for any classes declared to be part of MyPackage must be
stored in a directory called MyPackage.
• RULES:
o case is significant and
o 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.
• Can create hierarchy of packages.
• General form:
package pkg1[.pkg2[.pkg3]];
• A package hierarchy must be reflected in the file system of your Java development
system.
• Example,
package java.awt.image;
• needs to be stored in java\awt\image in a Windows environment
Prof. Jayashree N, Dept. of ISE, CiTech. 1
Programming in Java – 18CS653 Module 4 Solutions
Finding Packages and CLASSPATH
• Packages are mirrored by directories
• How does the Java run-time system know where to look for packages that you
create?
o By default, the Java run-time system uses the current working directory as
its starting point.
o Specify a directory path or paths by setting the CLASSPATH
environmental variable.
o Use the -classpath option with java and javac to specify the path to your
classes.
• Consider,
package myPack;
In a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack
The class path to myPack is
C:\MyPrograms\Java
A Short Package Example
Example,
// A simple package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
Prof. Jayashree N, Dept. of ISE, CiTech. 2
Programming in Java – 18CS653 Module 4 Solutions
}
}
To execute the above program, the control must be in the classpath i.e. To
execute→ be in the directory above MyPack.
2. Describe the four types of JAVA access modifiers. (Mar 2022) (05 Marks) (Mar
2022) (05 Marks) (Sept 2020) (08 Marks) (Jan 2019) (07 Marks)(Feb
2023)(10M)(Aug 2022)(8M)
The four types of access specifiers are:
i. No modifiers: by default all the members of the class are public.
ii. Private
iii. Public
iv. Protected
Because of the interplay between classes and packages, Java addresses four categories
of visibility for class members as given in the above table:
• Subclass in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses.
✓ Anything declared public can be accessed from anywhere.
✓ Anything declared private cannot be seen outside of its class.
✓ When a member does not have an explicit access specification, it is visible to
subclasses as well as to other classes in the same package
✓ If an element to be seen outside the current package, but only to classes that
subclass our class directly, then declare that element protected.
3. Explain access protection and importing of package in java.
(Mar 2022) (05 Marks)
Prof. Jayashree N, Dept. of ISE, CiTech. 3
Programming in Java – 18CS653 Module 4 Solutions
- There are no core Java classes in the unnamed default package; all of the standard
classes are stored in some named package.
- Java includes the import statement to bring certain classes, or entire packages, into
visibility.
- In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions.
- General form:
import pkg1[.pkg2].(classname|*);
- Example:
importjava.util.Date;
import java.io.*;
- All of the standard Java classes included with Java are stored in a package called
java.
- The basic language functions are stored in a package inside of the java package
called java.lang.
import java.lang.*;
- If a class with the same name exists in two different packages that you import
using the star form, the compiler will remain silent, unless you try to use one of
the classes.
- Results in compile time error.
- Must explicitly name the class specifying its package.
- import statement is optional.
4. What is an Interface? Write a JAVA program to demonstrate multiple inheritance
using interface. (Mar 2022) (08 Marks) (July 2021) (06 Marks) (Sept 2020) (06
Marks) (July 2019) (08 Marks)(Feb 2023)(6M)(Aug 022)(6M)
- Keyword → interface
- Using interface, you can specify what a class must do, but not how it does it.
- Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body.
- Once it is defined, any number of classes can implement an interface.
- One class can implement any number od interfaces.
- To implement an interface, a class must create the complete set of methods defined
by the interface.
Multiple inheritance using interfaces
interface Printable{
void print();
}
interface Showable{
void show();
}
Prof. Jayashree N, Dept. of ISE, CiTech. 4
Programming in Java – 18CS653 Module 4 Solutions
class MulInt implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
MulInt obj = new MulInt ();
obj.print();
obj.show();
}
}
5. Explain the interfaces in Java with suitable code. (July 2021) (06 Marks)
- If a class implements more than one interface, the interfaces are separated with a
comma.
- If a class implements more than one interface, the interfaces are separated with a
comma.
- If a class implements two interfaces that declare the same method!!
o Represent the methods with the interface reference using a dot operator.
- The methods that implement an interface must be declared as public.
interface Callback {
void callback(int param);
}
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
//Demo.java to check the implementation of interface
class Demo {
public static void main(String args[]) {
Client c = new Client();
c.callback(42);
}
}
6. Write general form of interface. How interfaces can be extended and
implemented. (Feb 2021) (08 Marks) (Feb 2021) (06 Marks)(Aug 2022)(6M)
General Form:
access interface name {
return-type method-name1(parameter-list);
Prof. Jayashree N, Dept. of ISE, CiTech. 5
Programming in Java – 18CS653 Module 4 Solutions
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
- When no access specifier is included → default access
- Public→ the interface can be used by any other code
- Methods→ have no bodies→ abstract methods
- Variables → implicitly final and static
→ must be initialized
- Methods and variables → implicitly public
- Example,
interface Callback {
void callback(int param);
}
Implementing Interfaces
- Keyword→ implements
- Create the methods defined by interface
- General form:
class classname [extends superclass] [implements interface
[,interface...]]
{
// class-body
}
- If a class implements more than one interface, the interfaces are separated
with a comma.
- If a class implements more than one interface, the interfaces are separated
with a comma.
- If a class implements two interfaces that declare the same method!!
o Represent the methods with the interface reference using a dot operator.
- The methods that implement an interface must be declared as public.
- Example:
class Client implements Callback {
// Implement Callback's interface
Prof. Jayashree N, Dept. of ISE, CiTech. 6
Programming in Java – 18CS653 Module 4 Solutions
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
//Demo.java to check the implementation of interface
class Demo {
public static void main(String args[]) {
Client c = new Client();
c.callback(42);
}
}
- When you implement an interface method, it must be declared as public.
- It is both permissible and common for classes that implement interfaces to
define additional members of their own.
Interfaces can be Extended
- One interface can inherit another by use of the keyword extends.
- Example,
//A.java
interface A {
void meth1();
void meth2();
}
//B.java
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
//MyClass.java
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
//IFExtend.java
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
Prof. Jayashree N, Dept. of ISE, CiTech. 7
Programming in Java – 18CS653 Module 4 Solutions
}
}
7. What is exception? How Java supports exception handling mechanism give
example. (Mar 2022) (06 Marks) (Mar 2022) (07 Marks) (July 2019) (05 Marks)
(July 2019) (08 Marks) (July 2019) (05 Marks) (Jan 2019) (08 Marks) (Sept 2020)
(08 Marks) (Sept 2020) (06 Marks) (Feb 2021) (10 Marks) (Feb 2021) (06 Marks)
(July 2021) (10 Marks) (Mar 2022) (06 Marks) (Feb 2021) (08 Marks)(Feb
2023)(8M)(10M) (Aug 2022)(8M)(6M)
A Java exception is an object that describes an exceptional condition that has
occurred in a piece of code. Ehen an 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.
This means, the exception is caught and processed. Exceptions can be generated
• By Java run-time system
These relate to fundamental errors that violate the rules of the Java language or
constraints of Java exception environment.
• Manually generated by our code
These are used to report some error condition to the caller of the method
Exception handling by Java
Exceptions in Java are managed via five keywords: try, catch, throw, throws,
and finally.
• Program statements to be monitored for exceptions are contained within a try
block.
• If an exception occurs within the try block, it is thrown.
• The code can catch this exception (using catch) and handle it in some rational
manner.
• To manually throw an exception, use the keyword throw.
• Any exception that is thrown out of a method must be specified as such by a
throws clause
• Any code that absolutely must be executed after a try block completes is put in
a finally block.
General form of exception-handling block is:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler forExceptionType1
}
catch (ExceptionType2 exOb) {
Prof. Jayashree N, Dept. of ISE, CiTech. 8
Programming in Java – 18CS653 Module 4 Solutions
// exception handler forExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Where, ExceptionType is the type of exception that has occurred.
Example program that covers the above key words [select the code
based on the question asked]
Using try and catch blocks
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) {
// catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.
Using throw clause
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
//create one of Java’s standard exception objects.
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
Output
Caught inside demoproc.
Prof. Jayashree N, Dept. of ISE, CiTech. 9
Programming in Java – 18CS653 Module 4 Solutions
Recaught: java.lang.NullPointerException: demo
Using throws
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
Make two changes to make this example compile.
i. Declare that throwOne( ) throws IllegalAccessException
ii. main( ) must define a try/catch statement that catches this exception
// This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Output
inside throwOne
caught java.lang.IllegalAccessException: demo
using finally
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
Prof. Jayashree N, Dept. of ISE, CiTech. 10
Programming in Java – 18CS653 Module 4 Solutions
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
8. Discuss about nested try statements and how such program may be executed. (Feb
2021) (08 Marks)
Nested try Statements
The try statement can be nested. That is, a try statement can be inside the block of
another try.
• Each time a try statement is entered, the context of that exception is pushed
on the stack.
• If an inner try statement does not have a catch handler for a particular
exception, the stack is unwound and the next try statement’s catch handlers
are inspected for a match.
• If no catch statement matches, then the Java run-time system will handle the
exception
// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
Prof. Jayashree N, Dept. of ISE, CiTech. 11
Programming in Java – 18CS653 Module 4 Solutions
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
Output
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42
9. Explain Java’s built-in exceptions. (Feb 2021) (08 Marks)
Java’s Built-in Exceptions
Standard package→ java.lang
java.lang → exception classes
→ RuntimeException →standard type→ method’s throw list
Prof. Jayashree N, Dept. of ISE, CiTech. 12
Programming in Java – 18CS653 Module 4 Solutions
Prof. Jayashree N, Dept. of ISE, CiTech. 13