You are on page 1of 34

What is Java?

Answer: Java, formerly known as oak, is an object-oriented programming language developed by Sun. It shares many superficial similarities with C, C++, and Objective C (for instance for loops have the same syntax in all four languages); but it is not based on any of those languages, nor have efforts been made to make it compatible with them. Java is sometimes referred to as C++ ++ . The language was originally created because C++ proved inadequate for certain tasks. Since the designers were not burdened with compatibility with existing languages, they were able to learn from the experience and mistakes of previous object-oriented languages. They added a few things C++ doesnt have like garbage collection and multithreading; and they threw away C++ features that had proven to be better in theory than in practice like multiple inheritance and operator overloading. Even more importantly Java was designed from the ground up to allow for secure execution of code across a network, even when the source of that code was untrusted and possibly malicious. This required the elimination of more features of C and C++. Most notably there are no pointers in Java. Java programs cannot (at least in theory) access arbitrary addresses in memory. Furthermore Java was designed not only to be cross-platform in source form like C, but also in compiled binary form. Since this is frankly impossible across processor architectures, Java is compiled to an intermediate byte-code which is interpreted on the fly by the Java interpreter. Thus to port Java programs to a new platform all that is needed is a port of the interpreter and a few native code libraries. Finally Java was designed to make it a lot easier to write bug free code. Shipping C code has, on average, one bug per 55 lines of code. About half of these bugs are related to memory allocation and deallocation. Thus Java has a number of features to make bugs less common:

Strong Typing No unsafe constructs The language is small so its easy to become fluent. The language is easy to read and write. Obfuscated Java isnt nearly as
common as obfuscated C.

There are no undefined or architecture dependent constructs. Java is object oriented so reuse is easy. Java has concurrency.
Where did Java come from?
Answer: In the late 1970s Bill Joy thought about doing a language that would merge the best features of MESA and C. However other projects (like cofounding

Sun) intervened. In the late 1980s he got Suns engineers started on a complete revision of the UNIX operating system that involved merging SunOS4.x with AT&Ts SYSVR4. In 1989 Joy sold his Sun stock, invested heavily in Microsoft and moved out of mainstream Sun to Aspen, Colorado. By the early 90s Bill was getting tired of huge programs. He decided that he wanted to be able to write a 10,000 line program that made a difference. In late 1990 Bill wrote a paper called Further which outlined his pitch to Sun engineers that they should produce an object environment based on C++. Today Joy freely admits that C++ was too complicated and wasnt up to the job. Around this time James Gosling (of emacs fame) had been working for several months on an SGML editor called Imagination using C++. The Oak language (now Java) grew out of Goslings frustration with C++ on his Imagination project. Patrick Naughton, then of Sun, now vice-president of technology at StarWave, started the Green Project on December 5th, 1990. Naughton defined the project as an effort to do fewer things better. That December he recruited Gosling a nd Mike Sheridan to help start the project. Joy showed them his Further paper, and work began on graphics and user interface issues for several months in C. In April of 1991 the Green Project (Naughton, Gosling and Sheridan) settled on smart consumer electronics as the delivery platform, and Gosling started working in earnest on Oak. Gosling wrote the original compiler in C; and Naughton, Gosling and Sheridan wrote the runtime-interpreter, also in C. Oak was running its first programs in August of 1991. Joy got his first demos of the system that winter, when Gosling and Naughton went skiing at Joys place in Aspen. By the fall of 1992 *7, a cross between a PDA and a remote control, was ready This was demoed to Scott McNealy, Suns president, in October . He was blown away. Following that the Green Project was set up as First Person Inc., a wholly owned Sun subsidiary. In early 1993 the Green team heard about a Time-Warner request for proposal for a settop box operating system. First Person quickly shifted focus from smart consumer electronics (which was proving to be more hype than reality) to the settop box OS market, and placed a bid with Time-Warner. Fortuitously, Sun lost the bid. The Time-Warner project went nowhere, the same place it probably would have gone if Sun had won the bid. First Person continued work on settop boxes until early 1994, when it concluded that like smart consumer electronics settop boxes were more hype than reality. Without a market to be seen First Person was rolled back into Sun in 1994. However around this time it was realized that the requirements for smart consumer electronics and settop box software (small, platform independent secure reliable code) were the same requirements for the nascent web. For a third time the project was redirected, this time at the web. A prototype browser called WebRunner was written by Patrick Naughton in one weekend of inspired hacking. After additional work by Naughton and Jonathan Payne this browser became HotJava. The rest, as they say, is history.

