Tuesday, May 29, 2007

java faq 4

Java Interview Questions And Answers [Java Frequently Asked Questions ,Java FAQ ] AddThis Social Bookmark Button

What are some alternatives to inheritance?
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

Why isn't there operator overloading?
Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn't even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().

What does it mean that a method or field is "static"?
Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.
Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work. out is a static field in the java.lang.System class.

Why do threads block on I/O?
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.

What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

Is null a keyword?
The null value is not a keyword.

Which characters may be used as the second character of an identifier,but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

What is the difference between notify() and notifyAll()?
notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a "writer" lock on a file might permit all "readers" to resume).

Why can't I say just abs() or sin() instead of Math.abs() and Math.sin()?
The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That's just the way it works, you'll get used to it. It's really a lot safer this way.
However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn't need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can't use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can't use it on java.lang.Math at all, because Math is a "final" class which means it can't be extended.

Why are there no global variables in Java?
Global variables are considered bad form for a variety of reasons: · Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables).
· State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state.
· When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once.
For these reasons, Java decided to ban global variables.

What does it mean that a class or member is final?
A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass.
Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it's initialized, and it must include an initializer statement where it's declared. For example,
public final double c = 2.998;
It's also possible to make a static field final to get the effect of C++'s const statement or some uses of C's #define, e.g. public static final double c = 2.998;

What does it mean that a method or class is abstract?
An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:
public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do.
Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.

What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.
The Java platform has three elements:
Java programming language
The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API)

What is the Java Virtual Machine?
The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.

What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the package?
The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.

What is native code?
The native code is code that after you compile it, the compiled code runs on a specific hardware platform.

Explain the user defined Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
// The class simply has to exist to be an exception
}

Is Java code slower than native code?
Not really. As a platform-independent environment, the Java platform can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability.

Can main() method be overloaded?
Yes. the main() method is a special method for a program entry. You can overload main() method in any ways. But if you change the signature of the main method, the entry point for the program will be gone.

What is the serialization?
The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage.

Explain the new Features of JDBC 2.0 Core API?
The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength database computing capabilities.
New Features in JDBC 2.0 Core API:

Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position
JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.
Java applications can now use the ResultSet.updateXXX methods.
New data types - interfaces mapping the SQL3 data types
Custom mapping of user-defined types (UTDs)
Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values.

How you can force the garbage collection?
Garbage collection automatic process and can't be forced.

Explain garbage collection?
Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Explain the Encapsulation principle.
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties of another object.

Explain the Polymorphism principle.
The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".

Explain the different forms of Polymorphism.
From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface

What are Access Specifiers available in Java?
ccess specifiers are keywords that determines the type of access to the member of a class. These are:
Public
Protected
Private
Defaults

Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void

Question: Read the following program:

public class test {
public static void main(String [] args) {
int x = 3;
int y = 1;
if (x = y)
System.out.println("Not equal");
else
System.out.println("Equal");
}
}

What is the result?
A. The output is “Equal”
B. The output in “Not Equal”
C. An error at " if (x = y)" causes compilation to fall.
D. The program executes but no output is show on console.


Answer: C

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

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?
Yes. It is true

Why are the interfaces more flexible than abstract classes?
--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).

What are new language features in J2SE 5.0?
Generally:
1. generics
2. static imports
3. annotations
4. typesafe enums
5. enhanced for loop
6. autoboxing/unboxing
7. varargs
8. covariant return types

What is covariant return type?
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
}
}

What is the result of the following statement?
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.

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

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 : D

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.

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 : C.

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

What are tag interfaces?
Tag interface is an alternate name for marker interface.

What are the restrictions placed on static method ?
We cannot override static methods. We cannot access any object variables inside static method. Also the this reference also not available in static methods.

What is JVM?
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.

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

What are ClassLoaders?
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.

What is Service Locator pattern?
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.

What is Session Facade pattern?
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.

What is Data Access Object pattern?
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.

Can we make an EJB singleton?
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.

How can we make a class Singleton ?
A) If the class is Serializable


class Singleton implements Serializable
{
private static Singleton instance;

private Singleton() { }

public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}

/**
If the singleton implements Serializable, then this
* method must be supplied.
*/
protected Object readResolve() {
return instance;
}

/**
This method avoids the object fro being cloned
*/
public Object clone() {
throws CloneNotSupportedException ;
//return instance;
}
}

B) If the class is NOT Serializable


class Singleton
{
private static Singleton instance;
private Singleton() { }

public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}

/**
This method avoids the object from being cloned
**/
public Object clone() {
throws CloneNotSupportedException ;
//return instance;
}

}

How is static Synchronization different form non-static synchronization?
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.

What are class members and Instance members?
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.

Name few Garbage collection algorithms?
Here they go:
Mark and Sweep
Reference counting
Tracing collectors
Copying collectors
Heap compaction
Mark-compact collectors

Can we force Garbage collection?
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.

Does Java pass by Value or reference?
Its uses Reference while manipulating objects but pass by value when sending method arguments. Those who feel why I added this simple question in this section while claiming to be maintaining only strong and interesting questions, go ahead and answer following questions.
a)What is the out put of:

import java.util.*;

class TestCallByRefWithObject
{
ArrayList list = new ArrayList(5);


public void remove(int index){
list.remove(index);
}

public void add(Object obj){
list.add(obj);
}

public void display(){
System.out.println(list);
}

public static void main(String[] args)
{
TestCallByRefWithObject test = new TestCallByRefWithObject();

test.add("1");
test.add("2");
test.add("3");
test.add("4");
test.add("5");

test.remove(4);
test.display();
}
}

b) And now what is the output of:


import java.util.*;

class TestCallByRefWithInt
{
int i = 5;


public void decrement(int i){
i--;
}

public void increment(int i){
i++;
}

public void display(){
System.out.println("\nValue of i is : " +i);
}

public static void main(String[] args)
{
TestCallByRefWithInt test = new TestCallByRefWithInt();

test.increment(test.i);

test.display();
}
}

Why Thread is faster compare to process?
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.

When and How is an object considered as Garbage by a GC?
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.






No comments: