Netaji Subhas Open University: Semester Iv Paper Code: 4.2 Programming in Java
Netaji Subhas Open University: Semester Iv Paper Code: 4.2 Programming in Java
Netaji Subhas Open University: Semester Iv Paper Code: 4.2 Programming in Java
UNIVERSITY
MCA
SEMESTER IV
PROGRAMMING IN JAVA
TANUSREE CHAKRABORTTY
1
1. Explain the meaning of “final” keyword in relation to variable, methods and
classes.
In the Java programming language, the final keyword is used in several different contexts to
define an entity which cannot later be changed.
Final Classes:
A final class cannot be subclassed. This is done for reasons of security and efficiency.
Accordingly, many of the Java standard library classes are final, for example
java.lang.System and java.lang.String. All methods in a final class are implicitly final.
Example:
Final Methods:
Example:
Final Variables:
A final variable can only be assigned once. This assignment does not grant the variable
immutable status. If the variable is a field of a class, it must be assigned in the constructor of
its class. (Note: If the variable is a reference, this means that the variable cannot be re-
bound to reference another object. But the object that it references is still mutable, if it was
originally mutable.)
Unlike the value of a constant, the value of a final variable is not necessarily known at
compile time.
2
Example:
Any attempt to reassign radius, xpos, ypos, zpos will meet with a compile error.
To illustrate that finality doesn't guarantee immutability: suppose we replace the three
position variables with a single one:
where pos is an object with three properties pos.x, pos.y and pos.z. Then pos cannot be
assigned to, but the three properties can, unless they are final themselves.
3
Q2. Write a short note on Exception handling in Java
Common Exceptions
There are many different exceptions that can be thrown by a program, and the Java
API contains quite a few. A lot are contained in the default package, java.lang;
however, when you start using more functionality such as AWT, Swing, or java.io,
the packages may also contain additional exceptions thrown by those libraries. As
you start expanding the functionality, it might be a good idea to look at potential
exceptions in the package and when they might be thrown in the course of your
application. Here is a primer of some:
"Catching" Exceptions
The java language contains keywords used specifically for testing for and handling
exceptions. The ones we will be using here are try and catch, and they must be used in
conjunction with one another. They sort of work like if-else:
try{
/*
Contains code to be tested
*/
}catch(Exception e){
/*
Contains code to be executed if instanced of Exception is caught
4
*/
}
The catch statement can look for all exceptions, using the Exception superclass, or it can
catch a specific exception that you think could be thrown in the code you are testing with the
try block. You can even have multiple catch blocks to catch and execute custom code for a
number of different errors. A good thing to note would be that any particular exception that is
caught is compared with each catch statement sequentially; so it is a good idea to put more
generic exceptions, like Exception, towards the bottom of the list.
The catch statement also stores an instance of the exception that was caught in the variable
that the programmer uses, in the previous example Exception e. While all exceptions are
subclasses of Exception, Exception itself is a subclass of Throwable, which contains a nice
suite of methods that you can use to get all kinds of information to report about your
exceptions:
• printStackTrace(PrintWriter s)--prints the stack trace to a file, this way you can log
stack traces transparent to the user or log for later reference
• toString()--if you just decide to print out the exception it will print out this:
NAME_OF_EXCEPTION: getMessage().
Using the catch we have control over what the error message is and where it goes.
In this section, I'm going to give you a few code samples on using try-catch blocks to give
you an idea of the flexibility you as a programmer have over exceptions in your programs.
The scenario is a user has input a file name to a program of a file that does not exist. In this
scenario we are going to be using a text-based program; however, in a graphical
environment you can easily use the catch block to draw dialog boxes. In the first example,
we want to print a useful error message and exit the program gracefully, saving the user
from the confusing stack trace with something useful:
try{
BufferedReader in = new BufferedReader(new FileReader(userInput));
System.out.println(in.readLine())
}catch(IOException e){
System.err.println(e.getMessage());
System.err.println("Error: " + userInput + " is not a valid file. Please verify that the
file exists and that you have access to it.");
System.exit(1);
}
Here, System.err.println() prints the error message to standard error output which is a high
priority buffer that is used to report error messages to the console. If you're being a good
5
programmer, you have separate methods that handle the different functionality of your
programs; this way you can easily start the program from a previous place in the program
before an exception occurs. In this next example, the user inputs the filename through the
function getUserInput() elsewhere in the program; we want to report the "helpful error
message" to the user and return the user to a place where he can enter a new filename.
The best way to prevent your application from crashing from exceptions is to avoid
exceptions in the first place. It is much more costly for a system to catch and handle
exceptions than to account for potential errors directly in your code. A lot of times, an
exception can point to a problem in the programmer's logic rather than in the user's use of
the program. You should look for the cause of exceptions, and try to understand why it
occurred and make sure that you really had considered everything. You will be making far
more resilient and robust applications.
6
Q3. Describe Applet Life Cycle.
The life cycle of an applet is determined by methods that are automatically called at its birth,
its death and when it is momentarily away. We discuss below the details. To illustrate the life
cycle calls, here is an applet that displays all calls in both a text area and the java console.
1. The Begin
2. Away for a Moment
3. Back Again
4. The End
5. A Minimal Appletviewer
The Begin
An applet extends a panel, so it "is" a component of the AWT. But how come it runs
as a program?
1. The browser starts a Java Virtual Machine (JVM) and gives it control over the part of
the screen that is specified width and height of the applet.
2. This JVM will do all things that belong to any java application, like starting the AWT-
Input handler and the garbage collector. (See User Threads).
3. Next it will create an instance of the applet as specified in the class file of the applet.
4. The JVM sees the window of the browser as a kind of a Java AWT frame, and adds
the applet as a panel to this frame.
5. As the main routine is in fact already running, there is an other method, init, for the
initialization of the applet. It is called automatically by the JVM.
6. After the call to init, a call to start is done and then a call to the paint routine.
Once a browser has loaded an applet, this applet will stay running. Also when the applet is
not visible, it is still running in the background. This is even the case when you have clicked
to other URLs. Only when you quit the browser, the applet will exit as well.
The stop method is exactly meant to keep in control of the applet at these moments where
the applet becomes not visible. By implementing this method, you can stop computations or
"threads" like animations. In general you should stop parts of the programs that consume
resources.
Back Again
Of course, once you can stop things, you should be able to restart them as well. For this
purpose, there is the start method. This method is also automatically called at the beginning,
just after init. When you ask the browser to reload a page containing the applet, it will call
stop, immediately followed by start.
7
The End
Just before exiting, so when the browser quits, the applet performs a call to the destroy
method. Here some clean-up code can be inserted, however this is in practice seldomly
necessary. Please note the difference with the stop method.
A Minimal Appletviewer
As we now have all ingredients that make up an applet, we can mimick the browser with a
simple Java application. The JDK appletviewer offers more functionality, but essentially does
the same.
This section introduces a new applet, Simple, that uses all of these methods. Unlike Java
applications, applets do not need to implement a main method.
So all we have to do is to make a frame, and then perform the necessary calls to init, start,
stop and destroy. Here is the essential part of the code.
Applet applet;
8
Q4. Write a program to demonstrate the use of interface in java.
Interfaces are used to encode similarities which classes of various types share, but do not
necessarily constitute a class relationship.
An interface declaration consists of modifiers, the keyword interface, the interface name, a
comma-separated list of parent interfaces (if any), and the interface body. For example:
// constant declarations
double E = 2.718282; // base of natural logarithms
// method signatures
void doSomething (int i, double x);
int doSomethingElse(String s);
}
The public access specifier indicates that the interface can be used by any class in any
package.
An interface can extend other interfaces, just as a class can extend or subclass another
class. However, whereas a class can extend only one other class, an interface can extend
any number of interfaces. The interface declaration includes a comma-separated list of all
the interfaces that it extends.
Any class can implement Relatable if there is some way to compare the relative "size"
of objects instantiated from the class. For strings, it could be number of characters;
for books, it could be number of pages; for students, it could be weight; and so forth.
For planar geometric objects, area would be a good choice (see the RectanglePlus
class that follows), while volume would work for three-dimensional geometric objects.
All such classes can implement the isLargerThan() method.
// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
public RectanglePlus(Point p) {
origin = p;
}
public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
Summary of Interfaces
An interface defines a protocol of communication between two objects.
An interface declaration contains signatures, but no implementations, for a set of
methods, and might also contain constant definitions.
A class that implements an interface must implement all the methods declared in the
interface.
An interface name can be used anywhere a type can be used.
10