Thursday, March 8, 2012

Difference between SAX and DOM parsers?


SAX Parser:
·        A SAX (Simple API for XML) parser does not create any internal structure. Instead, it takes the occurrences of components of an input document as events, and tells the client what it reads as it reads through the input document.
·        A SAX parser serves the client application always only with pieces of the document at any given time.
·        A SAX parser, however, is much more space efficient in case of a big input document (because it creates no internal structure). What’s more, it runs faster and is easier to learn than DOM parser because its API is really simple. But from the functionality point of view, it provides a fewer functions, which means that the users themselves have to take care of more, such as creating their own data structures.
DOM Parser:
·        A DOM (Document Object Model) parser creates a tree structure in memory from an input document and then waits for requests from client.
·        A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.
·        A DOM parser is rich in functionality. It creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree. But it is space inefficient when the document is huge, and it takes a little bit longer to learn how to work with it.

Thursday, March 1, 2012

Interview Question faq

Difference B/w Method overriding and Method hiding?
class Foo {
    public static void classMethod() {
        System.out.println("classMethod() in Foo");
    }

    public void instanceMethod() {
        System.out.println("instanceMethod() in Foo");
    }
}

class Bar extends Foo {
    public static void classMethod() { //this is method overriding
        System.out.println("classMethod() in Bar");
    }

    public void instanceMethod() {   //this is method overriding 
        System.out.println("instanceMethod() in Bar");
    }
}

class Test {
    public static void main(String[] args) {
        Foo f = new Bar();  //This is method hidding
        f.instanceMethod();
        f.classMethod();
    }
}









1. What is the difference between an Interface and Abstract class ?

· A class may implement several interfaces where as it can extend only one abstract class.



· An interface cannot provide any code at all, much less default code where as an abstract class can provide complete code, default code, and/or just stubs that has to be overridden.


· Static final constants can use the interfaces without qualification in classes that implement the interface where as both static constants and instance variables can use the abstract classes.


· Interface implementation can be added to any existing third part classes where as third party classes must be rewritten to extend from the abstract classes.


· Interfaces are used to often represent peripheral ability of a class, not central identity where as abstract class defines core identity of its descendants.


· If various implementations share is method signature then Interface works best where as If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best. 


· Interface is slow where as abstract class is fast in performance.


· If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method
where as in case of an abstract class if you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.


· You can put shared code into an abstract class, where you cannot into an interface. 



2. How do you write user-defined exceptions in Java? 



· To write user-defined exception in java, you exception class should extend Exception base class have call the super class methods in your own methods.




3. What is multiple inheritance? Is it supported in java? 


· This means one object having multiple parents, which is not truly supported in java but supported in C++. But overall design of java suggests that we can implement multiple inheritances in java using interfaces.



4. What is difference between an inner class and static inner class? 



· A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.


5. What is an inner class and what is its advantage? 



· Inner class is class, which is defined inside a class as private class and always bears a reference to the outer class.


o Inner classes can be nested within the body of a method.


· Scope of inner class is the entire enclosing class in which the inner class is nested.


· Inner classes can access attributes and methods in nesting class.


· Each inner class is compiled into a separate. class file labeled:NestingClass$InnerClass.


· Inner classes can contain methods that return handles to inner class instances.


· Major advantage of inner classes is the ability to create adaptor classes that implement an interface.


o Make all inner classes private to ensure hidden implementation.


o Rather than handle classes returning inner classes, they return interfaces.


· Inner classes frequently used with event handling in applets.


6. What is a transient variable? 


o The variable, which cannot be serialized, is known as transient variable.


7. What are wrapped classes? 



o Wrapped classes are classes that allow primitive types to be accessed as objects.




8. What is an immutable object and what are its advantages? 


· An immutable object is an object and any object it references that does not change after construction. The object is, therefore, immutable for its lifetime.


· Immutable classes are commonly used to represent strings, colors, and numeric values.
Advantage:


· They guarantee that their state cannot change after construction, they are inherently thread-safe.




9. What are basic rules, which govern creation of immutable classes? 


· Declare the class final.


· Declare all data private.


· Provide only getter methods and no setter methods.


