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++ doesn’t 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 isn’t 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 1970’s 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 1980’s he got Sun’s engineers started on a complete revision of the UNIX operating system that involved merging SunOS4.x with AT&T’s SYSVR4. In 1989 Joy sold his Sun stock, invested heavily in Microsoft and moved out of mainstream Sun to Aspen, Colorado. By the early 90’s 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 wasn’t 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 Gosling’s 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 Joy’s 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, Sun’s 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

Button is a heavy weight component. checking the contents of the document against constraints established in a DTD or Schema. whereas Swing components are lightweight. 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. Heavy weight components depend on the local windowing toolkit. when it is running on the Java platform for Unix platform. instantiate your subclass and then call that method. and MacOS. You can say that the syntax is wrong. What is the output of x Answer: When this kind of question has been asked. a bridge between XML documents and applications that process that XML. The Java Virtual Machine (Java VM) 2. What is a platform? Answer: A platform is the hardware or software environment in which a program runs. If you have an abstract class and you want to use a method which has been implemented. . For example. Answer: No! You cannot make an instance of an abstract class. it maps to a real Motif button. find the problems you think is necessary to ask before you give an answer. An abstract class has to be sub-classed. If the statement is rewritten as: x<="" statement="" true="" returned. you may need to subclass that abstract class.awt. Most platforms can be described as a combination of the operating system and hardware. The Java platform has two components: 1. java. Ask if variables a and b have been declared or initialized. Parsers? DOM vs SAX parser Answer: parsers are fundamental xml components. If the answer is yes. What is the difference between Swing and AWT components? Answer: AWT components are heavy-weight. like Windows 2000/XP.getInstance() which returns an instance of the Calender class. The parser is responsible for handling xml syntax. Solaris. Linux. What is the main difference between Java platform and other platforms? Answer: The Java platform differs from most other platforms in that it’s a software-only platform that runs on top of other hardware-based platforms.

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. The Serializable interface acts as a marker. well-tuned interpreters. What is the difference between Serializalble and . What is the package? Answer: The package is a Java namespace or part of Java libraries. the compiled code runs on a specific hardware platform.io. and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability. Is Java code slower than native code? Answer: Not really. that class is serializable. How many methods in the Serializable interface? Answer: There is no method in the Serializable interface. these libraries are known as packages.Serializable interface.Externalizable interface. or the java.What is the Java API? Answer: The Java API is a large collection of ready-made software components that provide many useful capabilities. the Java platform can be a bit slower than native code. These two methods are readExternal() and writeExternal(). 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. You have to implement these two methods in order to make your class externalizable. smart compilers. What is native code? Answer: The native code is code that after you compile it.io. The Java API is grouped into libraries of related classes and interfaces. As a platform-independent environment. As long as one class in a class’s inheritance hierarchy implements Serializable or Externalizable. However. How to make a class or a bean serializable? Answer: By implementing either the java. such as graphical user interface (GUI) widgets.

your class is serialized automatically by default. Frame and Dialog classes use a border layout as their default layout. This oft en causes dirty data and leads to significant errors. 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. How are Observer and Observable used? . you have a complete control over your class’s serialization process. What are synchronized methods and synchronized statements? Answer: Synchronized methods are methods that are used to control access to an object. it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. Synchronized statements are similar to synchronized methods. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. What is a transient variable? Answer: A transient variable is a variable that may not be serialized. 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. When you use Externalizable interface. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. The Observer interface is implemented by objects that observe Observable objects. If you don’t want some field to be serialized. you can mark that field transient or static. How are Observer and Observable used? Answer: Objects that subclass the Observable class maintain a list of observers. But you can override writeObject() and readObject() two methods to control more complex object serailization process. What is synchronization and why is it important? Answer: With respect to multithreading. Which containers use a border layout as their default layout? Answer: The Window. Without synchronization.Externalizable interface? Answer: When you use Serializable interface. synchronization is the capability to control the access of multiple threads to shared resources.

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. 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. The Observer interface is implemented by objects that observe Observable objects. Can a lock be acquired on a class? Answer: Yes.2. What method is used to specify a container’s layout? Answer: The setLayout() method is used to specify a cont ainer’s layout. suspend() and resume() methods in JDK 1. by blocking on I/O. This lock is acquired on the class’s Class object. by unsuccessfully attempting to acquire an object’s lock. 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. suspend() and resume() methods have been deprecated in JDK 1.2? Answer: The stop(). or by invoking an object’s wait() method.Answer: Objects that subclass the Observable class maintain a list of observers. What is multithreading? Answer: Multithreading means various threads that run in a system. What’s new with the stop(). It can also enter the waiting state by invoking its (deprecated) suspend() method. 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. How does multithreading take place on a computer with a single CPU? . a lock can be acquired on a class.

What invokes a thread’s run() method? Answer: After a thread is started. 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. making your class “implements” Runnable interface. the JVM invokes the thread’s run() method when the thread is i nitially executed.Answer: The operating system’s task scheduler allocates execution time to multiple tasks. making your class “extends” Thread class. What is the Collections API? Answer: The Collections API is a set of classes and interfaces that support operations on collections of objects. and notifyAll() methods? Answer: The wait(). What is the purpose of the wait(). via its start() method of the Thread class. You can lock an object by putting it in a “synchronized” block. Put jobs in a run() method and call start() method to start the thread. How to create multithread in a program? Answer: You have two ways to do so.notify(). it enters the dead state. First. waiting. 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. and dead. Can Java object be locked down for exclusive use by a given thread? Answer: Yes. Second. notify(). running. . By quickly switching between executing tasks. it creates the impression that tasks execute sequentially.

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. it returns to the ready state. UTF16. and 18 bit patterns. 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. When a task invokes its sleep() method. What is the difference between yielding and sleeping? Answer: When a task invokes its yield() method. or abstract. final. UTF-8 represents characters using 8. static. UTF-16 uses 16-bit and larger bit patterns. and UTF-8 characters? Answer: Unicode requires 16 bits and ASCII require 7 bits. 16. How many bits are used to represent Unicode. Is sizeof a keyword? Answer: The sizeof operator is not a keyword. What is an Iterator interface? Answer: The Iterator interface is used to step through the elements of a Collection. it returns to the waiting state. protected. it is usually represented as 8 bits. What is the Vector class? Answer: The Vector class provides the capability to implement a growable array 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. ASCII. Although the ASCII character set uses only 7 bits. private.What is the List interface? Answer: The List interface provides support for ordered collections of objects. If a method is declared as protected. .

and Applet classes support painting. Name Component subclasses that support painting.Boolean double java.Character java. What is a native method? Answer: A native method is a method that is implemented in a language other than Java.Long java.lang.lang.lang. 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.lang. Answer: The Canvas. 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. it doesn’t. a task executes for a predefined slice of time and then reenters the pool of ready tasks.What are wrapped classes? Answer: Wrapped classes are classes that allow primitive types to be accessed as objects. the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.lang.lang. It is possible for programs to use up memory resources faster than they are garbage collected.Float java.Void boolean java.lang.Integer java. Frame. An instance of a wrapper class contains.Double Does garbage collection guarantee that a program will not run out of memory? Answer: No. The scheduler then determines which task should execute next.Short java.lang. based on priority and other factors. How can you write a loop indefinitely? . or wraps.lang. Under time slicing. Wrapper class is wrapper around a primitive data type. Panel.Byte java.

both operands are evaluated. If the first operand returns a value of true then the second operand is evaluated. Then the & operator is applied to the operand. etc..)–for loop. When an expression involving the && operator is evaluated. What is the GregorianCalendar class? Answer: The GregorianCalendar provides support for traditional Western calendars.Answer: for(. What is the SimpleTimeZone class? Answer: The SimpleTimeZone class provides support for a Gregorian calendar. the first operand is evaluated. The && operator is then applied to the first and second operands. the evaluation of the second operand is skipped. 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 . Operator & has no chance to skip both sides evaluation and && operator does. give details as above. while(true)–always true. 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. but may not be declared to do both. If the first operand evaluates to false. 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. If asked why. 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.

. 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. It also provides the capability to specify a set of default values to be used. What is an abstract method? Answer: An abstract method is a method whose implementation is deferred to a subclass. a method that has no implementation (an interface of a method). What is the Locale class? Answer: The Locale class is used to tailor program output to the conventions of a particular geographic.written to a stream. 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 a static method? Answer: A static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated. 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 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. or cultural region. political. Or. What is the purpose of the System class? Answer: The purpose of the System class is to provide access to system resources. A static inner class does not have any object instances. 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 class’s outer class.

Button is a heavy weight component.Swing package. A class’s lock is acquired on the class’s Class object. 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. 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. such as ascent and descent. The Java platform communicates with the Motif Buttons using the Java Native Interface. there is an additional overhead tied to the local windowing system. What are peerless components? Answer: The peerless components are called light weight components. For example. except JApplet.Button. which is why these components are called heavy weight. For each and every component added to the application. it maps to a real Motif button. two peers and hence two Motif Buttons are also created. Which package has light weight components? Answer: javax. What happens when a thread cannot acquire a lock on an object? .What is an object’s lock and which object’s have locks? Answer: An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. All objects and classes have locks. JFrame and JWindow are lightweight components.awt. depend on the local windowing toolkit. when it is running on the Java platform for Unix platform. java. All components in Swing. What is the difference between the Font and FontMetrics classes? Answer: The FontMetrics class is used to define implementation-specific properties. of a Font object.awt. If you create two Buttons. the Motif button is called the peer to the java. In this relationship. What do heavy weight components mean? Answer: Heavy weight components like Abstract Window Toolkit (AWT). JDialog. A thread may execute a synchronized method of an object only after it has acquired the object’s lock.

Which class should you use to obtain design information . It takes the Exception object to be thrown as argument. long.1 Dictionary class and is used associate keys with values. and boolean. What is the Map interface? Answer: The Map interface replaces the JDK 1. it enters the waiting state until the lock becomes available. float. What is the difference between throw and throws keywords? Answer: The throw keyword denotes a statement that causes an exception to be initiated.Answer: If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock. Does a class inherit the constructors of its superclass? Answer: A class does not inherit constructors from any of its superclasses . char. 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. short. and the InputStream/OutputStream class hierarchy is byte-oriented. This includes the Error and Exception types. If a class is declared without any access modifiers. int. Answer: The primitive types are byte. 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. 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. The throws keyword is a modifier of a method that designates that exceptions may come out of the method. Name primitive Java types. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy. double. 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.

. 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. the rows and columns may have different sizes. However. What advantage do Java’s layout managers provide over traditional windowing systems? Answer: Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Non-static variables take on unique values with each object instance. In addition. What are the problems faced by Java programmers who don’t use layout managers? Answer: Without layout managers. Since Java’s layout managers aren’t tied to absolute sizing and positioning.about an object? Answer: The Class class is used to obtain information about an object’s 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. What is the difference between the paint() and repaint() methods? Answer: The paint() method supports painting via a Graphics object. they are able to accommodate platform-specific differences among windowing systems. How are the elements of a GridBagLayout organized? Answer: The elements of a GridBagLayout are organized according to a grid. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. 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. 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. the elements are of different sizes and may occupy more than one row or column of the grid.

Name Container classes. argument list. but located indifferent areas of memory. Frame. interface. Casting between numeric types is used to convert larger values. Applet. or ScrollPane . What is casting? Answer: There are two types of casting. What restrictions are placed on method overriding? Answer: Overridden methods must have the same name. What is the Set interface? . The overriding method may not limit the access of the method it overrides. How are this() and super() used with constructors? Answer: this() is used to invoke a constructor of the same class. Panel. usually altering the data in some way as it is passed from one stream to another. It is possible for two String objects to have the same value. Dialog. Casting between object references is used to refer to an object by a compatible class. or array type reference. casting between primitive numeric types and casting between object references. What an I/O filter? Answer: An I/O filter is an object that reads from one stream and writes to another. The overriding method may not throw any exceptions that may not be thrown by the overridden method. to smaller values. FileDialog. super() is used to invoke a superclass constructor. and return type. What class allows you to read objects directly from a stream? Answer: The ObjectInputStream class supports the reading of objects from input streams. such as byte values. such as double values.What restrictions are placed on method overloading? Answer: Two methods may not have the same name and argument list but different return types. 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. Answer: Window.

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. What is the List interface? Answer: The List interface provides support for ordered collections of objects. A ScrollPane handles its own events and performs its own scrolling. Sets do not allow duplicate elements. What is the difference between the File and RandomAccessFile classes? Answer: The File class encapsulates the files and directories of the local file system.Answer: The Set interface provides methods for accessing the elements of a finite mathematical set. 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 program’s appearance to the particular locale in which it is being run. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. 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 is the difference between a Scrollbar and a ScrollPane? Answer: A Scrollbar is a Component. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods. 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. but not a Container. What is a Java package and how is it used? Answer: A Java package is a naming context for classes and interfaces. What are the Object and Class classes used for? . A ScrollPane is a Container.

What is Serialization and deserialization? Answer: Serialization is the process of writing the state of an object to a byte stream.Answer: The Object class is the highest-level class in the Java class hierarchy. 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. 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. tunnelling means a way to transfer data. What is a Container in a GUI? Answer: A Container contains and arranges other components (including other containers) through the use of layout managers. The Class class is used to represent the classes and interfaces that are loaded by a Java program. For example. Some syntax may be similar. They are completely different. RMI tunnelling is a way to make RMI application get through firewall. How you restrict a user to cut and paste from the html page? Answer: Using javaScript to lock keyboard keys. 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. � Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places. which use specific layout policies to determine where components should go as a function of the size of the container. What is tunnelling? Answer: Tunnelling is a route to somewhere. Is Java a super set of JavaScript? Answer: No. In CS world. It is one of solutions. Deserialization is the process of restoring these objects. the finally block is still executed. .

The scheduler then determines which task should execute next. thus the called method has the responsibility of satisfying the post conditions. Name Component subclasses that support painting. the preconditions specify what the method required to be true when the method is called.� 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. based on priority and other factors. Hence making sure that preconditions are. What is polymorphism? Answer: Polymorphism allows methods to be written that needn’t be concerned about the specifics of the objects they will be applied to.Similarly. the exception handling facilities support the use of design by contract. 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. anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust. it doesn’t. It is possible for programs to use up memory resources faster than they are garbage collected. especially in the case of checked exceptions. a task executes for a predefined slice of time and then reenters the pool of ready tasks. It is part of the analysis of a program. ideally. postconditions specify what must be true when the method is finished. 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. 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. That is. For example. the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. The assert keyword can be used to make such contracts. The collection of use cases should. In Java. Under time slicing. 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. Does garbage collection guarantee that a program will not run out of memory? Answer: No. .

Frame. the first operand is evaluated. Panel. If the first operand evaluates to false. If the first operand returns a value of true then the second operand is evaluated. Which class is the superclass for every class ? Answer: Object. but may not be declared to do both. . 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. How can you write a loop indefinitely? Answer: for(. What is the SimpleTimeZone class? Answer: The SimpleTimeZone class provides support for a Gregorian calendar. If asked why. and Applet classes support painting. 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. the evaluation of the second operand is skipped. both operands are evaluated. What is a native method? Answer: A native method is a method that is implemented in a language other than Java..Answer: The Canvas.)–for loop. When an expression involving the && operator is evaluated. What is the GregorianCalendar class? Answer: The GregorianCalendar provides support for traditional Western calendars. Operator & has no chance to skip both sides evaluation and && operator does. give details as above. The && operator is then applied to the first and second operands. while(true)–always true. What is the difference between the Boolean & operator and the && operator? Answer: If an expression involving the Boolean & operator is evaluated. etc. Then the & operator is applied to the operand.

What is the purpose of the Runtime class? Answer: The purpose of the Runtime class is to provide access to the Java runtime system. It also provides the capability to specify a set of default values to be used. 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. Or. What is the purpose of the System class? Answer: The purpose of the System class is to provide access to system resources. 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. or cultural region.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. What is the Locale class? Answer: The Locale class is used to tailor program output to the conventions of a particular geographic. What is an abstract method? Answer: An abstract method is a method whose implementation is deferred to a subclass. What is a protected method? Answer: A protected method is a method that can be accessed by any method in . 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 doesn’t apply to an object or even require that any objects of the class have been instantiated. political.

depend on the local windowing toolkit. The Java platform communicates with the Motif Buttons using the Java Native Interface. 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.awt.its package and inherited by any subclass of its class.Button is a heavy weight component. What do heavy weight components mean? Answer: Heavy weight components like Abstract Window Toolkit (AWT). All objects and classes have locks. except JApplet. For each and every component added to the application. when it is running on the Java platform for Unix platform. JDialog. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. What are peerless components? Answer: The peerless components are called light weight components. What is an object’s lock and which object’s have locks? Answer: An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. it maps to a real Motif button. java. A class’s lock is acquired on the class’s Class object. In this relationship. All components in Swing. For example. 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. Which package has light weight components? Answer: javax. two peers and hence two Motif Buttons are also created. If you create two Buttons. there is an additional overhead tied to the local windowing system.Swing package. which is why these components are called heavy weight. 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 class’s outer class. JFrame and JWindow are lightweight components.Button. A static inner class does not have any object instances. What is the difference between the Font and FontMetrics . the Motif button is called the peer to the java.awt.

What is the Map interface? Answer: The Map interface replaces the JDK 1.classes? Answer: The FontMetrics class is used to define implementation-specific properties. This includes the Error and Exception types. 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. The throws keyword is a modifier of a method that designates that exceptions may come out of the method. 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 object’s lock. it enters the waiting state until the lock becomes available. and the InputStream/OutputStream class hierarchy is byte-oriented. Does a class inherit the constructors of its superclass? . The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy.1 Dictionary class and is used associate keys with values. where may the class be accessed? Answer: A class that is declared without any access modifiers is said to have package or friendly access. 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. What is the difference between throw and throws keywords? Answer: The throw keyword denotes a statement that causes an exception to be initiated. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. such as ascent and descent. It takes the Exception object to be thrown as argument. of a Font object. 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. If a class is declared without any access modifiers.

How are the elements of a GridBagLayout organized? Answer: The elements of a GridBagLayout are organized according to a grid. 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. and boolean. Answer: The primitive types are byte. short. the rows and columns may have different sizes.Answer: A class does not inherit constructors from any of its superclasses . What is the difference between the paint() and repaint() methods? . What advantage do Java’s layout managers provide over traditional windowing systems? Answer: Java uses layout managers to lay out components in a consistent manner across all windowing platforms. float. Since Java’s layout managers aren’t tied to absolute sizing and positioning. Which class should you use to obtain design information about an object? Answer: The Class class is used to obtain information about an object’s design. they are able to accommodate platform-specific differences among windowing systems. Non-static variables take on unique values with each object instance. In addition. 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. However. long. Name primitive Java types. char. What are the problems faced by Java programmers who don’t use layout managers? Answer: Without layout managers. int. the elements are of different sizes and may occupy more than one row or column of the grid. 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. double.

Casting between object references is used to refer to an object by a compatible class. What restrictions are placed on method overriding? Answer: Overridden methods must have the same name. Dialog. but . casting between primitive numeric types and casting between object references. The overriding method may not throw any exceptions that may not be thrown by the overridden method. Name Container classes. and return type. such as byte values. How are this() and super() used with constructors? Answer: this() is used to invoke a constructor of the same class. Panel. 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. Casting between numeric types is used to convert larger values. FileDialog. The overriding method may not limit the access of the method it overrides. to smaller values. argument list. What is casting? Answer: There are two types of casting. Frame. What restrictions are placed on method overloading? Answer: Two methods may not have the same name and argument list but different return types. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. 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. interface.Answer: The paint() method supports painting via a Graphics object. What class allows you to read objects directly from a stream? Answer: The ObjectInputStream class supports the reading of objects from input streams. It is possible for two String objects to have the same value. such as double values. Answer: Window. super() is used to invoke a superclass constructor. Applet. or ScrollPane . or array type reference.

usually altering the data in some way as it is passed from one stream to another. Normally. an event is enabled when a listener is added to an object for a particular event. 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 program’s appearance to t he particular locale in which it is being run. 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. A ScrollPane handles its own events and performs its own scrolling. What is the List interface? Answer: The List interface provides support for ordered collections of objects. What is the difference between a Scrollbar and a ScrollPane? Answer: A Scrollbar is a Component. but not a Container. Sets do not allow duplicate elements. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.located indifferent areas of memory. What is the Set interface? Answer: The Set interface provides methods for accessing the elements of a finite mathematical set. What is the purpose of the enableEvents() method? Answer: The enableEvents() method is used to enable an event for a particular object. What is the difference between the File and RandomAccessFile classes? Answer: The File class encapsulates the files and directories of the local file system. A ScrollPane is a Container. What an I/O filter? Answer: An I/O filter is an object that reads from one stream and writes to another. . The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

What is a Java package and how is it used? Answer: A Java package is a naming context for classes and interfaces. They are completely different. How the object oriented approach helps us keep complexity of software development under control? . Is Java a super set of JavaScript? Answer: No. A package is used to create a separate name space for groups of classes and interfaces. which use specific layout policies to determine where components should go as a function of the size of the container. Deserialization is the process of restoring these objects. The Class class is used to represent the classes and interfaces that are loaded by a Java program. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. How you restrict a user to cut and paste from the html page? Answer: Using javaScript to lock keyboard keys. What is Serialization and deserialization? Answer: Serialization is the process of writing the state of an object to a byte stream. For example. the finally block is still executed. What is tunnelling? Answer: Tunnelling is a route to somewhere. It is one of solutions. 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. tunnelling means a way to transfer data. The finally block will not be executed when the System. Some syntax may be similar. RMI tunnelling is a way to make RMI application get through firewall. What are the Object and Class classes used for? Answer: The Object class is the highest-level class in the Java class hierarchy. In CS world. What is a Container in a GUI? Answer: A Container contains and arranges other components (including other containers) through the use of layout managers.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.

What is polymorphism? Answer: Polymorphism allows methods to be written that needn’t be concerned about the specifics of the objects they will be applied to. The collection of use cases should. For example. postconditions specify what must be true when the method is finished. That is. thus the called method has the responsibility of satisfying the post conditions. 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. especially in the case of checked exceptions. the preconditions specify what the method required to be true when the method is called. the exception handling facilities support the use of design by contract. The assert keyword can be used to make such contracts. It is part of the analysis of a program. ideally.Answer: We can discuss such issue from the following aspects: � Objects allow procedures to be encapsulated with their data to reduce potential interference. 2) security because string is shared on different area like file system. networking connection. Hence making sure that preconditions are. In Java. 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. having immutable string allows you to be secure and safe because no one . database connection . � 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. 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. � Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places. 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.Similarly.