Information in this section is primarily based on the first hand accounts of Bill Joy and Patrick Naughton .

Can a private method of a superclass be declared within a subclass?


Answer: Sure. A private field or method or inner class belongs to its declared class and hides from its subclasses. There is no way for private stuff to have a runtime overloading or overriding (polymorphism) features.

Why Java does not support multiple inheritance ?


Answer: Java DOES support multiple inheritance via interface implementation.

Why Java does not support pointers ?


Answer: Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why Java and C# shine.

What is the difference between final, finally and finalize?


Answer: * final - declare constant * finally - handles exception * finalize - helps in garbage collection

Where and how can you use a private constructor ?


Answer: Private constructor can be used if you do not want any other class to instanstiate the object , the instantiation is done from a static public method, this method is used when dealing with the factory method pattern when the designer wants only one controller (factory method ) to create the object.

In System.out.println(),what is System,out and println,pls explain?


Answer: System is a predefined final class,out is a PrintStream object and println is a built-in overloaded method in the out object.

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.

Can you make an instance of an abstract class? For example - java.util.Calender is an abstract class with a method

getInstance() which returns an instance of the Calender class.


Answer: No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you have an abstract class and you want to use a method which has been implemented, you may need to subclass that abstract class, instantiate your subclass and then call that method.

What is the output of x


Answer: When this kind of question has been asked, find the problems you think is necessary to ask before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say that the syntax is wrong. If the statement is rewritten as: x<="" statement="" true="" returned.

What is the difference between Swing and AWT components?


Answer: AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

Parsers? DOM vs SAX parser


Answer: parsers are fundamental xml components, a bridge between XML documents and applications that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD or Schema.

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/XP, Linux, Solaris, and MacOS.

What is the main difference between Java platform and other platforms?
Answer: The Java platform differs from most other platforms in that its a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components: 1. The Java Virtual Machine (Java VM) 2. The Java Application Programming Interface (Java API)

What is the Java Virtual Machine?


Answer: The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.

What is the Java API?


Answer: 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?


Answer: 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?


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

Is Java code slower than native code?


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

What is the serialization?


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

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 classs inheritance hierarchy implements Serializable or Externalizable, that class is serializable.

How many methods in the Serializable interface?


Answer: There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.

How many methods in the Externalizable interface?


Answer: There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().

What is the difference between Serializalble and

Externalizable interface?
Answer: When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your classs serialization process.

What is a transient variable?


Answer: A transient variable is a variable that may not be serialized. If you dont want some field to be serialized, you can mark that field transient or static.

Why do threads block on I/O?


Answer: Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O Operation is performed.

Which containers use a border layout as their default layout?


Answer: The Window, Frame and Dialog classes use a border layout as their default layout.

How are Observer and Observable used?


Answer: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

What is synchronization and why is it important?


Answer: 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 objects value. This oft en causes dirty data and leads to significant errors.

What are synchronized methods and synchronized statements?


Answer: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the methods object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

How are Observer and Observable used?

Answer: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

What are three ways in which a thread can enter the waiting state?
Answer: A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an objects lock, or by invoking an objects wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Can a lock be acquired on a class?


Answer: Yes, a lock can be acquired on a class. This lock is acquired on the classs Class object.

Whats new with the stop(), suspend() and resume() methods in JDK 1.2?
Answer: The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

What is the preferred size of a component?


Answer: The preferred size of a component is the minimum component size that will allow the component to display normally.

What method is used to specify a containers layout?


Answer: The setLayout() method is used to specify a cont ainers layout.

Which containers use a FlowLayout as their default layout?


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

What is thread?
Answer: A thread is an independent path of execution in a system.

What is multithreading?
Answer: Multithreading means various threads that run in a system.

How does multithreading take place on a computer with a single CPU?

Answer: The operating systems task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

How to create multithread in a program?


Answer: You have two ways to do so. First, making your class extends Thread class. Second, making your class implements Runnable interface. Put jobs in a run() method and call start() method to start the thread.

Can Java object be locked down for exclusive use by a given thread?
Answer: Yes. You can lock an object by putting it in a synchronized block. The locked object is inaccessible to any thread other than the one that explicitly claimed it

Can each Java object keep track of all the threads that want to exclusively access to it?
Answer: Yes

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


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

What invokes a threads run() method?


Answer: After a thread is started, via its start() method of the Thread class, the JVM invokes the threads run() method when the thread is i nitially executed.

What is the purpose of the wait(), notify(), and notifyAll() methods?


Answer: The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.

What are the high-level thread states?


Answer: The high-level thread states are ready, running, waiting, and dead.

What is the Collections API?


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

What is the List interface?


Answer: The List interface provides support for ordered collections of objects.

How does Java handle integer overflows and underflows?


Answer: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

What is the Vector class?


Answer: The Vector class provides the capability to implement a growable array of objects .

What modifiers may be used with an inner class that is a member of an outer class?
Answer: A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

If a method is declared as protected, where may the method be accessed?


Answer: A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

What is an Iterator interface?


Answer: The Iterator interface is used to step through the elements of a Collection.

How many bits are used to represent Unicode, ASCII, UTF16, and UTF-8 characters?
Answer: Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

What is the difference between yielding and sleeping?


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

Is sizeof a keyword?
Answer: The sizeof operator is not a keyword.

What are wrapped classes?


Answer: Wrapped classes are classes that allow primitive types to be accessed as objects. 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 byte char float int long short void

Wrapper java.lang.Byte java.lang.Character java.lang.Float java.lang.Integer java.lang.Long java.lang.Short java.lang.Void

boolean java.lang.Boolean

double java.lang.Double

Does garbage collection guarantee that a program will not run out of memory?
Answer: No, it doesnt. 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

What is the difference between preemptive scheduling and time slicing?


Answer: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Name Component subclasses that support painting.


Answer: The Canvas, Frame, Panel, and Applet classes support painting.

What is a native method?


Answer: A native method is a method that is implemented in a language other than Java.

How can you write a loop indefinitely?

Answer: for(;;)for loop; while(true)always true, etc.

Can an anonymous class be declared as implementing an interface and extending a class?


Answer: An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

What is the purpose of finalization?


Answer: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

Which class is the superclass for every class ?


Answer: Object.

What is the difference between the Boolean & operator and the && operator?
Answer: If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.

What is the GregorianCalendar class?


Answer: The GregorianCalendar provides support for traditional Western calendars.

What is the SimpleTimeZone class?


Answer: The SimpleTimeZone class provides support for a Gregorian calendar.

Which Container method is used to cause a container to be laid out and redisplayed?
Answer: validate()

What is the Properties class?


Answer: The properties class is a subclass of Hashtable that can be read from or

written to a stream. It also provides the capability to specify a set of default values to be used.

What is the purpose of the Runtime class?


Answer: The purpose of the Runtime class is to provide access to the Java runtime system.

What is the purpose of the System class?


Answer: The purpose of the System class is to provide access to system resources.

What is the purpose of the finally clause of a try-catch-finally statement?


Answer: The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

What is the Locale class?


Answer: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

What must a class do to implement an interface?


Answer: It must provide all of the methods in the interface and identify the interface in its implements clause.

What is an abstract method?


Answer: An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has no implementation (an interface of a method).

What is a static method?


Answer: A static method is a method that belongs to the class rather than any object of the class and doesnt apply to an object or even require that any objects of the class have been instantiated.

What is a protected method?


Answer: A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class.

What is the difference between a static and a non-static inner class?


Answer: A non-static inner class may have object instances that are associated with instances of the classs outer class. A static inner class does not have any object instances.

What is an objects lock and which objects have locks?


Answer: An objects lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the objects lock. All objects and classes have locks. A classs lock is acquired on the classs Class object.

When can an object reference be cast to an interface reference?


Answer: An object reference be cast to an interface reference when the object implements the referenced interface.

What is the difference between a Window and a Frame?


Answer: The Frame class extends Window to define a main application window that can have a menu bar.

What do heavy weight components mean?


Answer: Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavy weight.

Which package has light weight components?


Answer: javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.

What are peerless components?


Answer: The peerless components are called light weight components.

What is the difference between the Font and FontMetrics classes?


Answer: The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

What happens when a thread cannot acquire a lock on an object?

