Set - 8

Question 1 :

The superclass constructor runs before the subclass constructor. The subclass's version of the overridable method will be invoked before the subclass's constructor has been invoked. If the subclass's overridable method depends on the proper initialization of the subclass (through the subclass constructor), the method will most likely fail. Is that true?

Answer :

Yes. It is true


Question 2 :

Why are the interfaces more flexible than abstract classes?  

Answer :

An interface-defined type can be implemented by any class in a class hierarchy and can be extended by another interface. In contrast, an abstract-class-defined type can be implemented only by classes that subclass the abstract class.
An interface-defined type can be used well in polymorphism. The so-called interface type vs. implementation types.
Abstract classes evolve more easily than interfaces. If you add a new concrete method to an abstract class, the hierarchy system is still working. If you add a method to an interface, the classes that rely on the interface will break when recompiled.
Generally, use interfaces for flexibility; use abstract classes for ease of evolution (like expanding class functionality).


Question 3 :

What are new language features in J2SE 5.0?

Answer :

Generally:
1. generics
2. static imports
3. annotations
4. typesafe enums
5. enhanced for loop
6. autoboxing/unboxing
7. varargs
8. covariant return types


Question 4 :

What is covariant return type?

Answer :

A covariant return type lets you override a superclass method with a return type that subtypes the superclass method's return type. So we can use covariant return types to minimize upcasting and downcasting.

class Parent {
  Parent foo () {
    System.out.println ("Parent foo() called");
    return this;
  }
}

class Child extends Parent {
  Child foo () {
   System.out.println ("Child foo() called");
   return this;
  }
}

class Covariant {
  public static void main(String[] args) {
    Child c = new Child();
    Child c2 = c.foo(); // c2 is Child
    Parent c3 = c.foo(); // c3 points to Child
 }
}


Question 5 :

What is the result of the following statement?

Answer :

int i = 1, float f = 2.0f;
i += f; //ok, the cast done automatically by the compiler
i = i + f; //error

The compound assignment operators automatically include cast operations in their behaviors.


Question 6 :

What is externalization? Where is it useful?

Answer :

Use the Externalizable interface when you need complete control over your Bean's serialization (for example, when writing and reading a specific file format).


Question 7 :

What is a marker interface ?

Answer :

An interface that contains no methods. E.g.: Serializable, Cloneable, SingleThreadModel etc. It is used to just mark java classes that support certain capability.


Question 8 :

What are tag interfaces?

Answer :

Tag interface is an alternate name for marker interface.


Question 9 :

What are the restrictions placed on static method ?

Answer :

We cannot override static methods. We cannot access any object variables inside static method. Also the this reference also not available in static methods.


Question 10 :

What is JVM?

Answer :

JVM stands for Java Virtual Machine. It is the run time for java programs. All are java programs are running inside this JVM only. It converts java byte code to OS specific commands. In addition to governing the execution of an application's byte codes, the virtual machine handles related tasks such as managing the system's memory, providing security against malicious code, and managing multiple threads of program execution.


Question 11 :

What is JIT?

Answer :

JIT stands for Just In Time compiler. It compiles java byte code to native code.


Question 12 :

What are ClassLoaders?

Answer :

A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class. Given the name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.
Every Class object contains a reference to the ClassLoader that defined it.
Class objects for array classes are not created by class loaders, but are created automatically as required by the Java runtime. The class loader for an array class, as returned by Class.getClassLoader() is the same as the class loader for its element type; if the element type is a primitive type, then the array class has no class loader.
Applications implement subclasses of ClassLoader in order to extend the manner in which the Java virtual machine dynamically loads classes.


Question 13 :

What is Service Locator pattern?

Answer :

The Service Locator pattern locates J2EE (Java 2 Platform, Enterprise Edition) services for clients and thus abstracts the complexity of network operation and J2EE service lookup as EJB (Enterprise JavaBean) Interview Questions - Home and JMS (Java Message Service) component factories. The Service Locator hides the lookup process's implementation details and complexity from clients. To improve application performance, Service Locator caches service objects to eliminate unnecessary JNDI (Java Naming and Directory Interface) activity that occurs in a lookup operation.


Question 14 :

What is Session Facade pattern?

Answer :