· Set all instance data in the constructor.


· Clone mutable objects for which a reference to them is returned.


· Clone mutable objects for which a reference to them is received. 


· Implement a deep clone if the default shallow clone is not correct for a properly behaved immutable object.




10. What is a Java package and how is it used?
· A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces



11.What restrictions are placed on method overriding? 




· Overridden methods must have the same name, argument list, and return type.


· The overriding method may not limit the access of the method it overrides.


· The overriding method may not throw any exceptions that may not be thrown by the overridden method.



12. What is use of this and super key words? 



· ‘this’ is used for referring to current instance of the object where as ‘super’ is used to refer to variables and methods of its super class.


· Incase of constructors, this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.




13. What is the difference between a static and non-static variable? 


· A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.




14. What is polymorphism and what are different types of polymorphism? 


· One name, different form and there are three forms.


1. Method overloading


2. Method overriding through Interfaces


3. Method overriding through java interfaces.




15. What is the essence of run-time polymorphism behavior? 



With runtime polymorphism based on method overriding, the decision as to which version of a method will be executed is based on the actual type of object whose reference is stored in the reference variable, and not on the type of the reference variable on which the method is invoked. 
The decisions as to which version of the method to invoke cannot be made at compile time. That decision must be deferred and made at runtime. This is sometimes referred to as late binding.


16. What is a singleton class and how to implement it? What are the advantages of Singleton class? 


Singleton classes are created to have only one instance.
A singleton may be used to represent some unique system.
It is generally implemented by keeping the constructor private.
It should have static members and methods.
The main advantage of singleton class is memory management( Garbage collection)


17. Why java prohibits use of ‘synchronized’ inside a constructor ?
Because other threads cannot get a reference to the object until construction of the object completes. This has got a performance overhead.



18. What do you mean by Garbage collection and what are its advantages and disadvantages? 


The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed.


An object is eligible for garbage collection when its reference is set to null. Method variables or local variables are eligible for Garbage collection when they go out of scope. 


Garbage Collection cannot be forced explicitly. JVM may do garbage collection if it is running short of memory.The call System.gc() does NOT force the garbage collection but only suggests that the JVM may make an effort to do garbage collection.


It frees up the heap space and takes care of heap fragmentation.


It also helps to ensure program integrity as programmers are unable to crash the JVM by incorrectly freeing the memory accidentally or purposefully.


The only disadvantage is garbage-collected heap is a performance overhead.


19.What do you mean by conservative garbage collector? 


The garbage collectors that cannot distinguish between genuine object references and look-alikes.


20. Can an object's finalize () method be invoked while it is reachable? 


An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.
21. How many times may an object's finalize() method be invoked by the garbage collector and when it is invoked ? 


An object's finalize() method may only be invoked once by the garbage collector when the object is unreachable.


22. Does garbage collection guarantee that a program will not run out of memory? 


Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.



23. How does the distributed garbage collection work in java? 



· The RMI subsystem implements a reference counting-based distributed garbage collection (DGC) algorithm to provide automatic memory management facilities for remote server objects.


· Basically, DGC works by having the remote server keep track of all external client references to it at any given time. When a client obtains a remote reference, it is addded to the remote object's referenced set. The DGC then marks the remote object as dirty and increases its reference count by one. When a client drops a reference, the DGC decreases its reference count by one, and marks the object as clean.


When the reference count reaches zero, the remote object is free of any live client references. It is then placed on the weak reference list and subject to periodic garbage collection.



24.What is the priority of Garbage collection thread in java ? 



This is a low-priority thread in java.



25. How many applications can be run by one run-time instance of JVM ? 



One run-time instance of java application can run only one instance.
26.When the JVM terminates ? 


The Java Virtual machine terminates when all the non-daemon threads of java application terminates.
If permitted by the security manager it can also call System.runtime.ext () for terminating the JVM.


27. Is it possible to know from the content of a class file whether it is a java class file or not?
The first four bytes of every java class file is a magic number “0xCAFEBABE”. So it is very easy to identify whether it is a java class file or not.




28.Name the process thru which JVM makes the types available to the running program? 