Answer: If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an objects lock, it enters the waiting state until the lock becomes available.

What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
Answer: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

What classes of exceptions may be caught by a catch clause?


Answer: A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

What is the difference between throw and throws keywords?


Answer: The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that designates that exceptions may come out of the method, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

If a class is declared without any access modifiers, where may the class be accessed?
Answer: A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

What is the Map interface?


Answer: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

Does a class inherit the constructors of its superclass?


Answer: A class does not inherit constructors from any of its superclasses .

Name primitive Java types.


Answer: The primitive types are byte, char, short, int, long, float, double, and boolean.

Which class should you use to obtain design information

about an object?
Answer: The Class class is used to obtain information about an objects design.

How can a GUI component handle its own events?


Answer: A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

How are the elements of a GridBagLayout organized?


Answer: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

What advantage do Javas layout managers provide over traditional windowing systems?
Answer: Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Javas layout managers arent tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

What are the problems faced by Java programmers who dont use layout managers?
Answer: Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

What is the difference between static and non-static variables?


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

What is the difference between the paint() and repaint() methods?


Answer: The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

What is the purpose of the File class?


Answer: The File class is used to create objects that provide access to the files and directories of a local file system.

What restrictions are placed on method overloading?


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

What restrictions are placed on method overriding?


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

What is casting?
Answer: There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

Name Container classes.


Answer: Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane .

What class allows you to read objects directly from a stream?


Answer: The ObjectInputStream class supports the reading of objects from input streams.

How are this() and super() used with constructors?


Answer: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

How is it possible for two String objects with identical values not to be equal under the == operator?
Answer: The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

What an I/O filter?


Answer: An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

What is the Set interface?

Answer: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

What is the List interface?


Answer: The List interface provides support for ordered collections of objects.

What is the purpose of the enableEvents() method?


Answer: The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

What is the difference between the File and RandomAccessFile classes?


Answer: The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

What interface must an object implement before it can be written to a stream as an object?
Answer: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

What is the ResourceBundle class?


Answer: The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the programs appearance to the particular locale in which it is being run.

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.

What is a Java package and how is it used?


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

What are the Object and Class classes used for?

Answer: The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

What is Serialization and deserialization?


Answer: Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

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.

Does the code in finally block get executed if there is an exception and a return statement in a catch block?
Answer: If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

How you restrict a user to cut and paste from the html page?
Answer: Using javaScript to lock keyboard keys. It is one of solutions.

Is Java a super set of JavaScript?


Answer: No. They are completely different. Some syntax may be similar.

What is a Container in a GUI?


Answer: A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.

How the object oriented approach helps us keep complexity of software development under control?
Answer: We can discuss such issue from the following aspects:

Objects allow procedures to be encapsulated with their data to reduce


potential interference.

Inheritance allows well-tested procedures to be reused and enables changes to


make once and have effect in all relevant places.

The well-defined separations of interface and implementation allows


constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.

What is polymorphism?
Answer: Polymorphism allows methods to be written that neednt be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to work even on objects of yet unconceived classes.

What is design by contract?


Answer: The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are.Similarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the post conditions. In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.

What are use cases?


Answer: A use case describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust.

Does garbage collection guarantee that a program will not run out of memory?
Answer: No, it doesnt. 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

What is the difference between preemptive scheduling and time slicing?


Answer: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Name Component subclasses that support painting.

Answer: The Canvas, Frame, Panel, and Applet classes support painting.

What is a native method?


Answer: A native method is a method that is implemented in a language other than Java.

How can you write a loop indefinitely?


Answer: for(;;)for loop; while(true)always true, etc.

Can an anonymous class be declared as implementing an interface and extending a class?


Answer: An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

What is the purpose of finalization?


Answer: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

Which class is the superclass for every class ?


Answer: Object.

What is the difference between the Boolean & operator and the && operator?
Answer: If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.

What is the GregorianCalendar class?


Answer: The GregorianCalendar provides support for traditional Western calendars.

What is the SimpleTimeZone class?


Answer: The SimpleTimeZone class provides support for a Gregorian calendar.

Which Container method is used to cause a container to be laid out and redisplayed?
Answer: validate()

What is the Properties class?


Answer: The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.

What is the purpose of the Runtime class?


Answer: The purpose of the Runtime class is to provide access to the Java runtime system.

