Professional Documents
Culture Documents
When you override methods, JVM determines the proper methods to call at the program’s
run time, not at the compile time. Overriding occurs when a class method has the same
name and signature as a method in parent class.
Example of Overloading
int add(int a,int b)
float add(float a,int b)
float add(int a ,float b)
void add(float a)
int add(int a)
void add(int a) //error conflict with the method int add(int a)
Example: Overloading
Class BookDetails{
String title;
String publisher;
float price;
setBook(String title){
}
setBook(String title, String publisher){
}
setBook(String title, String publisher,float price){
}
}
Example: Overriding
class BookDetails{
String title;
setBook(String title){ }
Ans) Inheritance is the property which allows a Child class to inherit some properties
from its parent class. In Java this is achieved by using extends keyword. Only properties
with access modifier public and protected can be accessed in child class.
In above example the child has inherit its family name from the parent class just by
inheriting the class.
Ans) Abstraction is way of converting real world objects in terms of class. For example
creating a class Vehicle and injecting properties into it. E.g
Ans) The encapsulation is achieved by combining the methods and attribute into a class.
The class acts like a container encapsulating the properties. The users are exposed mainly
public methods.The idea behind is to hide how thinigs work and just exposing the
requests a user can do.
Ans) Association is a relationship between two classes. In this relationship the object of
one instance perform an action on behalf of the other class. The typical behaviour can be
invoking the method of other class and using the member of the other class.
Ans) Aggregation has a relationship between two classes. In this relationship the object
of one class is a member of the other class. Aggregation always insists for a direction.
Ans) Immutable class is a class which once created, it’s contents can not be changed.
Immutable objects are the objects whose state can not be changed once constructed. e.g.
String class
E.g.
public final class FinalPersonClass {
Ans) True. Since the state of the immutable objects can not be changed once they are
created they are automatically synchronized/thread-safe.
Ans: )
2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using
an Array. When an element is inserted into an ArrayList or a Vector, the object will need
to expand its internal array if it runs out of room. A Vector defaults to doubling the size
of its array, while the ArrayList increases its array size by 50 percent.
Collection.synchronizedList(List list)
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)
Q3) If an Employee class is present and its objects are added in an arrayList. Now I
want the list to be sorted on the basis of the employeeID of Employee class. What
are the steps?
Ans) 1) Implement Comparable interface for the Employee class and override the
compareTo(Object obj) method in which compare the employeeID
Ans) Both collections implements Map. Both collections store value as key-value pairs.
The key differences between the two are
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for
the Hashtable isn't.
Fail-safe - “if the Hashtable is structurally modified at any time after the iterator is
created, in any way except through the iterator's own remove method, the iterator will
throw a ConcurrentModificationException�
3. HashMap permits null values and only one null key, while Hashtable doesn't allow key
or value as null.
Q5) What are the classes implementing List interface?
Ans)
There are three classes that implement List interface:
1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be
increased dynamically also operations like add,remove and get can be formed once the
object is created. It also ensures that the data is retrieved in the manner it was stored. The
ArrayList is not thread-safe.
3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First
In First Out) operation for add operation. It is faster if than ArrayList if it performs
insertion and deletion of elements from the middle of a list.
Ans) A Set is a collection that contains no duplicate elements. More formally, sets
contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null
element. HashSet,SortedSet and TreeSet are the commnly used class which implements
Set interface.
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows
the data to be iterated in the ascending order or sorted on the basis of Comparator or
Comparable interface. All elements inserted into the interface must implement
Comparable or Comparator interface.
HashSet: This class implements the Set interface, backed by a hash table (actually a
HashMap instance). It makes no guarantees as to the iteration order of the set; in
particular, it does not guarantee that the order will remain constant over time. This class
permits the null element. This class offers constant time performance for the basic
operations (add, remove, contains and size), assuming the hash function disperses the
elements properly among the buckets
Ans)
1) List can contain duplicate values but Set doesnt allow. Set allows only to unique
elements.
2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt
ensures the sequence in which data can be retrieved.(Except HashSet)
Q8) What is difference between Arrays and ArrayList ?
Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means that once
array is declared as :
Also the size of array cannot be incremented or decremented. But with arrayList the size
is variable.
2. Once the array is created elements cannot be added or deleted from it. But with
ArrayList the elements can be added and deleted at runtime.
4. To create an array the size should be known or initalized to some value. If not
initialized carefully there could me memory wastage. But arrayList is all about
dynamic creation and there is no wastage of memory.
Ans) Adding new elements is pretty fast for either type of list. For the ArrayList, doing
random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's
no efficient way to index into the middle of a linked list. When removing elements, using
ArrayList is slow. This is because all remaining elements in the underlying array of
Object instances must be shifted down for each remove operation. But here LinkedList is
fast, because deletion can be done simply by changing a couple of links. So an ArrayList
works best for cases where you're doing random access on the list, and a LinkedList
works better if you're doing a lot of editing in the middle of the list.
Q10) Consider a scenario. If an ArrayList has to be iterate to read data only, what
are the possible ways and which is the fastest?
Ans) It can be done in two ways, using for loop or using iterator of ArrayList. The first
option is faster than using iterator. Because value stored in arraylist is indexed access. So
while accessing the value is accessed directly as per the index.
Q11) Now another question with respect to above question is if accessing through
iterator is slow then why do we need it and when to use it.
Ans) For loop does not allow the updation in the array(add or remove operation) inside
the loop whereas Iterator does. Also Iterator can be used where there is no clue what type
of collections will be used because all collections have iterator.
Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The
Iterator pattern is one, which allows you to navigate through a collection of data using a
common interface without knowing about the underlying implementation. Iterator should
be implemented as an interface. This allows the user to implement it anyway its easier for
him/her to return data. The benefits of Iterator are about their strength to provide a
common interface for iterating through collections without bothering about underlying
implementation.
1. If later on code needs to be changed from ArrayList to Vector then only at the
declaration place we can do that.
2. The most important one – If a function is declared such that it takes list. E.g void
showDetails(List list);
When the parameter is declared as List to the function it can be called by passing
any subclass of List like ArrayList,Vector,LinkedList making the function more
flexible
Q14) What is difference between iterator access and index access?
Ans) Index based access allow access of the element directly on the basis of index. The
cursor of the datastructure can directly goto the 'n' location and get the element. It
doesnot traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired
element.So to reach the 'n'th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are
performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are
performed on elements present at last of the datastructure.
Ans) To sort the elements of the List in the reverse natural order of the strings, get a
reverse Comparator from the Collections class with reverseOrder(). Then, pass the
reverse Comparator to the sort() method.
Collections.sort(list, comp)
Ans) A null element can be added only if the set contains one element because when a
second element is added then as per set defination a check is made to check duplicate
value and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.
Ans) LinkedList.
Ans) HashSet implements hashmap internally to store the data. The data passed to
hashset is stored as key in hashmap with null as value.
Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be
used for both performance reasons, if you know that two different elements will never be
equals and for preventing spoofing, where an object tries to imitate another.
Throwable is a parent class off all Exception classes. They are two types of Exceptions:
Checked exceptions and UncheckedExceptions. Both type of exceptions extends
Exception class.
Ans) Runtime exceptions represent problems that are the result of a programming
problem. Such problems include arithmetic exceptions, such as dividing by zero; pointer
exceptions, such as trying to access an object through a null reference; and indexing
exceptions, such as attempting to access an array element through an index that is too
large or too small. Runtime exceptions need not be explicitly caught in try catch block as
it can occur anywhere in a program, and in a typical one they can be very numerous.
Having to add runtime exceptions in every method declaration would reduce a program's
clarity. Thus, the compiler does not require that you catch or specify runtime exceptions
(although you can). The solution to rectify is to correct the programming logic where the
exception has occurred or provide a check.
While exceptions are conditions that occur because of bad input etc. e.g.
FileNotFoundException will be thrown if the specified file does not exist. Or a
NullPointerException will take place if you try using a null reference. In most of the
cases it is possible to recover from an exception (probably by giving user a feedback for
entering proper values etc.)
Ans) A ClassNotFoundException is thrown when the reported class is not found by the
ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to
be loaded from another class which was loaded in a parent classloader and hence the
class from the child classloader is not visible.
java.lang.NoClassDefFoundError
src/com/TestClass
does not mean that the TestClass class is not in the CLASSPATH. It means that the class
TestClass was found by the ClassLoader however when trying to load the class, it ran
into an error reading the class definition. This typically happens when the class in
question has static blocks or members which use a Class that's not found by the
ClassLoader. So to find the culprit, view the source of the class in question (TestClass in
this case) and look for code using static blocks or static members.
Ans) Throw keyword is used to throw the exception manually. It is mainly used when the
program fails to satisfy the given condition and it wants to warn the application.The
exception thrown should be subclass of Throwable.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}
Ans) If the function is not capable of handling the exception then it can ask the calling
method to handle it by simply putting the throws clause at the function declaration.
Q11) What are the possible combination to write try, catch finally block?
Ans)
1) try{
}catch(Exception e){
}finally{
//the clean code which is executed always no matter the exception occurs or not.
}
2 try{
}finally{}
3 try{
}catch(Exception e){
The catch blocks must always follow the try block. If there are more than one catch
blocks they all must follow each other without any block in between. The finally block
must follow the catch block if one is present or if the catch block is absent the finally
block must follow the try block.
Ans) To create you own exception extend the Exception class or any of its subclasses.
e.g.
Q14)What is StackOverflowError?
Ans) The StackOverFlowError is an Error Object thorwn by the Runtime System when it
Encounters that your application/code has ran out of the memory. It may occur in case of
recursive methods or a large amount of data is fetched from the server and stored in some
object. This error is generated by JVM.
swap();
Q15) Why did the designers decide to force a method to specify all uncaught
checked exceptions that can be thrown within its scope?
Ans) Any Exception that can be thrown by a method is part of the method's public
programming interface. Those who call a method must know about the exceptions that a
method can throw so that they can decide what to do about them. These exceptions are as
much a part of that method's programming interface as its parameters and return value.
Ans) No. Once the control jumps to the catch block it never returns to the try block but it
goes to finally block(if present).
Q17) Where is the clean up code like release of resources is put in try-catch-finally
block and why?
Ans) The code is put in a finally block because irrespective of try or catch block
execution the control will flow to finally block. Typically finally block contains release
of connections, closing of result set etc.
Ans) NO. This will result in a compilation error. The try block must be followed by a
catch or a finally block. It is legal to omit the either catch or the finally block but not
both.
try{
int i =0;
}
int a = 2;
System.out.println(“a = “+a);
Q19) Is it valid to place some code in between try the catch/finally block that follows
it?
Ans) No. There should not be any line of code present between the try and the
catch/finally block. e.g. The following code is wrong.
try{}
String str = “ABC”;
System.out.println(“str = “+str);
catch(Exception e){}
Q20) What happens if the exception is never caught and throws down the method
stack?
Ans) If the exception is not caught by any of the method in the method’s stack till you get
to the main() method, the main method throws that exception and the JVM halts its
execution.
Q21) How do you get the descriptive information about the Exception occurred
during the program execution?
Ans) All the exceptions inherit a method printStackTrace() from the Throwable class.
This method prints the stack trace from where the exception occurred. It prints the most
recently entered method first and continues down, printing the name of each method as it
works its way down the call stack from the top.
Q22) Can you catch more than one exceptions in a single catch block?
Ans)Yes. If the exception class specified in the catch clause has subclasses, any
exception object that is a subclass of the specified Exception class will be caught by that
single catch block.
E.g..
try {
catch (IOException e) {
e.printStackTrace();
}
The catch block above will catch IOException and all its subclasses e.g.
FileNotFoundException etc.
Ans) You can write a single catch block to handle all the exceptions thrown during the
program execution as follows :
try {
}catch (Exception e) {
e.printStackTrace();
If you use the Superclass Exception in the catch block then you will not get the valuable
information about each of the exception thrown during the execution, though you can
find out the class of the exception occurred. Also it will reduce the readability of the code
as the programmer will not understand what is the exact reason for putting the try-catch
block.
Ans) Exception matching is the process by which the the jvm finds out the matching
catch block for the exception thrown from the list of catch blocks. When an exception is
thrown, Java will try to find by looking at the available catch clauses in the top down
manner. If it doesn't find one, it will search for a handler for a supertype of the exception.
If it does not find a catch clause that matches a supertype for the exception, then the
exception is propagated down the call stack. This process is called exception matching.
Q25) What happens if the handlers for the most specific exceptions is placed above
the more general exceptions handler?
Ans) Compilation fails. The catch block for handling the most specific exceptions must
always be placed above the catch block written to handle the more general exceptions.
1 try {
try {
// code that can throw IOException or its subtypes
} catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
} catch (IOException e){
// handle FileNotFoundException only
}
Q26) Does the order of the catch blocks matter if the Exceptions caught by them are
not subtype or supertype of each other?
Ans) No. If the exceptions are siblings in the Exception class’s hierarchy i.e. If one
Exception class is not a subtype or supertype of the other, then the order in which their
handlers(catch clauses) are placed does not matter.
Q27) What happens if a method does not throw an checked Exception directly but
calls a method that does? What does 'Ducking' the exception mean?
Ans) If a method does not throw an checked Exception directly but calls a method that
throws an exception then the calling method must handle the throw exception or declare
the exception in its throws clause. If the calling method does not handle and declares the
exception, the exceptions is passed to the next method in the method stack. This is called
as ducking the exception down the method stack.
e.g. The code below will not compile as the getCar() method has not declared the
CarNotFoundException which is thrown by the getColor () method.
void getCar() {
getColor();
void getColor () {
throw new CarNotFoundException();
getColor();
void getColor () {
Ans) Yes you can leave the catch block without writing any actual code to handle the
exception caught.
e.g. The code below is legal but not appropriate, as in this case you will nt get any
information about the exception thrown.
try{
}catch(FileNotFound eFnf){
e.g. the catch block below catches the FileNotFound exception and rethrows it again.
}catch(FileNotFound eFnf){
throw FileNotFound();
An instance of Thread is just…an object. Like any other object in Java, it has variables
and methods, and lives and dies on the heap. But a thread of execution is an individual
process (a "lightweight" process) that has its own call stack. In Java, there is one thread
per call stack—or, to think of it in reverse, one call stack per thread. Even if you don't
create any new threads in your program, threads are back there running.
The main() method, that starts the whole ball rolling, runs in one thread, called
(surprisingly) the main thread. If you looked at the main call stack (and you can, any time
you get a stack trace from something that happens after main begins, but not within
another thread), you'd see that main() is the first method on the stack— the method at the
bottom. But as soon as you create a new thread, a new stack materializes and methods
called from that thread run in a call stack that's separate from the main() call stack.
2. Threads have direct access to the data segment of its process; processes have their own
copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use
interprocess communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent
process.
6. Threads can exercise considerable control over threads of the same process; processes
can only exercise control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior
of the other threads of the process; changes to the parent process do not affect child
processes.
Ans)
Threads support concurrent operations. For example,
• Multiple requests by a client on a server can be handled as an individual client thread.
• Long computations or high-latency disk and network operations can be handled in the
background without disturbing foreground computations or screen updates.
2)Implements the Runnable interface.The class will have to implement the run()
method in the Runnable interface. Create an instance of this class. Pass the reference of
this instance to the Thread constructor a new thread of execution will be created. e.g.
class
1) New – When a thread is instantiated it is in New state until the start() method is called
on the thread instance. In this state the thread is not considered to be alive.
2) Runnable – The thread enters into this state after the start method is called in the
thread instance. The thread may enter into the Runnable state from Running state. In this
state the thread is considered to be alive.
3) Running – When the thread scheduler picks up the thread from the Runnable thread’s
pool, the thread starts running and the thread is said to be in Running state.
4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not
runnable. The thread switches to this state because of reasons like wait method called or
sleep method has been called on the running thread or thread might be waiting for some
i/o resource so blocked. 5) Dead – When the thread finishes its execution i.e. the run()
method execution completes, it is said to be in dead state. A dead state can not be started
again. If a start() method is invoked on a dead thread a runtime exception will occur.
Q7) What is the difference when the synchronized keyword is applied to a static
method or to a non static method?
Ans) When a synch non static method is called a lock is obtained on the object. When a
synch static method is called a lock is obtained on the class and not on the object. The
lock on the object and the lock on the class don’t interfere with each other. It means,
a thread accessing a synch non static method, then the other thread can access the synch
static method at the same time but can’t access the synch non static method.
Ans) In general each thread has its own copy of variable, such that one thread is not
concerned with the value of same variable in the other thread. But sometime this may not
be the case. Consider a scenario in which the count variable is holding the number of
times a method is called for a given class irrespective of any thread calling, in this case
irrespective of thread access the count has to be increased so the count variable is
declared as volatile. The copy of volatile variable is stored in the main memory, so every
time a thread access the variable even for reading purpose the local copy is updated each
time from the main memory. The volatile variable also have performance issues.
Ans)
2) sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes
into sleep state it doesn’t release the lock. wait() allows thread to release the lock and
goes to suspended state. The thread is only active when a notify() or notifAll() method is
called for the same object.
Ans) notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first.
Q12) What happens if a start method is not invoked and the run method is directly
invoked?
Ans) If a thread has been instantiated but not started its is said to be in new state. Unless
until a start() method is invoked on the instance of the thread, it will not said to be alive.
If you do not call a start() method on the newly created thread instance thread is not
considered to be alive. If the start() method is not invoked and the run() method is
directly called on the Thread instance, the code inside the run() method will not run in a
separate new thread but it will start running in the existing thread.
Ans) A new thread of execution with a new call stack starts. The state of thread changes
from new to runnable. When the thread gets chance to execute its target run() method
starts to run.
Q14) If code running is a thread creates a new thread what will be the initial
priority of the newly created thread?
Ans) When a code running in a thread creates a new thread object , the priority of the
new thread is set equal to the priority of the thread which has created it.
Q15) When jvm starts up, which thread will be started up first?
Ans) When jvm starts up the thread executing main method is started.
Ans) Daemon thread are service provider threads run in the background,these not used to
run the application code generally.When all user threads(non-daemon threads) complete
their execution the jvm exit the application whatever may be the state of the daemon
threads. Jvm does not wait for the daemon threads to complete their execution if all user
threads have completed their execution.
To create Daemon thread set the daemon value of Thread using setDaemon(boolean
value) method. By default all the threads created by user are user thread. To check
whether a thread is a Daemon thread or a user thread use isDaemon() method.
Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused
memory by the application. The Garbage collector code runs in a Daemon thread which
terminates as all the user threads are done with their execution.
Ans) Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)
Ans) Yes a class can have both synchronized and non-synchronized methods.
Ans) Yes. If a class has a synchronised and non-synchronised methods, multiple threads
can access the non-synchronised methods.
Q2) If a thread goes to sleep does it hold the lock?
Ans) Yes when a thread goes to sleep it does not release the lock.
Ans) Yes. A thread can hold multiple locks at the same time. Once a thread acquires a
lock and enters into the synchronized method / block, it may call another synchronized
method and acquire a lock on another object.
Q4) Can a thread call multiple synchronized methods on the object of which it hold
the lock?
Ans) Yes. Once a thread acquires a lock in some object, it may call any other
synchronized method of that same object using the lock that it already holds.
Ans) Yes. As static methods are class methods and have only one copy of static data for
the class, only one lock for the entire class is required. Every class in java is represented
by java.lang.Class instance. The lock on this instance is used to synchronize the static
methods.
Q6) Can two threads call two different static synchronized methods of the same
class?
Ans) No. The static synchronized methods of the same class always block each other as
only one lock per class exists. So no two static synchronized methods can execute at the
same time.
Ans)No As the thread executing the static synchronized method holds a lock on the class
and the thread executing the non-satic synchronized method holds the lock on the object
on which the method has been called, these two locks are different and these threads do
not block each other.
Ans) No. Only a thread can be started only once in its lifetime. If you try starting a thread
which has been already started once an IllegalThreadStateException is thrown, which is a
runtime exception. A thread in runnable state or a dead thread can not be restarted.
Ans) If a class is made to extend the thread class to have a multithreaded application then
this subclass of Thread can not extend any other class and the required application will
have to be added to this class as it can not be inherited from any other class. If a class is
made to implement Runnable interface, then the class can extend other class or
implement other interface.
Q11) Can the start() method of the Thread class be overridden? If yes should it be
overridden?
Ans) Yes the start() method can be overridden. But it should not be overridden as it’s
implementation in thread class has the code to create a new executable thread and is
specialised.
Q12) What are the methods of the thread class used to schedule the threads?
Q15) List the methods which when called the thread does not release the locks held?
• notify()
• join()
• sleep()
• yield()
Q16) List the methods which when called on the object the thread releases the locks
held on that object?
Ans) wait()
Ans) Yes each thread has its own call stack. For eg
In the above example t1 and t3 will have the same stack and t2 will have its own
independent stack.
Ans) ThreadLocal is a class. If a variable is declared as threadLocal then each thread will
have a its own copy of variable and would not interfere with the other's thread copy.
Typical scenario to use this would be giving JDBc connection to each thread so that there
is no conflict.
ThreadLocal class by JAVA API
public class ThreadLocal {
public Object get();
public void set(Object newValue);
public Object initialValue();
}
Implementation of ThreadLocal
public class ConnectionDispenser {
private static class ThreadLocalConnection extends ThreadLocal {
public Object initialValue() {
return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
}
}
Ans) Inner class is a class defined inside other class and act like a member of the
enclosing class.
Ans) A static member class behaves much like an ordinary top-level class, except that it
can access the static members of the class that contains it. The static nested class can be
accessed as the other static members of the enclosing class without having an instance of
the outer class. The static class can contain non-static and static members and methods.
static int i = 9;
int no = 6;
}
}
The static inner class can be accessed from Outer Class in the following manner:
InnerClass.StaticInner staticObj= new InnerClass. StaticInner ();
No outer class instance is required to instantiate the nested static class because the static
class is a static member of the enclosing class.
Ans) The different type of static inner classes are: Non - static inner classes – classes
associated with the object of the enclosing class. Member class - Classes declared
outside a function (hence a "member") and not declared "static".
The member class can be declared as public, private, protected, final and abstract. E.g.
class MemberClass {
}
}
Method local class – The inner class declared inside the method is called method local
inner class. Method local inner class can only be declared as final or abstract. Method
local class can only access global variables or method local variables if declared as final
public class InnerClass {
int i = 9;
final int k = 6;
class MethodLocal {
MethodLocal() {
System.out.println(k + i);
}
}
}
}
Anonymous inner class - These are local classes which are automatically declared and
instantiated in the middle of an expression. Also, like local classes, anonymous classes
cannot be public, private, protected, or static. They can specify arguments to the
constructor of the superclass, but cannot otherwise have a constructor. They can
implement only one interface or extend a class.
Anonymous class cannot define any static fields, methods, or classes, except for static
final constants.
Also, like local classes, anonymous classes cannot be public, private, protected, or static
Some examples:
return -1;
}else if(prt1.getAge()<prt2.getAge()) {
return 1;
} else {
return 0;
}
}
});
Q5) Does a static nested class have access to the enclosing class' non-static methods
or instance variables?
Ans) No .
Ans) The embedding of inner class into the outer class in the case when the inner class is
to be used only by one class i.e. the outer class makes the package more streamlined.
Nesting the inner class code where it is used (inside the outer class) makes the code more
readable and maintainable.
The inner class shares a special relationship with the outer class i.e. the inner class has
access to all members of the outer class and still have its own type is the main advantages
of Inner class. Advantage of inner class is that they can be hidden from the other classes
in the same package and still have the access to all the members (private also) of the
enclosing class. So the outer class members which are going to be used by the inner class
can be made private and the inner class members can be hidden from the classes in the
same package. This increases the level of encapsulation.
If a class A is written requires another class B for its own use, there are two ways to do
this. One way is to write a separate class B or to write an inner class B inside class A.
Advantage of writing the inner class B in the class A is you can avoid having a separate
class. Inner classes are best used in the event handling mechanism and to implement the
helper classes. The advantage of using inner class for event handling mechanism is that
the use of if/else to select the component to be handled can be avoided. If inner classes
are used each component gets its own event handler and each event handler implicitly
knows the component it is working for. e.g. Button btn1 = new Button("Submit");
Btn.addActionListener(new ActionListener(){/br>
Public void actionPerformed(ActionEvent ae){ submitClicked(); }
} );
The advantage of using static nested class is that to instantiate a static nested class you
need not create an instance of the enclosing class which reduces the number of objects
the application creates at runtime.
Ans) 1. Using inner class increases the total number of classes being used by the
application. For all the classes created by JVM and loaded in the memory, jvm has to
perform some tasks like creating the object of type class. Jvm may have to perform some
routine tasks for these extra classes created which may result slower performance if the
application is using more number of inner classes. 2. Inner classes get limited support of
ide/tools as compared to the top level classes, so working with the inner classes is
sometimes annoying for the developer.
class hasAnonymous{
superClass anon = new superClass(){
void doSomething() {
System.out.println(“Doing something in the Anonymous class”);
}
};
Here anon is the reference which is of type superClass which is the class extended by the
anonymous class i.e. superclass of the anonymous class. The method doSomething() is
the super class method overridden by the anonymous class.
2) Plain old anonymous class type two –
interface Eatable{
public void prepareSweets();
}
class serveMeal{
Eatable food = new Eatable(){
public void prepareSweets(){ //come implementation code goes here }
};
}
food is reference variable of type Eatable interface which refers to the anonymous class
which is the implementer of the interface Eatable. The anonymous implementer class of
the interface Eatable implements its method prepareSweets() inside it.
3) Argument defined anonymous class – e.g.
interface Vehicle {
void getNoOfWheels();
}
class Car {
void getType(Vehical v) { }
}
class BeautifulCars {
void getTheBeautifilCar() {
Car c = new Car ();
c.getType (new Vehicle () {
public void getNoOfWheels () {
System.out.println("It has four wheels");
}
});
}
}
Anonymous class is defined as the argument of the method getTheBeautifilCar(), this
anonymous class is the implementer of the interface Vehicle. The method of class Car
getTheBeautifilCar() expects the argument as an object of type Vehicle. So first we create
an object of Car referenced by the variable ‘c’. On this object of Car we call the method
getTheBeautifilCar() and in the argument we create an anonymous class in place which is
the implementer of interface Vehicle hence of type Vehicle.
Q9) If you compile a file containing inner class how many .class files are created and
what are all of them accessible in usual way?
Ans) If a inner class enclosed with an outer class is compiled then one .class file for each
inner class an a .class file for the outer class is created. e.g.
class EnclosingOuter {
class Inner{ }
}
If you compile the above code with command
% javac EnclosingOuter.java
Two files
EnclosingOuter.class
EnclosingOuter$Inner.class
will be created. Though a separate inner class file is generated, the inner class file is not
accessible in the usual way like,
% java EnclosingOuter$Inner
Q10) How to access the inner class from code within the outer class?
Ans) The inner class is instantiated only through the outer class instance.
class EnclosingOuter {
private int noInnerClass = 1;
public void getNoOfInnerClasses(){
Inner in = new Inner();
System.out.println(“No Of Inner classes is : “+ in.getNoOfClassesFromOuter());
}
class Inner{
}
Here the method getNoOfInnerClasses() is called on the outer class’s instance through
this outer class instance the inner class instance in is created.
Q11) How to create an inner class instance from outside the outer class instance
code?
Ans) To create an instance of the inner class you must have the instance of its
enclosing class.
e.g. class EnclosingOuter {
class Inner{ }
}
To create the instance of inner class from class other than the enclosing class.
1) class OtherThanOuter{
EnclosingOuter out = new EnclosingOuter();
EnclosingOuter.Inner in = out.new Inner();
}
2) class OtherThanOuter{
EnclosingOuter.Inner out = new EnclosingOuter.Inner (); }
Q12) How to refer to the outer this i.e. outer class’s current instance from inside the
inner class?
Ans) The outer this reference i.e. the outer class’ current instance’ reference can be
refered using ‘OuterClassName.this’. E.g
class EnclosingOuter {
class Inner{
System.out.println(“Inner class reference is “ + this); // inner class instance
Q14) Can the method local inner class object access method’s local variables?
Ans) No, a method local inner class object can not access the method local variable.
Reason: The local variables are not guaranteed to live as long as the local inner class
object. The method local variable live on stack and exist only till the method lives, their
scope is limited only code inside the method they are declared in. But the local inner
class object created within the method lives on heap and it may exist even after the
method ends if in case the reference of this local inner class is passed into some other
code and is stored in an instance variable. So we can not be sure that the local variables
will live till the method local inner class object lives, therefore the method local inner
class object can not access the method local variable. To access the method local
variables, the variable has to be declared as final.
Q15) Can a method local inner class access the local final variables?Why?
Ans) Yes. Because the final variables are stored on heap and they live as long as the
method local inner class object may live.
Q16) Which modifiers can be applied to the method local inner class?
Q17) Can a local class declared inside a static method have access to the instance
members of the outer class?
Ans) No. There is no this reference available in the static method .The static method class
can not have access to any members of the outer class other than static members.
Q18) Can a method which is not in the definition of the superclass of an anonymous
class be invoked on that anonymous class reference?
Ans) No. Compilation will fail.As the reference variable type of the anonymous class will
be of superclass which will not know of any method defined inside the anonymous class
the compilation will fail.
e.g. class SuperClass{
void doSomething() {
System.out.println("In the Super class");
}
}
class hasAnonymous{
SuperClass anon = new SuperClass(){
void doSomething() {
System.out.println("In the Anonymous class");
}
void doStuff() {
System.out.println("An Anonymous class method not present in
superClass");
}
};
Ans) Yes. But there will be no way by which the methods defined in the anonymous class
which are not present in its superclass be invoked. As only those methods which are
defined in the suprclass which the anonymous class extends be invoked defining the
methods in the anonymous class will be of no use.
Ans) No. An anonymous class can implement only one interface. If the anonymous class
is extending a class then it becomes the implementer of all the interfaces implemented by
its superclass automatically.
Q21) Can an anonymous class implement an interface and also extend a class at the
same time?
Ans) No. An anonymous class can either extend a class or implement a single interface.
If the anonymous class is extending a class then it becomes the implementer of all the
interfaces implemented by its superclass automatically.
Ans) During object serialization, the default Java serialization mechanism writes the
metadata about the object, which includes the class name, field names and types, and
superclass. This class definition is stored as a part of the serialized object. This stored
metadata enables the deserialization process to reconstitute the objects and map the
stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically
computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes
the class name, sorted member names, modifiers, and interfaces to the secure hash
algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the
serialized class and compares the suid value with the one of the object. If the suid values
match then the object is said to be compatible with the class and hence it is de-serialized.
If not InvalidClassException exception is thrown.
• Add fields
• Change a field from static to non-static
• Change a field from transient to non-transient
• Add classes to the object tree
• Delete fields
• Change class hierarchy
• Change non-static to static
• Change non-transient to transient
• Change type of a primitive field
So, if no suid is present , inspite of making compatible changes, jvm generates new suid
thus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.
then if any of the metioned compatible changes are made the class need not to be
recompiled. But for incompatible changes there is no other way than to compile again.
• To send state of one or more object’s state over the network through a socket.
• To save the state of an object in a file.
• An object’s state needs to be manipulated as a stream of bytes.
Q4) Other than Serialization what are the different approach to make object
Serializable?
Ans) Besides the Serializable interface, at least three alternate approaches can serialize
Java objects:
Ans) No. Serializable is a Marker Interface. It does not have any methods.
Q6) What happens if the object to be serialized includes the references to other
serializable objects?
Ans) If the object to be serialized includes the references to other objects whose class
implements serializable then all those object’s state also will be saved as the part of the
serialized state of the object in question. The whole object graph of the object to be
serialized will be saved during serialization automatically provided all the objects
included in the object’s graph are serializable.
Ans- If you try to serialize an object of a class which implements serializable, but the
object includes a reference to an non-serializable class then a ‘NotSerializableException’
will be thrown at runtime.
e.g.
Ans) No. The static variables belong to the class and not to an object they are not the part
of the state of the object so they are not saved as the part of serialized object.
Ans) These variables are not included in the process of serialization and are not the part
of the object’s serialized state.
try {
FileInputStream fis = new FileInputStream("testTransients.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (TestTransientVal) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("After de-serialization:- " + c.name + " "+ c.age);
}
Explanation –
The transient variable is not saved as the part of the state of the serailized variable, it’s
value after de-serialization is it’s default value.
Q11) Does the order in which the value of the transient variables and the state of the
object using the defaultWriteObject() method are saved during serialization
matter?
Ans) Yes. As while restoring the object’s state the transient variables and the serializable
variables that are stored must be restored in the same order in which they were saved.
Q12) How can one customize the Serialization process? or What is the purpose of
implementing the writeObject() and readObject() method?
Ans) When you want to store the transient variables state as a part of the serialized object
at the time of serialization the class must implement the following methods –
e.g.
try {
os.defaultWriteObject();
os.writeInt(noOfTranVar);
} catch (Exception e) { e.printStackTrace(); }
}
The value of transient variable ‘noOfTranVar’ is saved as part of the serialized object
manually by implementing writeObject() and restored by implementing readObject().
The normal serializable variables are saved and restored by calling defaultWriteObject()
and defaultReadObject()respectively. These methods perform the normal serialization
and de-sirialization process for the object to be saved or restored respectively.
Q13) If a class is serializable but its superclass in not , what will be the state of the
instance variables inherited from super class after deserialization?
Ans) The values of the instance variables inherited from superclass will be reset to the
values they were given during the original construction of the object as the non-
serializable super-class constructor will run.
E.g.
public class ParentNonSerializable {
int noOfWheels;
ParentNonSerializable(){
this.noOfWheels = 4;
}
ChildSerializable() {
this.noOfWheels = 8;
this.color = "blue";
}
}
try {
FileInputStream fis = new FileInputStream("superNotSerail.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (ChildSerializable) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("After :- " + c.noOfWheels + " "+ c.color);
}
The instance variable ‘noOfWheels’ is inherited from superclass which is not serializable.
Therefore while restoring it the non-serializable superclass constructor runs and its value
is set to 8 and is not same as the value saved during serialization which is 4.
Ans) true.
Ans) Java supports two type of cloning: - Deep and shallow cloning. By default shallow
copy is used in Java. Object class has a method clone() which does shallow cloning.
Ans) In shallow copy the object is copied without its contained objects.
Shallow clone only copies the top level structure of the object not the lower levels.
It is an exact bit copy of all the attributes.
The shallow copy is done for obj and new object obj1 is created but contained objects of
obj are not copied.
Figure 2: Shallow copy object obj1
It can be seen that no new objects are created for obj1 and it is referring to the same old
contained objects. If either of the containedObj contain any other object no new reference
is created
Ans) In deep copy the object is copied along with the objects it refers to. Deep clone
copies all the levels of the object from top to the bottom recursively.
When a deep copy of the object is done new references are created.
One solution is to simply implement your own custom method (e.g., deepCopy()) that
returns a deep copy of an instance of one of your classes. This may be the best solution if
you need a complex mixture of deep and shallow copies for different fields, but has a few
significant drawbacks:
• You must be able to modify the class (i.e., have the source code) or implement a
subclass. If you have a third-party class for which you do not have the source and
which is marked final, you are out of luck.
• You must be able to access all of the fields of the class’s superclasses. If
significant parts of the object’s state are contained in private fields of a
superclass, you will not be able to access them.
• You must have a way to make copies of instances of all of the other kinds of
objects that the object references. This is particularly problematic if the exact
classes of referenced objects cannot be known until runtime.
• Custom deep copy methods are tedious to implement, easy to get wrong, and
difficult to maintain. The method must be revisited any time a change is made to
the class or to any of its superclasses.
Other common solution to the deep copy problem is to use Java Object Serialization
(JOS). The idea is simple: Write the object to an array using JOS’s
ObjectOutputStream and then use ObjectInputStream to reconsistute a copy of the
object. The result will be a completely distinct object, with completely distinct referenced
objects. JOS takes care of all of the details: superclass fields, following object graphs,
and handling repeated references to the same object within the graph.
• It will only work when the object being copied, as well as all of the other objects
references directly or indirectly by the object, are serializable. (In other words,
they must implement java.io.Serializable.) Fortunately it is often sufficient to
simply declare that a given class implements java.io.Serializable and let
Java’s default serialization mechanisms do their thing. Java Object
Serialization is slow, and using it to make a deep copy requires both serializing
and deserializing.
There are ways to speed it up (e.g., by pre-computing serial version ids and defining
custom readObject() and writeObject() methods), but this will usually be the primary
bottleneck. The byte array stream implementations included in the java.io package are
designed to be general enough to perform reasonable well for data of different sizes and
to be safe to use in a multi-threaded environment. These characteristics, however, slow
down ByteArrayOutputStream and (to a lesser extent) ByteArrayInputStream .
• Shallow copying is default cloning in Java which can be achieved using clone()
method of Object class. For deep copying some extra logic need to be provided.
Ans) If we do a = clone(b)
1) Then b.equals(a)
2) No method of a can modify the value of b.
Ans) Heap
Ans) Garbage collector frees the memory occupied by the unreachable objects during the
java program by deleting these unreachable objects.
It ensures that the available memory will be used efficiently, but does not guarantee that
there will be sufficient memory for the program to run.
Ans) Yes GC is a dameon thread. A dameon thread runs behind the application. It is
started by JVM. The thread stops when all non-dameon threads stop.
Ans) An object becomes eligible for Garbage Collection when no live thread can access
it.
Q6) What are the different ways to make an object eligible for Garbage Collection
when it is no longer needed?
Ans)
1. Set all available object references to null once the purpose of creating the
object is served :
str = null;
/*String object referenced by variable str becomes eligible for GC */
}
Ans) No. The Garbage Collection can not be forced, though there are few ways by which
it can be requested there is no guarantee that these requests will be taken care of by JVM.
Ans) There are two ways in which we can request the jvm to execute the Garbage
Collection.
• 1) The methods to perform the garbage collections are present in the Runtime
class provided by java. The Runtime class is a Singleton for each java main
program.
The method getRuntime() returns a singleton instance of the Runtime class. The
method gc() can be invoked using this instance of Runtime to request the garbage
collection.
• 2) Call the System class System.gc() method which will request the jvm to
perform GC.
Ans) The finalize() method should be overridden for an object to include the clean up
code or to dispose of the system resources that should to be done before the object is
garbage collected.
Q10) If an object becomes eligible for Garbage Collection and its finalize() method
has been called and inside this method the object becomes accessible by a live thread
of execution and is not garbage collected. Later at some point the same object
becomes eligible for Garbage collection, will the finalize() method be called again?
Ans) No
Q11) How many times does the garbage collector calls the finalize() method for an
object?
Q12) What happens if an uncaught exception is thrown from during the execution
of the finalize() method of an object?
Ans) The exception will be ignored and the garbage collection (finalization) of that object
terminates.
The JSPs have a translation or a compilation process where the JSP engine
translates and compiles a JSP file into a JSP Servlet. The translated and
compiled JSP Servlet moves to the execution phase (run time) where they can
handle requests and send response.
Unless explicitly compiled ahead of time, JSP files are compiled the first time
they are accessed. On large production sites, or in situations involving
complicated JSP files, compilation may cause unacceptable delays to users first
accessing the JSP page. The JSPs can be compiled ahead of time (ie
precompiled) using application server tools/settings or by writing your own
script.
Q2) Explain the life cycle methods of a JSP?
Ans) Pre-translated: Before the JSP file has been translated and compiled into
the Servlet.
Translated: The JSP file has been translated and compiled as a Servlet.
Initialized: Prior to handling the requests in the service method the container
calls the jspInit() to initialize the Servlet. Called only once per Servlet
instance.
Servicing: Services the client requests. Container calls this method for each
request.
Out of service: The Servlet instance is out of service. The container calls the
jspDestroy() method.
Q3) What are different type of scripting elements?
Ans)
Declaration Element: is the embedded Java declaration statement, which
gets inserted at the Servlet class level.
<%! Calendar c = Calendar.getInstance(); %>
Important: declaring variables via this element is not thread-safe, because
this variable ends up in the generated Servlet as an instance variable, not
within the body of the _jspservice() method. Ensure their access is either
read-only or synchronized.
Scriptlet Elements: are the embedded Java statements, which get executed
as part of the service method.
(Note: Not recommended to use Scriptlet elements because they don’t
provide reusability and maintainability. Use custom tags (like JSTL, JSF tags,
etc) or beans instead).
<%
//Java codes
String userName=null;
userName=request.getParameter("userName");
%>
Directive Elements: A JSP element that provides global information for the
translation phase.
<%@ page import=�java.util.Date� %>
<%@ include file=�myJSP� %>
<%@ taglib uri=�tagliburi� prefix=�myTag�%>
Q4) What are the different scope values or what are the different
scope values for "jsp:usebean"?
Ans)
Ans)
Ans) No. The declaration of variables in JSP is not thread-safe, because the
declared variables end up in the generated Servlet as an instance variable, not
within the body of the _jspservice() method.
The following declaration is not thread safe: because these are declarations,
and will only be evaluated once when the page is loaded
<%! int a = 5 %>
The following declaration is thread safe: because the variables declared inside
the scriplets have the local scope and not shared.
<% int a = 5 %>;
Q7) Explain JSP URL mapping? What is URL hiding or protecting the
JSP page?
Ans) The JSP resources usually reside directly or under subdirectories (e.g.
myPath) of the document root, which are directly accessible to the user
through the URL. If you want to protect your Web resources then hiding the
JSP files behind the WEB-INF directory can protect the JSP files, css (cascading
style sheets) files, Java Script files, pdf files, image files, html files etc from
direct access. The request should be made to a servlet who is responsible for
authenticating and authorising the user before returning the protected JSP
page or its resources.
Q8) What are custom tags? Explain how to build custom tags?
Ans) Custom JSP tag is a tag you define. You define how a tag, its attributes
and its body are interpreted, and then group your tags into collections called
tag libraries that can be used in any number of JSP files. So basically it is a
reusable and extensible JSP only solution. The pre-built tags also can speed up
Web development.
Step 1
Create a Custom tag class using only doStartTag()
package myTagPkg;
public class MyTag extends TagSupport
{
int attr = null;
public int setAttr(int a ttr){this.attr = a ttr}
public int getAttr(){return attr;}
public int doStartTag() throws JspException {
.......
return 0;
}
public void release(){.....}
}
Step 2 The Tag library descriptor file (*.tld) maps the XML element names to
the tag implementations. The code sample MyTagDesc.tld is shown below:
<taglib>
<tag>
<name>tag1</name>
<tagclass>myTagPkg.MyTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>attr</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
Step 3
The web.xml deployment descriptor maps the URI to the location of the *.tld
(Tag Library Descriptor) file. The code sample web.xml file is shown below:
<web-app>
<taglib>
<taglib-uri>/WEB-INF/MyTagURI</taglib-uri>
<taglib-location>/WEB-INF/tags/MyTagDesc.tld</taglib-location>
</taglib>
</web-app>
STEP: 4
The JSP file declares and then uses the tag library as shown below:
Q9) What is the difference between custom JSP tags and JavaBeans?
Ans) In the context of a JSP page, both accomplish similar goals but the differences are:
Ans) When you invoke a forward request, the request is sent to another resource on the
server, without the client being informed that a different resource is going to process the
request. This process occurs completly with in the web container. When a sendRedirtect
method is invoked, it causes the web container to return to the browser indicating that a
new URL should be requested. Because the browser issues a completly new request any
object that are stored as request attributes before the redirect occurs will be lost. This
extra round trip a redirect is slower than forward.
Ans) Certain objects that are available for the use in JSP documents without being
declared first. These objects are parsed by the JSP engine and inserted into the generated
servlet. The implicit objects are listed below:
request
response
pageContext
session
application
out
config
page
exception
Q13) How do I prevent the output of my JSP or Servlet pages from being cached by
the browser?
Ans) You will need to set the appropriate HTTP header attributes to prevent the dynamic
content output by the JSP page from being cached by the browser. Just execute the
following scriptlet at the beginning of your JSP pages to prevent them from being cached
at the browser. You need both the statements to take care of some of the older browser
versions.
Q14) How to implement a thread-safe JSP page? What are the advantages and
Disadvantages of using it?
within your JSP page. With this, instead of a single instance of the servlet generated for
your JSP page loaded in memory, you will have N instances of the servlet loaded and
initialized, with the service method of each instance effectively synchronized. You can
typically control the number of instances (N) that are instantiated for all servlets
implementing SingleThreadModel through the admin screen for your JSP engine. More
importantly, avoid using the tag for variables. If you do use this tag, then you should set
isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access
those variables, causing a nasty race condition. SingleThreadModel is not recommended
for normal use. There are many pitfalls, including the example above of not being able to
use <%! %>. You should try really hard to make them thread-safe the old fashioned way:
by making them thread-safe .
Q15) Why to use the HttpServlet Init method to perform expensive operations that
need only be done once?
Ans) Because the servlet init() method is invoked when servlet instance is loaded, it is the
perfect location to carry out expensive operations that need only be performed during
initialization. By definition, the init() method is thread-safe. The results of operations in
the HttpServlet.init() method can be cached safely in servlet instance variables, which
become read-only in the servlet service method.
Ans) By default, JSP files create HttpSessions. This is in compliance with J2EETM to
facilitate the use of JSP implicit objects, which can be referenced in JSP source and tags
without explicit declaration. HttpSession is one of those objects. If you do not use
HttpSession in your JSP files then you can save some performance overhead with the
following JSP page directive:
<%@ page session="false"%>
Programming Questions
Q1)What is the o/p of following program?
a) 0
b) 5
c) Compilation error
d) 1
Answer
Answer is b
Q2) What is the o/p of following program?
a) 0
b) 5
c) Compilation error
d) NullPointerException
Answer
Answer is b, because static variables are related to class and not instance. Hence te
instance value doesnt hold good if a static variable is tried to access.
Q3)What is the o/p of following program?
class Father {
protected Father() {
System.out.println("Created a Father");
}
}
public class Child extends Father {
private Child() {
System.out.println("Inside child");
}
public static void main(String args[]) {
new Child();
}
a) Inside Child
b) Created a Father
c) Compilation error
d) Created a Father Inside Child
Answer
Answer is d. As a rule always the parent default constructor is called and then child
constructor.
Q4)What is the o/p of following program?
class Father {
private Child() {
System.out.println("Inside child");
}
public static void main(String args[]) {
super("Hi");
new Child();
}
a) Inside Child
b) Created a Father
c) Compilation error
d) Created a Father Hi Inside Child
Answer
Answer is c. As a rule always the parent default constructor should be always present if a
parameterized constructor is created. In this case create a default constructor for Father
class.
Q5)What is a WeakHashMap?
Answer
Answer is a.
Q6)Which of the following is/are true?
Answer
Answer is c. trim() function is only performed if blankspaces are present at the beginning
or end. If not present it will return the same string. Hence the function will return true. Bit
if the string contains blankspaces, subString() is called to trim the string and return a new
String using new operator
Q7) Which of the following lines allow main method to be executed by ClassLoader?
Answer
Answer is 3. Only final,public, static ,void is allowed with main method.
Q8) What is o/p of following program?
a) 1
b) 0
c) RunTimeException occurs
d) Compile time error 'i should be initialized'
Answer
Answer is d.final variable need to be declared always even the default value should be
mentioned explicitly.
Q1)What is the o/p of following program?
public class Question05 {
void test() {
System.out.println("In Question05Sub");
}
}
a) In Question05
b) In Question05Sub
c) Compilation error
d) In Question05
In Question05Sub
Answer
Answer is c. If the parent method throws a Checked Exception then the child class
overriding it can throw same exception or unchecked exception or any subclass of the
Exception thrown (in this case subclass of IOException)
Q2) What is the o/p of following program?
a) Print 0,1,2,3,4
b) Print 1,2,3,4
c) Compilation error
d) throws RunTimeException
Answer
Answer is c, the local variable i cannot be accessed directly inside inner class. To make it
accessible it should be declared as final.
Q3)What is the o/p of following program?
static {
System.out.println("Inside Parent static");
}
{
System.out.println("Inside Parent init");
}
public Parent(){
System.out.println("Parent Const");
}
public static void main(String args[]){
new MyChild();
}
static {
System.out.println("Inside Child static");
}
{
System.out.println("Inside Child init");
}
public MyChild(){
System.out.println("Child Const");
}
}
a) Inside Parent static
Inside Child static
Inside Parent init
Parent Const
Inside Child init
Child Const
Answer
Answer is a.
Q4)What is the o/p of following program?
a) 147
b) -109
c) Compilation error
d) Rutime error
Answer
Answer is b.
Q5)What is o/p of following program?
a) Hi
b)Compilation Error
c) Runtime Error
d) 132
Answer
Answer is a.
Q6)Which of the o/p following program?
a) Prints S r n
b) Prints t i g
c) Compilation Error
d) Prints t g
Answer
Answer is a.
Q7) Select methods that correctly overload the following method
byte bMethod(short i) throws Exception {...}
Answer
Answer is a,c,d.
Q8) What is o/p of following program?
a) 1
b) 0
c) RunTimeException occurs
d) Compile time error 'i should be initialized'
Answer
Answer is d.final variable need to be declared always even the default value should be
mentioned explicitly.
Q1)What is the o/p of following program?
new Widening1().f1(null);
}
}
Answer
new Widening1().f1(null);
}
}
Answer
a) 052
b) Compilation Error
c) 7
d)152
Answer
Answer is c. If you are caught with this, then try running it ...
Q4)What is the o/p of following program?
a) inside 1
b) inside 2
c) Compilation error
d) Rutime error
Answer
Answer is b.
Q5)Wil this code compile fine?
3 map.put("param1","value1");
4 map.put("param2","value2");
5 map=new HashMap();
}
}
a) Yes
b)No,Compilation Error at line 3
c)No, Runtime Error
d)No,Compilation Error at line 5
Answer
Answer is d.Once declared the final variable cannot be initialized again
Q6)Which of the o/p following program?
3 map.put("param1","value1");
4 map.put("param2","value2");
5 map=new HashMap();
}
}
a) Yes
b)No,Compilation Error at line 3
c)No, Runtime Error
d)No,Compilation Error at line 5
Answer
Answer is b. Non static variable cannot be used inside static variable.
Q7) What is o/p of following program
Answer
Answer
Answer is No.
|