The Java Virtual Machine makes types available to the running program through a process of loading, linking, and initialization.



29. Define loading, linking and initialization of java class ? 



Loading : Loading is the process of bringing a binary form for a type into the Java Virtual Machine.

Linking :
 Linking is the process of incorporating the binary type data into the runtime state of the virtual machine. Linking is divided into three sub-steps: verification, preparation, and resolution. 


Initialization:
 During initialization the class variables are their proper initial values.




30. What do you mean by first active use of a class in JVM? 





· The invocation of a constructor on a new instance of the class.


· The creation of an array that has the class as its an element type.


· The invocation of a method declared by the class (not inherited from a super class) .


· The use or assignment of a field declared by the class (not inherited from a superclass or super interface), except for fields that are both static and final, and are initialized by a compile-time constant expression.


31. What are steps involved in loading of a class file into JVM?
· Produce a stream of binary data that represents the type.



· Parse the stream of binary data into internal data structures in the method area.


· Create an instance of class java.lang.Class that represents the type.




32.Is it possible to detect a malformed class file during early loading by the class loader? 


No it is not possible. If a class loader encounters a missing or malformed class file during early loading, it must wait to report that error until the class is first active use by the program.


33.What are the different stages of linking after the class is loaded? 


Verification, prepare and resolve are the three phases of linking.




34. What is verification stage and what are steps involved during verification? 


It ensures that the types obey the semantics of java language and doesn’t violate the integrity of JVM.


The entire process of detecting any kind of problem with loaded types is placed under the category of verification. 


Verification of symbolic references and converting them to direct references.


· checking that final classes are not sub classed


· checking that final methods are not overridden


· if the type being checked is a non-abstract class, checking that all the methods declared in any
interfaces implemented by the class are indeed implemented by the class


· Making sure no incompatible method declarations (such as two methods that have the same name, the same number, order, and types of parameters, but different return types) appear between the type and its supertypes.


35. What is done during Preparation Stage?

The Java Virtual Machine allocates memory for the class variables and sets them to default initial values. The class variables are not initialized to their proper initial values until the initialization phase.


Java Virtual Machine implementations may also allocate memory for data structures that are intended to improve the performance of the running program.


36. What happens during Resolution Phase?
Resolution is the process of locating classes, interfaces, fields, and methods referenced symbolically from a types constant pool, and replacing those symbolic references with direct references.



37. How the initialization of class is is different from initialization of interface? 


Initialization of class requires initialization of its super classes but initialization of interfaces doesn’t require initialization of it super interfaces.


38. What is a JIT compiler? 


JIT compilers are used to convert the java byte codes to native types on the fly.



39. What is the difference between instance method and class method ? 



· Instance methods require an instance before they can be invoked; class methods do not.
· Instance methods use dynamic (late) binding; class(static methods) methods use static (early) binding.

40. What is the difference between a process and Thread? 



A process is a self-contained running program within its own address space while a Thread is a single sequential flow of control within a process.


Each process has its own set of variables where as Threads share the same data.


Inter-process communication is much slower and restrictive as compared to inter-thread 
communication is faster.


Creating and destroying Thread is much cheaper in terms of performance overhead as compared to launching a new process.


41. What is the difference between pre-emptive multi-tasking and co-operative multi-tasking? 


In case of pre-emptive multitasking, the program is interrupted without consulting first where as in case of co-operative multitasking; programs are interrupted only when they are willing to yield control.


Windows 95,NT – pre-emptive multi-tasking where Windows 3.1 is co-operative multitasking.
Pre-emptive multi-tasking is more effective as compared co-operative multitasking.




42. What is difference between creating a thread by extending Thread class and implementing Runnable? 


Explain the four different states of a thread 


The four different states of a thread are 


New: When a thread is created with new operator .It is not yet running.


Runnable: Once you invoke the start method on the thread it becomes runnable. It is up to the OS to decide when to give time to the thread to run. A runnable thread may or may not be running.

Blocked : 
Thread enters this state under the following condition. 

Someone calls sleep () on the thread.


Thread calls an operation that blocks on input/output.
Thread calls wait() method.
Thread tries to lock an object that is currently locked by another thread.