if two objects are equal via equals method compareTo method must return “0″ for them.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 .com/2011/07/why-multiple-inheritances-are-not. casting etc rather than diamond problem source : http://javarevisited. Anyway java supports multiple inheritances via interfaces. while java.blogspot.sg/2011/03/10-interview-questions-on-singleton. 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. source : http://javarevisited.lang.blogspot.blogspot.html 2) Why multiple inheritances are not supported in Java? Short answer is because of diamond pattern.e. Read : http://javarevisited.NoClassDefFoundError occurs when a particular class was present during Compile time but not available during run time by any reason.lang.I think more convincing reason for not supporting multiple inheritance is complexity involved in constructor chaining. situation is called deadlock check here for detailed answer 4) When a singleton is not singleton in Java? Many cases like Serialization. failing this may result in some subtle bug when you store those objects in collection class like arraylist in java.sg/2012/07/why-enum-singleton-are-better-in-java.blogspot.html 5) Difference between noclassdeffounderror and classnotfoundexception? As per my experience java. Clasloader loading multiple instance etc. Since hashmap maintains a linked list of element in bucket and while copying from one hashmap to . if string had been mutable anyone can surpass the security be logging in someone else name and then later modifying file belongs to other.html Read : http://javarevisited. diamond pattern creates ambiguity and make problem for compiler.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. check here for detailed answer 7) Explain race condition in Java hashmap ? Race conditions in Java are always tricky to find and solve. RMI.can change reference of string once it gets created.com/2010/10/why-string-is-immutable-in-java.

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 and write in int or boolean variable you can declare them as volatile variable. Though many programmer knows what is a volatile variable but they fail on second part i. From Java 5 along with major changes like Autoboxing. So if you want to share any variable in which read and write operation is atomic by implementation e. This is the most tricky Java interview question.e. Java introduces some change in Java Memory Model (JMM). 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. TreeSet and TreeMap which uses compareTo will not able to detect duplicates and allow duplicate inside set. where to use volatile variable in Java as its not common to have clear understanding and hands-on on volatile in Java. 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.g. always call static method in Java by using class name like Math. Enum.g. there is no sure sort answer but you can use profile and memory dump to find memory leak in Java. It’s not a good practice to call static method by instance. 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. 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. Volatile guarantee not just limited to the variable but also all the variables two threads see known as “happens before” relationship.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. Generics and Variable arguments . 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. JConsole can also help to provide graph of memory usage which can show pattern for memory leak. Though volatile is just a keyword its probably most confusing one in core 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.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. Which guarantees visibility of changes made by one thread to another also as "happens-before" which solves the .