What is the purpose of the System class?


Answer: The purpose of the System class is to provide access to system resources.

What is the purpose of the finally clause of a try-catch-finally statement?


Answer: The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

What is the Locale class?


Answer: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

What must a class do to implement an interface?


Answer: It must provide all of the methods in the interface and identify the interface in its implements clause.

What is an abstract method?


Answer: An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has no implementation (an interface of a method).

What is a static method?


Answer: A static method is a method that belongs to the class rather than any object of the class and doesnt apply to an object or even require that any objects of the class have been instantiated.

What is a protected method?


Answer: A protected method is a method that can be accessed by any method in

its package and inherited by any subclass of its class.

What is the difference between a static and a non-static inner class?


Answer: A non-static inner class may have object instances that are associated with instances of the classs outer class. A static inner class does not have any object instances.

What is an objects lock and which objects have locks?


Answer: An objects lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the objects lock. All objects and classes have locks. A classs lock is acquired on the classs Class object.

When can an object reference be cast to an interface reference?


Answer: An object reference be cast to an interface reference when the object implements the referenced interface.

What is the difference between a Window and a Frame?


Answer: The Frame class extends Window to define a main application window that can have a menu bar.

What do heavy weight components mean?


Answer: Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavy weight.

Which package has light weight components?


Answer: javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.

What are peerless components?


Answer: The peerless components are called light weight components.

What is the difference between the Font and FontMetrics

classes?
Answer: The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

What happens when a thread cannot acquire a lock on an object?


Answer: If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an objects lock, it enters the waiting state until the lock becomes available.

What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
Answer: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

What classes of exceptions may be caught by a catch clause?


Answer: A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

What is the difference between throw and throws keywords?


Answer: The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that designates that exceptions may come out of the method, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

If a class is declared without any access modifiers, where may the class be accessed?
Answer: A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

What is the Map interface?


Answer: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

Does a class inherit the constructors of its superclass?

Answer: A class does not inherit constructors from any of its superclasses .

Name primitive Java types.


Answer: The primitive types are byte, char, short, int, long, float, double, and boolean.

Which class should you use to obtain design information about an object?
Answer: The Class class is used to obtain information about an objects design.

How can a GUI component handle its own events?


Answer: A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

How are the elements of a GridBagLayout organized?


Answer: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

What advantage do Javas layout managers provide over traditional windowing systems?
Answer: Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Javas layout managers arent tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

What are the problems faced by Java programmers who dont use layout managers?
Answer: Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

What is the difference between static and non-static variables?


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

What is the difference between the paint() and repaint() methods?

Answer: The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

What is the purpose of the File class?


Answer: The File class is used to create objects that provide access to the files and directories of a local file system.

What restrictions are placed on method overloading?


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

What restrictions are placed on method overriding?


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

What is casting?
Answer: There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

Name Container classes.


Answer: Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane .

What class allows you to read objects directly from a stream?


Answer: The ObjectInputStream class supports the reading of objects from input streams.

How are this() and super() used with constructors?


Answer: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

How is it possible for two String objects with identical values not to be equal under the == operator?
Answer: The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but

located indifferent areas of memory.

What an I/O filter?


Answer: An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

What is the Set interface?


Answer: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

What is the List interface?


Answer: The List interface provides support for ordered collections of objects.

What is the purpose of the enableEvents() method?


Answer: The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

What is the difference between the File and RandomAccessFile classes?


Answer: The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

What interface must an object implement before it can be written to a stream as an object?
Answer: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

What is the ResourceBundle class?


Answer: The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the programs appearance to t he particular locale in which it is being run.

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.

What is a Java package and how is it used?


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

What are the Object and Class classes used for?


Answer: The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

What is Serialization and deserialization?


Answer: Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

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.

Does the code in finally block get executed if there is an exception and a return statement in a catch block?
Answer: If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

How you restrict a user to cut and paste from the html page?
Answer: Using javaScript to lock keyboard keys. It is one of solutions.

Is Java a super set of JavaScript?


Answer: No. They are completely different. Some syntax may be similar.

What is a Container in a GUI?


Answer: A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.

How the object oriented approach helps us keep complexity of software development under control?

Answer: We can discuss such issue from the following aspects:

Objects allow procedures to be encapsulated with their data to reduce


potential interference.