Dead : 
The Thread is dead for one of two reasons.



It dies a natural death because the run method exits normally.
It dies abruptly because an uncaught exception terminates the run method.


43What happens when there are more than one highest priority threads having same priority? 


In that case only one of the thread is picked up. It is up to the thread Scheduler to arbitrate between threads of same priority.
There is no guarantee that all the same priority threads will be fairly treated. 


44. Why do threads block on I/O ?
Threads block on I/O so that other threads may execute while the I/O operation is performed.



45. What are the methods which can only be called from within a Synchronized method or block ? 

Notify ():
 unblocks one randomly selected thread among the threads that called wait() on this object.


NoitifyAll() :
 unblocks the threads that called wait() on this object.


Wait ():
 causes the thread to wait until it is notified.



46. What is the difference between yield and sleep methods of Thread?
When a task invokes its yield () method, it returns to the ready state. When a task invokes its sleep () method, it returns to the waiting state.



47.Java can be extended to do anything the machine can do


In theory a Java applet can do anything: manipulate 3D VRML models, play movies, make sounds, you name it. In practice it's a lot more limited. We've already seen one important limitation: an applet has control of its region of the page but no ability to operate elsewhere on the page. But here's a more serious one: an applet can do only what the run time environment allows. Today that's limited to some low level graphics, user interfaces (buttons, menus, text fields and the like), reading and writing files (under strict security guidelines), playing a sound file and some network capabilities.


What's missing? There is no way today to control a VRML model. And what if we want to do more to a sound file than just play it? What if we want to change the volume? Or do a fade in? Or add a reverb? None of these effects exist today in Java's official bag of tricks. (Some are available through undocumented classes that Sun ships with the JDK. Anything undocumented is risky, since there's no support, no guarantee of compatible behavior across platforms and no guarantee that these interfaces won't change. Caveat Emptor.) Anything that Java doesn't support would need to be written in a fully compiled language like C and then made available to the Java run time environment.


And therein lies the real limitation. To do more than Java can do today requires that we do two things: write new libraries that can be used by the Java interpreter; and then make each of those libraries available on every single system that might try to use these new capabilities. An applet is only usable if the capabilities on which it depends are available wherever we want to run them. Because although we can download applets at the moment we want to run them, we can't do the same with the underlying libraries. Java's built-in security makes downloading an applet low in risk; the same can't be said for arbitrary code libraries which do the low level work.


So Java is limited by the pervasiveness of support libraries. We need general 2D and 3D graphics, sound and video manipulation and other multimedia capabilities on every system with a Java-enabled browser. Then we won't be quite so limited. This is the plan for SGI's Cosmo 3D and Sun's Java Media, cross-platform libraries that will extend Java into 3D graphics, sound, video and animation.
48.Java in a browser eliminates the need for CGI scripts and programs


Java applets will replace some uses of the Common Gateway Interface. Prior to Java, the only way to create a web page whose contents are not static was through CGI scripts or programs running on the web server. In some cases, this server-side code can be replaced conveniently by Java applets running in the browser. In many situations, however, browser-side Java can't be used in place of CGI. The reasons may involve security (do we want password validation code running in the interpretive Java environment, where a clever user could disassemble them?) or performance constraints that Java's interpretive environment can't satisfy.


In a lot of cases, Java will let us do things that CGI supported badly if at all. Client pull and server push are brute force, high overhead techniques for creating interactive pages. By eliminating the need to communicate with a server, we can create truly interactive pages. An example is this clock applet, which tells me that I have owned the disordered.org domain for an unknown number of days (an unknown number of weeks or an unknown number of years). These three instances of a particular applet class share a thread, which updates their display every eight seconds. A CGI-based equivalent would require communication with the server on every update.




In the short term, we may have to use CGI mechanisms simply because Java doesn't give us access to the resources we need. To write a web browser-based database query application, we would set up a form to capture the input and ship it off to a CGI script on the server. This server-side program would validate the data, run a query against the database and generate a new HTML page with the result. A Java applet could be used to replace server-side data validation, thereby improving user response in cases where the input is invalid. (No wait for the browser to communicate with the server and the server to send the error back.) If we have a Java class interface to the database (and our concerns about security don't keep us from using it), we could implement the query and display in Java as well and eliminate the server-side code.