//volatile variable public static Singleton getInstance(){ if(_instance == null){ synchronized(Singleton. Java volatile keyword also guarantees visibility and ordering . /** * Java program to demonstrate where to use Volatile keyword in Java. } 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. volatile keyword is also used to communicate content of memory between threads.class){ if(_instance == null) _instance = new Singleton(). after Java 5 write to any volatile variable happens before any read into volatile variable. Example of volatile keyword in Java: To Understand example of volatile keyword in java let’s go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without volatile keyword in java. so if Thread A is creating Singleton instance and just after creation lost the CPU. Java volatile keyword cannot be used with method or class and it can only be used with variable. } } return _instance. Why because reader threads are not doing any locking and until writer thread comes out of synchronized block. . 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 . With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads. How Garbage collection works in Java and How Synchronization works in Java if you haven’t read already you may find some useful information based on my experience in Java . So in Summary apart from synchronized keyword in java. If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread.problem of memory writes that happen in one thread can " leak through" and be seen by another thread. all other thread will not be able to see value of _instance as not null and they will believe its still null. memory will not be synchronized and value of _instance will not be updated in main memory. * In this example Singleton Instance is declared as volatile variable to ensure * every thread see updated value for _instance. that instance has been created until it comes out of the Singleton block. * * @author Javin Paul */ public class Singleton{ private static volatile Singleton _instance. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.

free to cache value of volatile variable instead of always reading from main memory. which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. due to this its possible for a Thread to see 32 bit from two different write.out. public void printMessage(){ while(isActive){ System. You can avoid this issue by making long and double variable volatile in Java. Without volatile variable compiler can re-order code. } } . Many platform perform write in long and double variable 2 step. 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. } 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. like Visibility.println("Thread is Active"). Game Thread might miss update from event handler thread if its not synchronized in java already. it would not be visible to this thread. updateUserPosition().Let’s 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. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation completed. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. 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. 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. while(!bExit) { checkUserPosition(). 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. So if we don't use volatile keyword with this variable . private boolean bExit. 2) Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases. value of this variable is updated in event thread and checked in game thread . writing 32 bit in each step. like following example without volatile variable may result in infinite loop private boolean isActive = thread. Many programmer knows what is volatile variable and How does it work but they never really used volatile for any practical purpose. Making boolean variable " bExit" as volatile in java ensures this will not happen.

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

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 . 7. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile. 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. From Java 5 Writing into a volatile field has the same memory effect as a monitor release.5. You can not synchronize on null object but your volatile variable in java could be null. 6.

Sign up to vote on this title
UsefulNot useful