Inheritance allows well-tested procedures to be reused and enables changes to


make once and have effect in all relevant places.

The well-defined separations of interface and implementation allows


constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.

What is polymorphism?
Answer: Polymorphism allows methods to be written that neednt be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to work even on objects of yet unconceived classes.

What is design by contract?


Answer: The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are.Similarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the post conditions. In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.

What are use cases?


Answer: A use case describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust

1) Why String is immutable in java? Three reasons: 1) String pool requires string to be immutable otherwise shared reference can be changed from anywhere. 2) security because string is shared on different area like file system, networking connection, database connection , having immutable string allows you to be secure and safe because no one

can change reference of string once it gets created. if string had been mutable anyone can surpass the security be logging in someone else name and then later modifying file belongs to other. source : http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html 2) Why multiple inheritances are not supported in Java? Short answer is because of diamond pattern, diamond pattern creates ambiguity and make problem for compiler. Anyway java supports multiple inheritances via interfaces.I think more convincing reason for not supporting multiple inheritance is complexity involved in constructor chaining, casting etc rather than diamond problem source : http://javarevisited.blogspot.com/2011/07/why-multiple-inheritances-are-not.html 3) How to detect deadlock and fix it? when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock check here for detailed answer 4) When a singleton is not singleton in Java? Many cases like Serialization, RMI, Clasloader loading multiple instance etc. Read : http://javarevisited.blogspot.sg/2012/07/why-enum-singleton-are-better-in-java.html Read : http://javarevisited.blogspot.sg/2011/03/10-interview-questions-on-singleton.html 5) Difference between noclassdeffounderror and classnotfoundexception? As per my experience java.lang.NoClassDefFoundError occurs when a particular class was present during Compile time but not available during run time by any reason, while java.lang.ClassNotFoundException comes when class loaded explicitly during runtime. 6) Why equals() method must be compatible with compareTo in java ? compareTo method in Java must be compatible with equals method in Java i.e. if two objects are equal via equals method compareTo method must return 0 for them, failing this may result in some subtle bug when you store those objects in collection class like arraylist in java. check here for detailed answer 7) Explain race condition in Java hashmap ? Race conditions in Java are always tricky to find and solve. Not many people know about it that hashmap could run into race condition if it would be modified by two threads simultaneous and one thread tries to re-siz or rehash the map because of capacity crossing threshold value. Since hashmap maintains a linked list of element in bucket and while copying from one hashmap to

other or old to new order of linked list got reversed, which could result in infinite loop if two threads are doing resizing at same time? Otherwise some set e.g. TreeSet and TreeMap which uses compareTo will not able to detect duplicates and allow duplicate inside set. Read : What is Race condition in Java for more information on how to handle race conditions in Java 8) Can we call static method with null object? I bet this is the most tricky Java interview question I ever encountered. Yes we can call because static method is bound at compile time and only type of variable is used for static binding not the value of object. Its not a good practice to call static method by instance, always call static method in Java by using class name like Math.max() 9) How does volatile variable works in Java? Another seriously senior developer question in Java and tricky part of this question is change in volatile variable in Java 5. Though volatile is just a keyword its probably most confusing one in core Java. Volatile guarantee not just limited to the variable but also all the variables two threads see known as happens before relationship. Another important aspect of making a variable volatile is that compiler will not reorder the variable when switching from client to server configuration or while performing optimization. Read What is volatile variable in Java and How it works for detailed information on volatile variable in Java 10) How to detect memory leak in Java. This is the most tricky Java interview question, there is no sure sort answer but you can use profile and memory dump to find memory leak in Java. JConsole can also help to provide graph of memory usage which can show pattern for memory leak.

How to use Volatile keyword in Java What is Volatile variable in Java and when to use Volatile variable in Java is famous multi-threading interview question in Java interviews. Though many programmer knows what is a volatile variable but they fail on second part i.e. where to use volatile variable in Java as its not common to have clear understanding and hands-on on volatile in Java. In this tutorial we will address this gap by providing simple example of volatile variable in Java and discussing some when to use Volatile variable in Java. Any way Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. From Java 5 along with major changes like Autoboxing, Enum, Generics and Variable arguments , Java introduces some change in Java Memory Model (JMM), Which guarantees visibility of changes made by one thread to another also as "happens-before" which solves the