This discussion ignores two other points: that JavaScript will sometimes be a preferable to Java for browser-side programming; and there are now opportunities to invoke server-side Java code in the form of servlets. Java on the server has many of the same advantages and disadvantages over other server-side languages that Java has as an application language. A large advantage of Java servlets is that it saves the process creation overhead inherent in CGI, particularly in situations where there will be multiple interactions between browser and server to satisfy a request; there are disadvantages as well in the increased complexity of the debugging environment for such code.
49.Java's performance problems are temporary; it'll soon be as fast as C++


Right now Java is slow: slow to load, slow to start and slow to execute. Load time can be attributed in part to Java's insistence on storing each class in a separate file and using a separate HTTP request to retrieve it. Changing to an archive that stores a bunch of classes in a single file should help quite a bit. Start time is related to load time (classes are loaded the first time they're invoked, not at startup), but also includes late binding time. In essence, every time we run a Java applet we're paying a startup penalty so the developer doesn't have to do a link step. Since the Java classes don't change all that often, doing the link and placing the linked classes in an archive is generally preferable.


This leaves execution performance as the biggest problem. And a problem it is, with Java code taking an average of twenty times longer than native C++ code. Of course, an average tells you nothing about how a specific program will behave: some Java applets run nearly as fast as C++ (likely because most of their work takes place in native code run time libraries), while others run more like fifty times slower.


The best solution to this difference in performance is to translate Java source or byte code into native code. Most platforms have native code translators either already available or under development. Native translation can make a huge difference in performance for Java applications; when applied to applets in the form of just-in-time translators they provide similar gains at the expense of a small increase in startup overhead. Suddenly Java that runs twenty times as long as C++ can get a lot closer.


So how close can Java get? Will it ever reach the point where it can replace other languages for performance-critical tasks? Does it make sense to write compute-intensive codes in Java and design the Java run time to take advantage of multiprocessor architectures?


For a lot of reasons, Java is likely to always be slower than C++ and Fortran for the typical application. (A range of 50% to 300% slower than C++ has been suggested as the practical limit of Java performance improvements.) Some of these reasons are:


Reliance on pointers for objects: Every Java object access means a pointer dereference; C++ programmers have the option of either linking objects with pointers or placing one object inside the other, thereby eliminating a level of indirection.
Reliance on heap storage for objects: While basic types (int, float, etc.) can reside on the stack, objects in Java can only be allocated on the heap. This means more work for the memory manager and the garbage collector. Stack-based objects are much faster to reclaim, giving another advantage to C++.