Session facade is one design pattern that is often used while developing enterprise applications. It is implemented as a higher level component (i.e.: Session EJB), and it contains all the iteractions between low level components (i.e.: Entity EJB). It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design. Think of a bank situation, where you have someone that would like to transfer money from one account to another. In this type of scenario, the client has to check that the user is authorized, get the status of the two accounts, check that there are enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction otherwise is something goes south, the situation has to be restored.
As you can see, multiple server-side objects need to be accessed and possibly modified. Multiple fine-grained invocations of Entity (or even Session) Beans add the overhead of network calls, even multiple transaction. In other words, the risk is to have a solution that has a high network overhead, high coupling, poor reusability and mantainability.
The best solution is then to wrap all the calls inside a Session Bean, so the clients will have a single point to access (that is the session bean) that will take care of handling all the rest.


Question 15 :

What is Data Access Object pattern?

Answer :

The Data Access Object (or DAO) pattern: separates a data resource's client interface from its data access mechanisms adapts a specific data resource's access API to a generic client interface
The DAO pattern allows data access mechanisms to change independently of the code that uses the data.
The DAO implements the access mechanism required to work with the data source. The data source could be a persistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database, or a business service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets. The business component that relies on the DAO uses the simpler interface exposed by the DAO for its clients. The DAO completely hides the data source implementation details from its clients. Because the interface exposed by the DAO to clients does not change when the underlying data source implementation changes, this pattern allows the DAO to adapt to different storage schemes without affecting its clients or business components. Essentially, the DAO acts as an adapter between the component and the data source.


Question 16 :

Can we make an EJB singleton?

Answer :

This is a debatable question, and for every answer we propose there can be contradictions. I propose 2 solutions of the same. Remember that EJB's are distributed components and can be deployed on different JVM's in a Distributed environment
i) Follow the steps as given below
Make sure that your serviceLocator is deployed on only one JVM.
In the serviceLocator create a HashTable/HashMap(You are the right judge to choose between these two)
When ever a request comes for an EJB to a serviceLocator, it first checks in the HashTable if an entry already exists in the table with key being the JNDI name of EJB. If key is present and value is not null, return the existing reference, else lookup the EJB in JNDI as we do normally and add an entry into the Hashtable before returning it to the client. This makes sure that you maintain a singleton of EJB.
ii) In distributed environment our components/Java Objects would be running on different JVM's. So the normal singleton code we write for maintaining single instance works fine for single JVM, but when the class could be loaded in multiple JVM's and Instantiated in multiple JVM's normal singleton code does not work. This is because the ClassLoaders being used in the different JVM's are different from each other and there is no defined mechanism to check and compare what is loaded in another JVM. A solution could be(Not tested yet. Need your feedback on this) to write our own ClassLoader and pass this classLoader as argument, whenever we are creating a new Instance and make sure that only one instance is created for the proposed class. This can be done easily.


Question 17 :

How is static Synchronization different form non-static synchronization?

Answer :