problem of memory writes that happen in one thread can " leak through" and be seen by another thread. Java volatile keyword cannot be used with method or class and it can only be used with variable. Java volatile keyword also guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.

This Java tutorial on Volatile keyword is in continuation of my article How HashMap works in Java and difference between HashMap and Hashtable in Java , How Garbage collection works in Java and How Synchronization works in Java if you havent read already you may find some useful information based on my experience in Java .

Example of volatile keyword in Java: To Understand example of volatile keyword in java lets go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without volatile keyword in java. /** * Java program to demonstrate where to use Volatile keyword in Java. * In this example Singleton Instance is declared as volatile variable to ensure * every thread see updated value for _instance. * * @author Javin Paul */ public class Singleton{ private static volatile Singleton _instance; //volatile variable public static Singleton getInstance(){ if(_instance == null){ synchronized(Singleton.class){ if(_instance == null) _instance = new Singleton(); } } return _instance; } If you look at the code carefully you will be able to figure out: 1) We are only creating instance one time 2) We are creating instance lazily at the time of first request comes. If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.

Why because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads. So in Summary apart from synchronized keyword in java, volatile keyword is also used to communicate content of memory between threads.

Lets see another example of volatile keyword in Java:

most of the time while writing game we use a variable bExist to check whether user has pressed exit button or not, value of this variable is updated in event thread and checked in game thread , So if we don't use volatile keyword with this variable , Game Thread might miss update from event handler thread if its not synchronized in java already. volatile keyword in java guarantees that value of volatile variable will always be read from main memory and "happens-before" relationship in Java Memory model will ensure that content of memory will be communicated to different threads. private boolean bExit; while(!bExit) { checkUserPosition(); updateUserPosition(); } In this code example One Thread (Game Thread) can cache the value of "bExit" instead of getting it from main memory every time and if in between any other thread (Event handler Thread) changes the value; it would not be visible to this thread. Making boolean variable " bExit" as volatile in java ensures this will not happen.

When to use Volatile variable in Java


One of the most important thing in learning of volatile keyword is understanding when to use volatile variable in Java. Many programmer knows what is volatile variable and How does it work but they never really used volatile for any practical purpose. Here are couple of example to demonstrate when to use Volatile keyword in Java: 1) You can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. You can avoid this issue by making long and double variable volatile in Java. 2) Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation completed, without volatile keyword different reader thread may see different values. 3) volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory. like following example without volatile variable may result in infinite loop private boolean isActive = thread; public void printMessage(){ while(isActive){ System.out.println("Thread is Active"); } }

without volatile modifier its not guaranteed that one Thread see the updated value of isActive from other thread. compiler is also free to cache value of isActive instead of reading it from main memory in every iteration. By making isActive a volatile variable you avoid these issue. 4) Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment. Important points on Volatile keyword in Java 1. volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal. 2. volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache. 3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables). 4. Using Volatile keyword in Java on variables reduces the risk of memory consistency errors, because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable. 5. From Java 5 changes to a volatile variable are always visible to other threads. Whats more it also means that when a thread reads a volatile variable in java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change. 6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without use of volatile keyword in Java. 7. An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock. 8. Java volatile variable that is an object reference may be null. 9. Java volatile keyword doesn't means atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java. 10. If a variable is not shared between multiple threads no need to use volatile keyword with that variable.

Difference between synchronized and volatile keyword in Java Difference between volatile and synchronized is another popular core Java question asked in multi-threading and concurrency interviews. Remember volatile is not a replacement of synchronized keyword but can be used as an alternative in certain cases. Here are few differences between volatile and synchronized keyword in Java. 1. Volatile keyword in java is a field modifier, while synchronized modifies code blocks and methods. 2. Synchronized obtains and releases lock on monitors java volatile keyword doesn't require that. 3. Threads in Java can be blocked for waiting any monitor in case of synchronized, that is not the case with volatile keyword in Java. 4. Synchronized method affects performance more than volatile keyword in Java.

5. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory and "main" memory while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile. 6. You can not synchronize on null object but your volatile variable in java could be null. 7. From Java 5 Writing into a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire In Summary volatile keyword in Java is not a replacement of synchronized block or method but in some situation is very handy and can save performance overhead which comes with use of synchronization in Java