Garbage collection: While garbage collectors have their merits (they make programming a lot easier, they are a general solution to the memory reclamation problem. And for many application there is a specific solution to memory allocation and reclamation that will outperform the general one. Where performance is critical, the programmer can probably do a better job of handling this task than even the most cleverly written garbage collector (which the GC in today's Java most definitely is not).
Run time method selection: C++ gives the programmer the choice of using virtual or nonvirtual methods. Nonvirtual methods are implemented at functions, while virtual methods require an extra level of indirection through a method table. All Java methods are virtual, which means more overhead on every method invocation. This does make life a lot easier for the programmer, who doesn't have to worry about which methods are resolved when. But there is a small price to pay.


Insistence on object orientation: Although arguably better from a design, development and maintenance standpoint, object oriented programs tend to be written as a large number of small procedures. This means more frequent method invocations, which can mean slower code. C++ can be written in a more procedural fashion. In addition, C++ programmers can use inline declarations to eliminate function calling overhead. Java does not provide such programmer control.


Thread-safety: Java was designed as a multithreaded language. Thread-aware languages need thread-safe libraries, in which each procedure allows for the possibility that it will be invoked simultaneously from multiple threads. To avoid problems should this happen, the procedure must set up access locks around critical sections of code. This extra work makes thread-safe libraries slower than their unsafe equivalents, which is why most thread-safe C and C++ libraries are also supplied in unsafe versions. Since Java's run time libraries are of necessity thread-safe, they are another source of overhead in comparison to C++.


JIT translation has to be fast: Most compilers have optimization modules that perform highly sophisticated analysis on the code they generate to make it more efficient. One problem with optimization is that it increases compilation time, sometimes by quite a lot. But for performance critical applications that take a long time to run or are run regularly, the extra compilation time is more than compensated by the improved run time performance. Now apply this analysis to Java applets and just-in-time translation: instead of incurring the overhead once at compilation time, we would see it every time the byte code applet loads and is converted to native code. Clearly we don't want to wait any longer than necessary for our applet to start. This places severe limits on the kinds of optimizations that Java JIT compilers can do. Note that this constraint does not apply to Java applications, which can be compiled to native code just like C++ programs and can have a similar degree of optimization applied to them.


Java doesn't need to be as fast as C++; just fast enough: Here's where economics come into play: once Java is fast enough for most tasks, the emphasis vendors place on performance is likely to move onto some other area where they can offer differentiation. Improving performance takes a lot of work for each small gain. So once the perception of Java as a poor performer dissipates, the marketing advantage of improving performance does the same. It's is much like the situation with C++ compilers: although C++ has features like variable references that would permit it to run faster than the equivalent C using pointers, compilers don't take advantage of that opportunity to produce faster code. In at least this regard, Marketing and customer demand drive technology.


The upshot of all this is that Java will get a lot faster, but that there are likely limits on its performance. Java won't be as fast as C++; and C++ won't be as fast as Fortran. There will still likely be a need for at least a few different languages for different requirements.


50.What is JVM?
A Java Virtual Machine is a runtime environment required for execution of a Java application.Every Java application runs inside a runtime instance of some concrete implementation of abstract specifications of JVM.It is JVM which is crux of 'platform independent' nature of the language.



51.What is a JVM consisted of?
Each time a Java Application is executed then an instance of JVM ,responsible for its running,is created.A JVM instance is described in terms of subsystems, memory areas, data types, and instructions.The block diagram given below,depicts a view of Internal Architecture of JVM :



52.What is a class loader and what is its responsibilities?
The Class loader is a subsystem of a JVM which is responsible,predominantly for loading classes and interfaces in the system.Apart from this,a class loader is responsible for the following activities:-Verification of imported types(classes and interfaces)-Allocating memory for class variables and initializing them to default values.Static fields for a class are created and these are set to standard default values but they are not explicitly initialized.



The method tables are constructed for the class.-Resolving symbolic references from type to direct references The class loaders can be of two types: a bootstrap or primordial class loader and user defined class loaderEach JVM has a bootstrap class loader which loads trusted classes , including classes from Java API.JVM specs do not tell how to locate these classes and is left to implementation designers.A Java application with user defined class loader objects can customize class loading.These load untrustworthy classes and not an intrinsic part of JVM.They are written in Java,converted to class files and loaded into the JVM and installed like any other objects.If you want to read this in more details then read Chapter 8,"The Linking Model" of Inside Java 2 Virtual Machine by Bill Venners.




53. What is heap and stack?
The heap is the part of memory of JVM where all objects reside.The stack is consisted of stack frames.When a thread invokes a method,the JVM pushes a new frame onto that thread's Java stack.Each stack frame is consisted of operand stack and the local variable array.All arguments,local variables,intermediate computations and return values if any are kept in these stack corresponding to the method invoked.The stack frame on the top of the stack is called the active stack frame,which is the current place of execution.When the method completes, the virtual machine pops and discards the frame for that method.






54. How is your Java program executed inside JVM?
When JVM executes a Java application, a runtime instance of JVM is born.This runtime instance invoke main() method of Java application.The main() method of an application serves as the starting point for that application's initial thread. The initial thread can in turn fire off other threads.This thread has a program counter(PC) and Java stack.


Whenever main() method is invoked, a stack frame is pushed onto the stack,this then becomes the active tack frame.The program counter in the new Java stack frame will point to the beginning of the method.If there are more method invocations within main() method then this process of pushing new stack frame onto the stack for each method call is repeated as and when they are invoked.When a method returns, the active frame is popped from the stack and the one below becomes the active stack frame.The PC is set to the instruction after the method call and the method continues.There is only one heap corresponding to an instance of JVM and all objects created are stored here.This heap is shared by all threads created in an application.


Inside the Java virtual machine, threads come in two flavors:daemon and non- daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads.

The initial thread of an application-
-the one that begins at main()--is a non- daemon thread.A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit() method of class Runtime or System.When main() returns,it terminates the application's only non-daemon thread, which causes the virtual machine instance to exit.

55. What is Java class file's magic number? 


A Magic Number of a class file is a unique identifier for tools to quickly differentiate class files from non class files.The first four bytes of each Java class file has the magic value as 0xCAFEBABE.And the answer to why this number,I do not actually know but there may be very few sensible and acceptable options possible constructed from letters A-F which can surely not be 'CAFEFACE' or 'FADECAFE'....


56. How JVM performs Thread Synchronization?


JVM associates a lock with an object or a class to achieve mutilthreading. A lock is like a token or privilege that only one thread can "possess" at any one time. When a thread wants to lock a particular object or class, it asks the JVM.JVM responds to thread with a lock maybe very soon, maybe later, or never. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.If a thread has a lock,no other thread can access the locked data until the thread that owns the lock releases it.The JVM uses locks in conjunction with monitors.


A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code.Each monitor is associated with an object reference. It is the responsibility of monitor to watch an arriving thread must obtain a lock on the referenced object.When the thread leaves the block,it releases the lock on the associated object.A single thread is allowed to lock the same object multiple times.JVM maintains a count of the number of times the object has been locked. An unlocked object has a count of zero. When a thread acquires the lock for the first time, the count is incremented to one. Each time the thread acquires a lock on the same object, a count is incremented. Each time the thread releases the lock, the count is decremented. When the count reaches zero, the lock is released and made available to other threads.In Java language terminology, the coordination of multiple threads that must access shared data is called synchronization. The language provides two built-in ways to synchronize access to data: with synchronized statements or synchronized methods.The JVM does not use any special opcodes to invoke or return from synchronized methods. When the JVM resolves the symbolic reference to a method, it determines whether the method is synchronized. If it is, the JVM acquires a lock before invoking the method. For an instance method, the JVM acquires the lock associated with the object upon which the method is being invoked. For a class method, it acquires the lock associated with the class to which the method belongs. After a synchronized method completes, whether it completes by returning or by throwing an exception, the lock is released.Two opcodes, monitorenter and monitorexit are used by JVM for accomplishing this task.When monitorenter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref on the stack. If the thread already owns the lock for that object, a count is incremented. Each time monitorexit is executed for the thread on the object, the count is decremented. When the count reaches zero, the monitor is released.


57.How JVM performs Garbage Collection?


Whenever a reference to an object on heap lies dangling or no longer in use then it becomes eligible for being garbage collected by JVM.JVM specifications do not force any specific kind of garbage collection algorithm though there are several algorithms like reference counting,tracing,compacting,copying,generational etc. in place.It is very important that garbage collection should be efficient and non interfering in execution of Java programs.There is a trade off between ease of implementation versus better performance while implementing garbage collection feature for a JVM.



58. How to profile heap usage?

Try using -Xaprof to get a profile of the allocations (objects and sizes) of your application.Also try -agentlib:hprof=heap=all (or other option, try -agentlib:hprof=help for a list).





59. What will you do if VM exits while printing "OutOfMemoryError" and increasing max heap size doesn't help?
The Java HotSpot VM cannot expand its heap size if memory is completely allocated and no swap space is available. This can occur, for example, when several applications are running simultaneously. When this happens, the VM will exit after printing a message similar to the following.Exception java.lang.OutOfMemoryError: requested bytesIf you see this symptom, consider increasing the available swap space by allocating more of your disk for virtual memory and/or by limiting the number of applications you run simultaneously. You may also be able to avoid this problem by setting the command-line flags -Xmx and -Xms to the same value to prevent the VM from trying to expand the heap. Note that simply increasing the value of -Xmx will not help when no swap space is available.



60. Should one pool objects to help Garbage Collector?Should one call System.gc() periodically? 
The answer is No!Pooling objects will cause them to live longer than necessary. The garbage collection methods will be much more efficient if you let it do the memory management. The strong advice is taking out object pools.Don't call System.gc(), HotSpot will make the determination of when its appropriate and will generally do a much better job.



61. An application has a lot of threads and is running out of memory, why?
You may be running into a problem with the default stack size for threads. In Java SE 6, the default on Sparc is 512k in the 32-bit VM, and 1024k in the 64-bit VM. On x86 Solaris/Linux it is 320k in the 32-bit VM and 1024k in the 64-bit VM.On Windows, the default thread stack size is read from the binary (java.exe). As of Java SE 6, this value is 320k in the 32-bit VM and 1024k in the 64-bit VM.You can reduce your stack size by running with the -Xss option. For example:java -server -Xss64kNote that on some versions of Windows, the OS may round up thread stack sizes using very coarse granularity. If the requested size is less than the default size by 1K or more, the stack size is rounded up to the default; otherwise, the stack size is rounded up to a multiple of 1 MB.64k is the least amount of stack space allowed per thread.





62. If your program is I/O bound or running in native methods, do these activities engage JVM?
The answer is 'No'.If the program is I/O bound or running in native methods, then the VM is not involved in the consumption of CPU time. The VM technology will engage CPU for running bytecodes. Typical examples of time spent not running bytecode are graphical operations that make heavy use of native methods, and I/O operations such as reading and writing data to network sockets or database files.




63. What is the difference between interpreted code and compiled code?

An interpreter produces a result from a program, while a compiler produces a program written in assembly language and in case of Java from bytecodes.The scripting languages like JavaScript,Python etc. require Interpreter to execute them.So a program written in scripting language will directly be executed with interpreter installed on that computer,if it is absent then this program will not execute.While in case of compiled code,an assembler or a virtual machine in case of Java is required to convert assembly level code or bytecodes into machine level instructions/commands.Generally, interpreted programs are slower than compiled programs, but are easier to debug and revise.





64. Why Java based GUI intensive program has performance issues?
GUI intensive Java application mostly run underlying OS specific native libraries which is time and more CPU cycles consuming.


65.The overall performance of a Java application depends on four factors:
The design of the application

The speed at which the virtual machine executes the Java bytecodes
The speed at which the libraries that perform basic functional tasks execute (in native code)
The speed of the underlying hardware and operating system
The virtual machine is responsible for byte code execution, storage allocation, thread synchronization, etc. Running with the virtual machine are native code libraries that handle input and output through the operating system, especially graphics operations through the window system. Programs that spend significant portions of their time in those native code libraries will not see their performance on HotSpot improved as much as programs that spend most of their time executing byte codes.




66. What is 64 bit Java ?
A 64-bit version of Java has been available to Solaris SPARC users since the 1.4.0 release of J2SE. A 64-bit capable J2SE is an implementation of the Java SDK (and the JRE along with it) that runs in the 64-bit environment of a 64-bit OS on a 64-bit processor. The primary advantage of running Java in a 64-bit environment is the larger address space.This allows for a much larger Java heap size and an increased maximum number of Java Threads, which is needed for certain kinds of large or long-running applications. The primary complication in doing such a port is that the sizes of some native data types are changed. Not surprisingly the size of pointers is increased to 64 bits. On Solaris and most Unix platforms, the size of the C language long is also increased to 64 bits. Any native code in the 32-bit SDK implementation that relied on the old sizes of these data types is likely to require updating.Within the parts of the SDK written in Java things are simpler, since Java specifies the sizes of its primitive data types precisely. However even some Java code needs updating, such as when a Java int is used to store a value passed to it from a part of the implementation written in C.





67. What is the difference between JVM and JRE?
A Java Runtime Environment (JRE) is a prerequisite for running Java applications on any computer.A JRE contains a Java Virtual Machine(JVM),all standard,core java classes and runtime libraries. It does not contain any development tools such as compiler, debugger, etc. JDK(Java Development Kit) is a whole package required to Java Development which essentially contains JRE+JVM,and tools required to compile and debug,execute Java applications.