When Synchronization is applied on a static Member or a static block, the lock is performed on the Class and not on the Object, while in the case of a Non-static block/member, lock is applied on the Object and not on class. [Trail 2: There is a class called Class in Java whose object is associated with the object(s) of your class. All the static members declared in your class will have reference in this class(Class). As long as your class exists in memory this object of Class is also present. Thats how even if you create multiple objects of your class only one Class object is present and all your objects are linked to this Class object. Even though one of your object is GCed after some time, this object of Class is not GCed untill all the objects associated with it are GCed.
This means that when ever you call a "static synchronized" block, JVM locks access to this Class object and not any of your objects. Your client can till access the non-static members of your objects.


Question 18 :

What are class members and Instance members?

Answer :

Any global members(Variables, methods etc.) which are static are called as Class level members and those which are non-static are called as Instance level members.


Question 19 :

Name few Garbage collection algorithms?

Answer :

Here they go:
Mark and Sweep
Reference counting
Tracing collectors
Copying collectors
Heap compaction
Mark-compact collectors


Question 20 :

Can we force Garbage collection?

Answer :

java follows a philosophy of automatic garbage collection, you can suggest or encourage the JVM to perform garbage collection but you can not force it. Once a variable is no longer referenced by anything it is available for garbage collection. You can suggest garbage collection with System.gc(), but this does not guarantee when it will happen. Local variables in methods go out of scope when the method exits. At this point the methods are eligible for garbage collection. Each time the method comes into scope the local variables are re-created.


Question 21 :

Why Thread is faster compare to process?

Answer :

A thread is never faster than a process. If you run a thread(say there's a process which has spawned only one thread) in one JVM and a process in another and that both of them require same resources then both of them would take same time to execute. But, when a program/Application is thread based(remember here there will be multiple threads running for a single process) then definetly a thread based appliation/program is faster than a process based application. This is because, when ever a process requires or waits for a resource CPU takes it out of the critical section and allocates the mutex to another process.
Before deallocating the ealier one, it stores the context(till what state did it execute that process) in registers. Now if this deallocated process has to come back and execute as it has got the resource for which it was waiting, then it can't go into critical section directly. CPU asks that process to follow scheduling algorithm. So this process has to wait again for its turn. While in the case of thread based application, the application is still with CPU only that thread which requires some resource goes out, but its co threads(of same process/apllication) are still in the critical section. Hence it directly comes back to the CPU and does not wait outside. Hence an application which is thread based is faster than an application which is process based.
Be sure that its not the competion between thread and process, its between an application which is thread based or process based.


Question 22 :

When and How is an object considered as Garbage by a GC?

Answer :

An object is considered garbage when it can no longer be reached from any pointer in the running program. The most straightforward garbage collection algorithms simply iterate over every reachable object. Any objects left over are then considered garbage.


Question 23 :

What are generations in Garbage Collection terminology? What is its relevance?

Answer :

Garbage Collectors make assumptions about how our application runs. Most common assumption is that an object is most likely to die shortly after it was created: called infant mortality. This assumes that an object that has been around for a while, will likely stay around for a while. GC organizes objects into generations (young, tenured, and perm). This tells that if an object lives for more than certain period of time it is moved from one generation to another generations( say from young -> tenured -> permanent). Hence GC will be run more frequently at the young generations and rarely at permanent generations. This reduces the overhead on GC and gives faster response time.


Question 24 :

What is a Throughput Collector?

Answer :

The throughput collector is a generational collector similar to the default collector but with multiple threads used to do the minor collection. The major collections are essentially the same as with the default collector. By default on a host with N CPUs, the throughput collector uses N garbage collector threads in the collection. The number of garbage collector threads can be controlled with a command line option.


Question 25 :

When to Use the Throughput Collector?

Answer :

Use the throughput collector when you want to improve the performance of your application with larger numbers of processors. In the default collector garbage collection is done by one thread, and therefore garbage collection adds to the serial execution time of the application. The throughput collector uses multiple threads to execute a minor collection and so reduces the serial execution time of the application. A typical situation is one in which the application has a large number of threads allocating objects. In such an application it is often the case that a large young generation is needed


Question 26 :

What is Aggressive Heap?

Answer :

The -XX:+AggressiveHeap option inspects the machine resources (size of memory and number of processors) and attempts to set various parameters to be optimal for long-running, memory allocation-intensive jobs. It was originally intended for machines with large amounts of memory and a large number of CPUs, but in the J2SE platform, version 1.4.1 and later it has shown itself to be useful even on four processor machines. With this option the throughput collector (-XX:+UseParallelGC) is used along with adaptive sizing (-XX:+UseAdaptiveSizePolicy). The physical memory on the machines must be at least 256MB before Aggressive Heap can be used.


Question 27 :

What is a Concurrent Low Pause Collector?

Answer :

The concurrent low pause collector is a generational collector similar to the default collector. The tenured generation is collected concurrently with this collector. This collector attempts to reduce the pause times needed to collect the tenured generation. It uses a separate garbage collector thread to do parts of the major collection concurrently with the applications threads. The concurrent collector is enabled with the command line option -XX:+UseConcMarkSweepGC. For each major collection the concurrent collector will pause all the application threads for a brief period at the beginning of the collection and toward the middle of the collection. The second pause tends to be the longer of the two pauses and multiple threads are used to do the collection work during that pause. The remainder of the collection is done with a garbage collector thread that runs concurrently with the application. The minor collections are done in a manner similar to the default collector, and multiple threads can optionally be used to do the minor collection.


Question 28 :

When to Use the Concurrent Low Pause Collector?

Answer :

Use the concurrent low pause collector if your application would benefit from shorter garbage collector pauses and can afford to share processor resources with the garbage collector when the application is running. Typically applications which have a relatively large set of long-lived data (a large tenured generation), and run on machines with two or more processors tend to benefit from the use of this collector. However, this collector should be considered for any application with a low pause time requirement. Optimal results have been observed for interactive applications with tenured generations of a modest size on a single processor.


Question 29 :

What is Incremental Low Pause Collector?

Answer :

The incremental low pause collector is a generational collector similar to the default collector. The minor collections are done with the same young generation collector as the default collector. Do not use either -XX:+UseParallelGC or -XX:+UseParNewGC with this collector. The major collections are done incrementally on the tenured generation. This collector (also known as the train collector) collects portions of the tenured generation at each minor collection. The goal of the incremental collector is to avoid very long major collection pauses by doing portions of the major collection work at each minor collection. The incremental collector will sometimes find that a non-incremental major collection (as is done in the default collector) is required in order to avoid running out of memory.


Question 30 :

When to Use the Incremental Low Pause Collector?

Answer :

Use the incremental low pause collector when your application can afford to trade longer and more frequent young generation garbage collection pauses for shorter tenured generation pauses. A typical situation is one in which a larger tenured generation is required (lots of long-lived objects), a smaller young generation will suffice (most objects are short-lived and don't survive the young generation collection), and only a single processor is available.


Question 31 :

How do you enable the concurrent garbage collector on Sun's JVM?

Answer :

-Xconcgc options allows us to use concurrent garbage collector (1.2.2_07+)we can also use -XX:+UseConcMarkSweepGC which is available beginning with J2SE 1.4.1.


Question 32 :

What is a platform?

Answer :

A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000 and XP, Linux, Solaris, and MacOS.


Question 33 :

What is transient variable?

Answer :

Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.


Question 34 :

How to make a class or a bean serializable?

Answer :

By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable.


Question 35 :

What restrictions are placed on method overloading?

Answer :

Two methods may not have the same name and argument list but different return types.


Question 36 :

Name Container classes.

Answer :

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane


Question 37 :

What is the List interface?

Answer :

The List interface provides support for ordered collections of objects.


Question 38 :

What is the difference between a Scrollbar and a ScrollPane?

Answer :

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.


Question 39 :

What is tunnelling?

Answer :

Tunnelling is a route to somewhere. For example, RMI tunnelling is a way to make RMI application get through firewall. In CS world, tunnelling means a way to transfer data.


Question 40 :

What is meant by "Abstract Interface"?

Answer :

First, an interface is abstract. That means you cannot have any implementation in an interface. All the methods declared in an interface are abstract methods or signatures of the methods.


Question 41 :

Can Java code be compiled to machine dependent executable file?

Answer :

Yes. There are many tools out there. If you did so, the generated exe file would be run in the specific platform, not cross-platform.


Question 42 :

Do not use the String contatenation operator in lengthy loops or other places where performance could suffer. Is that true?

Answer :

Yes.


Question 43 :

What method is used to specify a container's layout?

Answer :

The setLayout() method is used to specify a container's layout.


Question 44 :

Which containers use a FlowLayout as their default layout?

Answer :

The Panel and Applet classes use the FlowLayout as their default layout.


Question 45 :

What state does a thread enter when it terminates its processing?

Answer :

When a thread terminates its processing, it enters the dead state.


Question 46 :

What is the Collections API?

Answer :

The Collections API is a set of classes and interfaces that support operations on collections of objects.


Question 47 :

What is the List interface?

Answer :

The List interface provides support for ordered collections of objects.


Question 48 :

Is sizeof a keyword?

Answer :

The sizeof operator is not a keyword in Java.


Question 49 :

Which class is the superclass for every class.

Answer :

Object.


Question 50 :

Which Container method is used to cause a container to be laid out and redisplayed?

Answer :

validate()


Question 51 :

What's the difference between a queue and a stack?

Answer :

Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule


Question 52 :

What comes to mind when you hear about a young generation in Java?

Answer :

Garbage collection.


Question 53 :

You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

Answer :

Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.


Question 54 :

What comes to mind when someone mentions a shallow copy in Java?

Answer :

Object cloning.
If you're overriding the method equals() of an object, which other method you might also consider?
hashCode()


Question 55 :

You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?

Answer :

ArrayList


Question 56 :

How would you make a copy of an entire Java object with its state?

Answer :

Have this class implement Cloneable interface and call its method clone().


Question 57 :

What will be the output on executing the following code.

public class MyClass {
	public static void main (String args[] ) {
		int abc[] = new int [5];
		System.out.println(abc);
	}
}


A). Error array not initialized
B). 5
C). null
D). Print some junk characters
Answer : Option D

Explanation :

It will print some junk characters to the output. Here it will not give any compile time or runtime error because we have declared and initialized the array properly. Event if we are not assigning a value to the array, it will always initialized to its defaults.


Question 58 :

What will be the output on executing the following code.

public class MyClass {
	public static void main (String args[] ) {
		int abc[] = new int [5];
		System.out.println(abc[0]);
	}
}


A). Error array not initialized
B). 5
C). 0
D). Print some junk characters
Answer : Option C