Tuesday, April 01, 2014

WBUT 2012-2013 JAVA SOLUTIONS PART 2



1.          What is the role of garbage collection? What are packages? Explain the steps to create packages (WBUT 2013)

Sol:
Since objects are dynamically allocated by using the new operator, we find how such objects are destroyed and their memory released for later reallocation. In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes a different approach; it handles deallocation for you automatically. The technique that accomplishes this is called garbage collection. It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. There is no explicit need to destroy objects as in C++. Garbage collection only occurs sporadically (if at all) during the execution of your program. It will not occur simply because one or more objects exist that are no longer used. Furthermore, different Java run-time implementations will take varying approaches to garbage collection, but for the most part, you should not have to think about it while writing your programs.
The finalize( ) Method
Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-Java resource such as a file handle or window character font, then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector.
To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method you will specify those actions that must be performed before an object is destroyed. The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is freed, the Java run time calls the finalize() method on the object. The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. It is important to understand that finalize( ) is only called just prior to garbage collection. It is not called when an object goes out-of-scope, for example. This means that you cannot know when—or even if—finalize( ) will be executed. Therefore, your program should provide other means of releasing system resources, etc., used by the object. It must not rely on finalize( ) for normal program operation.

2.         What is the difference between character based and byte based IO streams? Discuss different types of character and byte based streams. (WBUT 2013)
Sol:
            1st Part:
A stream is a way of sequentially accessing a file. A byte stream access the file byte by byte. A byte stream is suitable for any kind of file, however not quite appropriate for text files. For example, if the file is using a unicode encoding and a character is represented with two bytes, the byte stream will treat these separately and you will need to do the conversion yourself.
A character stream will read a file character by character. A character stream needs to be given the file's encoding in order to work properly.
2nd Part:
                    







3.         Describe the different stages in the life-cycle of an applet
Or
Distinguish between init( ) and start( ) methods.
(WBUT 2013)


Sol:
Various states, an applet, undergo between its object creation and object removal (when the job is over) is known as life cycle. Each state is represented by a method. There exist 5 states represented by 5 methods. That is, in its life of execution, the applet exists (lives) in one of these 5 states
·  init() method
·  start() method
·  paint() method
·  stop() method
·  destroy() method






·  init(): The applet's voyage starts here. In this method, the applet object is created by the browser. Because this method is called before all the other methods, programmer can utilize this method to instantiate objects, initialize variables, setting background and foreground colors in GUI etc.; the place of a constructor in an application. It is equivalent to born state of a thread.

·  start(): In init() method, even through applet object is created, it is in inactive state. An inactive applet is not eligible for microprocessor time even though the microprocessor is idle. To make the applet active, the init() method calls start() method. In start() method, applet becomes active and thereby eligible for processor time.

·  paint(): This method takes a java.awt.Graphics object as parameter. This class includes many methods of drawing necessary to draw on the applet window. This is the place where the programmer can write his code of what he expects from applet like animation etc. This is equivalent to runnable state of thread.

·  stop(): In this method the applet becomes temporarily inactive. An applet can come any number of times into this method in its life cycle and can go back to the active state (paint() method) whenever would like. It is the best place to have cleanup code. It is equivalent to the blocked state of the thread.

·  destroy(): This method is called just before an applet object is garbage collected. This is the end of the life cycle of applet. It is the best place to have cleanup code. It is equivalent to the dead state of the thread.

4.         What is synchronization? When is it used?
Sol:
Java supports multiple threads to be executed. This may cause two or more threads to access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in synch. Synchronization avoids memory consistence errors caused due to inconsistent view of shared memory. When a method is declared as synchronized; the thread holds the monitor for that method's object If another thread is executing the synchronized method, your thread is blocked until that thread releases the monitor.

Explain the use of synchronization keyword.

When a method in Java needs to be synchronized, the keyword synchronized should be added.
Example:
Public synchronized void increment()
{
       X++;
}
Synchronization does not allow invocation of this Synchronized method for the same object until the first thread is done with the object. Synchronization allows having control over the data in the class.

5.         Give an example where interface can be used to support multiple inheritances. (WBUT 2013)

interface A {

    public void show();
}
 interface B {

    public void show();
}
 interface C extends A, B {

    //same method is declared in A and B both
    public void show();
    
}
class Interfaces1 implements  C {

   
    public void show() {
        System.out.println("Using Interface java implements multiple inheritance");
    }

    public static void main(String[] args) {
        A objA = new Interfaces1();
        B objB = new Interfaces1();
        C objC = new Interfaces1();
        
        //all the method calls below are going to same concrete implementation
        objA.show();
        objB.show();
        objC.show();
    }

}

6.         Abstract class (WBUT 2013)
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, then the class itself must be declared abstract, as in:
public abstract class GraphicObject {
   // declare fields
   // declare nonabstract methods
   abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

7.           Exception handling (WBUT 2013)


An exception is an abnormal condition that arises in a code sequence at run time. A Java exception is an object that describes an exceptional  condition that has occurred in a piece of code When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error An exception can be caught to handle it or pass it on Exceptions can be generated by the Java run-time system, or they can be manually generated by your code.
Java exception handling is managed by via five keywords:try, catch, throw, throws, and finally.
Program statements to monitor are contained within a tryblock. If an exception occurs within the try block, it is thrown  Code within catch block catch the exception and handle it 
System generated exceptions are automatically thrown by the Java run-time system 
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 Claus Any code that absolutely must be executed before a method returns is put in a finally block
General form of an 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 }
All exception types are subclasses of the built-in class Throwable 
Throwable has two subclasses, they are Exception (to handle exceptional conditions that user programs should catch) An important subclass of Exception is RuntimeException, that includes division by zero and invalid array indexing Error (to handle exceptional conditions that are not expected to be caught under normal circumstances). i.e. stack overflow

No comments:

Post a Comment