Vous êtes sur la page 1sur 28

Question: What is transient variable? Answer: Transient variable can't be serialize.

For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null. Question: Name the containers which uses Border Layout as their default layout? Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes. Question: What do you understand by Synchronization? Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption. E.g. Synchronizing a function: public synchronized void Method1 () { // Appropriate method-related code. } E.g. Synchronizing a block of code inside a function: public myFunction (){ synchronized (this) { // Synchronized code here. } } Question: What is Collection API? Answer: The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map. Question: Is Iterator a Class or Interface? What is its use? Answer: Iterator is an interface which is used to step through the elements of a Collection.

Question: What is similarities/difference between an Abstract class and Interface? Answer: Differences are as follows:

Interfaces provide a form of multiple inheritance. A class can extend only one other class.

Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc. A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

Similarities:

Neither Abstract classes or Interface can be instantiated.

Question: How to define an Abstract class? Answer: A class containing abstract method is called Abstract class. An Abstract class can't be instantiated. Example of Abstract class: abstract class testAbstractClass { protected String myString; public String getMyString() { return myString; } public abstract string anyAbstractFunction(); }

Question: How to define an Interface? Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface. Emaple of Interface: public interface sampleInterface { public void functionOne(); public long CONSTANT_ONE = 1000; }

Question: Explain the user defined Exceptions? Answer: User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class.

This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions. Example: class myCustomException extends Exception { // The class simply has to exist to be an exception }

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

Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position JDBC 2.0 Core API provides the Batch Updates functionality to the java applications. Java applications can now use the ResultSet.updateXXX methods. New data types - interfaces mapping the SQL3 data types Custom mapping of user-defined types (UTDs) Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values. Question: Explain garbage collection? Answer: Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() andRuntime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

Question: How you can force the garbage collection? Answer: Garbage collection automatic process and can't be forced. Question: What is OOPS?

Answer: OOP is the common abbreviation for Object-Oriented Programming. Question: Describe the principles of OOPS. Answer: There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation. Question: Explain the Encapsulation principle. Answer: Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. Question: Explain the Inheritance principle. Answer: Inheritance is the process by which one object acquires the properties of another object. Question: Explain the Polymorphism principle. Answer: The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods". Question: Explain the different forms of Polymorphism. Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

Method overloading Method overriding through inheritance Method overriding through the Java interface

Question: What are Access Specifiers available in Java? Answer: Access specifiers are keywords that determines the type of access to the member of a class. These are:

Public Protected Private Defaults

Question: what is the class variables ? Answer: When we create a number of objects of the same class, then each object will share a common copy of variables. That means that there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static

keyword in a class, but mind it that it should be declared outside outside a class. These variables are stored in static memory. Class variables are mostly used for constants, variable that never change its initial value. Static variables are always called by the class name. This variable is created when the program starts i.e. it is created before the instance is created of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined as int then it's initial value is by default zero, when declared boolean its default value is false and null for object references. Class variables are associated with the class, rather than with any object. Question: What is the difference between the instanceof and getclass, these two are same or not ? Answer: instanceof is a operator, not a function while getClass is a method of java.lang.Object class. Consider a condition where we use if(o.getClass().getName().equals("java.lang.Math")){ } This method only checks if the classname we have passed is equal to java.lang.Math. The class java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class loader is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defines. getClass() method returns the runtime class of an object. It fetches the java instance of the given fully qualified type name. The code we have written is not necessary, because we should not compare getClass.getName(). The reason behind it is that if the two different class loaders load the same class but for the JVM, it will consider both classes as different classes so, we can't compare their names. It can only gives the implementing class but can't compare a interface, but instanceof operator can. The instanceof operator compares an object to a specified type. We can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClass() method. Remember instanceof opeator and getClass are not same. Try this example, it will help you to better understand the difference between the two. Interface one{ } Class Two implements one { } Class Three implements one { } public class Test { public static void main(String args[]) { one test1 = new Two();

one test2 = new Three(); System.out.println(test1 instanceof one); //true System.out.println(test2 instanceof one); //true System.out.println(Test.getClass().equals(test2.getClass())); //false } } What is the difference between procedural and object-oriented programs? a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code. What is the difference between Assignment and Initialization? Assignment can be done as many times as desired whereas initialization can be done only once. What is the difference between constructor and method? Constructor will be automatically invoked when an object is created whereas method has to be called explicitly. What is the difference between an argument and a parameter?While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments. What are different types of access modifiers? public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private cant be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package. What is final, finalize() and finally? final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method cant be overridden. A final variable cant change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is

thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency. What is UNICODE? Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other. What are Transient and Volatile Modifiers?Transient: The transient modifier applies to variables only and it is not stored as part of its objects Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program. What is difference between overloading and overriding? In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.

What is the difference between String and String Buffer? String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings. What is the difference between exception and error?- The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.

What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?- Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in

Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object. What is daemon thread and which method is used to create the daemon thread? Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread. Are there any global variables in Java, which can be accessed by other part of your program? No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here. What is an applet? Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.

What is the difference between applications and applets? a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface. What is a stream and what are the types of Streams and classes of the Streams A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer. What is the difference between Reader/Writer and InputStream/Output Stream? The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byteoriented. What is an I/O filter? 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 are Vector, Hashtable, LinkedList and Enumeration? Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the objects keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series. What are the advantages of the model over the event-inheritance model? The event-delegation model has two advantages over the event-inheritance model. They are: a)It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a components design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance. What is source and listener? source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. What is adapter class? An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved(). The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged() . What is meant by controls and what are different types of controls in AWT? Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.What is the difference between choice and list?

A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items. What is the difference between scrollbar and scrollpane? A Scrollbar is a Component, but not a Container whereas Scrollpane is a Conatiner and handles its own events and perform its own scrolling. What is a layout manager and what are different types of layout managers available in java AWT? A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout. How are the elements of different layouts organized? FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion. BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards. GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different size and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. Which containers use a Border layout as their default layout? Window, Frame and Dialog classes use a BorderLayout as their layout. Which containers use a Flow layout as their default layout? Panel and Applet classes use the FlowLayout as their default layout. What is Externalizable? Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in) How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? 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 preemptive scheduling and time slicing? 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. What are order of precedence and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left Why the methods of the Math class are static? Its to reduce un-necessary object creation.Generally utility class methods should be kept static.See if the methods of Math class are non static then you will have to create object of Math class every time and that object is of no use after method is called once.To reduce un necessary object creation and keep the garbage collector heap healthymethod should be made static if they are utility methods.Math class methods do not depend on instance variables ...hence, why to create a object of math class....math.min(2,1) -> 1Method execution in math class depend on method args, and not instance variables...Even if u tries to create an object of Math class ...U will get an exception... Since math class has a private constructo What is the meaning of persistence? Persistence means 'to save'. In java, persistence is referred to saving the state of an objectfrom memory to some other media (mostly permanent media such as hard disk, but it can be a database, a network stream etc. etc.).Hibernate is an Object to Relational mapping framework. It helps in persisting (or saving)and loading (a.k.a mapping) the state of objects in your application to a relational database management system. The reason it is so popular is because it is based on configuration files (also called as declarative programming). It generate all the boilerplate JDBC code for you, you just have to focus on the API's methods to persist the objects from your java programs Is java fully object oriented? No There is lot many reasons to say...Java supports OOP concepts partially...But not fully...The main aim of java is to avoid any complexity for programmers...So they avoided almost all the complexity from the OOP...Like multiple inheritance, friend functions, operator overloading... Etc...The main reason for keeping primitive types as non-objects is speed. For all the places where primitive types dont make sense (such as containers etc.) you have the option to' wrap' then in their equivalent objects. JDK 1.5 even introduces the concept of autoboxing to make this transition even more programmers friendly Transient variable can't be final or static The modifier transient can be applied to field members of a class to turn off serialization on these field members. Every field marked as transient will not be serialized. You uset he transient keyword to indicate to the Java virtual machine that the transient variable is not part of the persistent state of an object. Java classes often hold some globally relevant value in a static class variable. The static member fields belong to class and not to an individual instance. The concept of serialization is concerned with the object's current state. Only data associated with a specific instance of a class is serialized, therefore static member fields are ignored during serialization (they are not

serialized automatically), because they do not belong to the serialized instance, but to the class. To serialize data stored in a static variable one must provide class-specific serialization. Surprisingly, the java compiler does not complaint if you declare a static member field a transient. However, there is no point in declaring a static member field as transient, since transient means: "do not serialize and static fields would not be serialized any way. On the other hand, an instance member field declared as final could also be transient, but if so, you would face a problem a little bit difficult to solve: As the field is transient, its state would not be serialized, it implies that, when you deserialize the object you would have to initialize the field manually, however, as it is declared final, the compiler would complaint about it. For instance, maybe you do not want to serialize your class' logger, then you declared it this way: private transient final Log log = LogFactory.getLog(EJBRefFactory.class); Now, when you deserialize the class your logger will be a null object, since it was transient. Then you should initialize the logger manually after serialization or during the serialization process. But you can't, because logger is a final members as well

Explain StreamTokenizer? The Stream Tokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles. Each byte read from the input stream is regarded as a character in the range '\u0000'through '\u00FF'. The character value is used to look up five possible attributes of the character: white space, alphabetic, numeric, string quote, and comment character. Each character can have zero or more of these attributes. In addition, an instance has four flags. These flags indicate :Whether line terminators are to be returned as tokens or treated as white space that merely separates tokens. Whether C-style comments are to be recognized and skipped. Whether C++-style comments are to be recognized and skipped. Whether the characters of identifiers are converted to lowercase.A typical application first constructs an instance of this class, sets up the syntax tables, and then repeatedly loops calling the next Token method in each iteration of the loop until it returns the value TT_EOF. What is the purpose of Void class? - The Void class is an un instantiable placeholder class to hold a reference to the Class object representing the primitive Java type void. Can an anonymous class implement an interface and extend a class at the same time? No, an anonymous class can either implement an interface or extend a class at a particular time but not both at the same time. Can protected or friendly features be accessed from different packages? No, when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package.

incomplete???? So you can't use static. (When you use static with a method, you can calldirectly without creating an object). So you can't do it. encodeURL vs. encodeRedirectURL Both these methods revolve around the concept of URL rewriting. I dont know whether u r aware bout this. But basically it involves suffixing the URL with aHTTP_QUERY_STRING,

which mostly is a session id used to keep track of a particular users context. URL re-writing is used get over the usage of cookies which are dependenton browser configuration, thus not reliable at all. Now Session is a comprehensive topicon its own, so wont discuss it now.But yes the difference between the methods is in their usage and not their functionality.Both perform the same task of re-writing a URL.us use encodeRedirectURL when u send a redirect header to the browser usingresponse.sendRedirect(string URL)for e.g. lets say on a particular condition u want to redirect to different pageif (name == null){response.sendRedirect(response(encodeRedirectURL("errorPage.jsp"))}on the other hand lets say u want to provide a link to shopping cart page to a user - printWriter.println("A HREF=" + response.encodeURL("shoppingCart.jasp") + ">")thus essentially they do same thing of rewriting the URL for non-cookie compliant browser.In short.....encodeURL is used for all URLs in a servlet's output.It helps session ids to be encoded with the URL.encodeRedirectURL () is used with res.sendRedirect only. It is also used for encodingsession ids with URL but only while redirecting. Difference between comparator and comparable? 1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package. 2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has methodpublic int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. 3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified. 4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface. 5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by CompareTo method. 6)Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator. What is the difference between Serializable and Externalizable interface in Java? This is most frequently asked question in java serialization interview. Here is my version Externalizable provides us writeExternal () and readExternal () method which gives us flexibility to control java serialization mechanism instead of relying on java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically. How many methods Serializable has? If no method then what is the purpose of Serializable interface? Serializable interface exists in java.io package and forms core of java serialization mechanism. It doesn't have any method and also called Marker Interface. When your class implements Serializable interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.

What is serialVersionUID? What would happen if you don't define this? SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object . serialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also. Consequence of not specifying serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throwsjava.io.InvalidClassException in case of serialVersionUID mismatch.

While serializing you want some of the members not to serialize? How do you achieve it? this is sometime also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don't want any field to be part of object's state then declare it either static or transient based on your need and it will not be included during java serialization process. What will happen if one of the members in the class doesn't implement Serializable interface? If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a NotSerializableException will be thrown at runtime and this is why I always put a SerializableAlert (comment section in my code) to instruct developer to remember this fact while adding a new field in a Serializable class. If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization? Java serialization process only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java And values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process . once the constructor chaining will started it wouldn't be possible to stop that , hence even if classes higher in hierarchy implements Serializable interface , there constructor will be executed. 7) Can you Customize Serialization process or can you override default Serialization process in Java? The answer is yes you can. We all know that for serializing an object objectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject () is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization or deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since onlyJava Virtual

Machine can call private method integrity of your class will remain and Java Serialization will work as normal. Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized? If Super Class of a Class already implements Serializable interface in Java then its already serializable in Java, since you can not unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid java serialization you need to implement writeObject () and readObject () method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above question and normally it asked as follow-up question as interview progresses. Which methods are used during Serialization and DeSerialization process in java? This is quite a common question basically interviewer is trying to know that whether you are familiar with usage of readObject (), writeObject (), readExternal () and writeExternal () or not. Java Serialization is done by java.io.ObjectOutputStream class. That class is a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call objectOutputStream.writeObject (saveThisobject) and to deserialize that object we call ObjectInputStream.readObject () method. Call to writeObject () method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be casted on correct type. Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized? It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don't provide serialVersionUID in our code java compiler will generate it and normally its equal to hash code of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class. What are the compatible changes and incompatible changes in Java Serialization Mechanism? The real challenge lies with change in class structure by adding any field, method or removing any field or method is that with already serialized object. As per Java Serialization specification adding any field or method comes under compatible change and changing class hierarchy or unimplementing Serializable interfaces some under non compatible changes. For complete list of compatible and non compatible changes I would advise reading java serialization specification. Can we transfer a Serialized object vie network?

Yes you can transfer a Serialized object via network because java serialized object remains in form of bytes which can be transmitter via network. Which kind of variables is not serialized during Java Serialization? This question asked sometime differently but the purpose is same whether Java developer knows specifics about static and transient variable or not. Since static variables belong to the class and not to an object they are not the part of the state of object so they are not saved during Java Serialization process. As Java Serialization only persist state of object and not object itself. Transient variables are also not included in java serialization process and are not the part of the objects serialized state. After this question sometime interviewer ask a follow-up if you don't store values of these variables then what would be value of these variable once you deserialize and recreate those object? This is for you guys to think about What are Chained Exceptions? The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. For example, lets say you are trying to read a number from the disk and using it to divide a number. Think the method throws an ArithmeticException because of an attempt to divide by zero (number we got). However, the problem was that an I/O error occurred, which caused the divisor to be set improperly (set to zero). Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error. This is the place where chained exceptions come in to picture. The below methods will be useful when dealing with chained exceptions. Throwable getCause( ) Throwable initCause(Throwable causeExc) Explain how Uncaught Exceptions are propagated? Actually, there's no requirement that you code a catch clause for every possible exception that could be thrown from the corresponding try block. If a method doesn't provide a catch clause for a particular exception, that method is said to be "ducking" the exception.

So what happens to a ducked exception? Before we discuss that, we need to briefly review the concept of the call stack. Most languages have the concept of a method stack or a call stack. Simply put, the call stack is the chain of methods that your program executes to get to the current method. If your program starts in method main() and main() calls method a(), which calls method b(), which in turn calls method c(), the call stack consists of the following:

a b c main We will represent the stack as growing upward (although it can also be visualized as growing downward). As you can see, the last method called is at the top of the stack, while the first calling method is at the bottom. The method at the very top of the stack trace would be the method you were currently executing. If we move back down the call stack, we're moving from the current method to the previously called method.

Now let's examine what happens to ducked exceptions. Imagine a building, say, five stories high, and at each floor there is a deck or balcony. Now imagine that on each deck, one person is standing holding a baseball mitt. Exceptions are like balls dropped from person to person, starting from the roof. An exception is first thrown from the top of the stack (in other words, the person on the roof), and if it isn't caught by the same person who threw it (the person on the roof), it drops down the call stack to the previous method, which is the person standing on the deck one floor down. If not caught there, by the person one floor down, the exception/ball again drops down to the previous method (person on the next floor down), and so on until it is caught or until it reaches the very bottom of the call stack. This is called exception propagation.

If an exception reaches the bottom of the call stack, it's like reaching the bottom of a very long drop; the ball explodes, and so does your program. An exception that's never caught will cause your application to stop running. A description (if one is available) of the exception will be displayed, and the call stack will be "dumped." What are different types of reference? java.lang.ref package can be used to declare soft, weak and phantom references. Garbage Collector won?t remove a strong reference. A soft reference will only get removed if memory is low. So it is useful for implementing caches while avoiding memory leaks. A weak reference will get removed on the next garbage collection cycle. Can be used for implementing canonical maps. The java.util.WeakHashMap implements a HashMap with keys held by weak references.

A phantom reference will be finalized but the memory will not be reclaimed. Can be useful when you want to be notified that an object is about to be collected. What is synchronization in respect to multi-threading in Java? With respect to multi-threading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to erroneous behavior or program. Explain different way of using thread? A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance. What is the difference between Thread.start() & Thread.run() method? Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread. Why do we need run() & start() method both. Can we achieve it with only run method? We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Javas multiple inheritance problems which will make it difficult to inherit another class with Thread. What is ThreadLocal class? How can it be used? Below are some key points about ThreadLocal variables
o o

A thread-local variable effectively provides a separate copy of its value for each thread that uses it. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread

o o

In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread. Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)

ThreadLocal variable are difficult to understand and I have found below reference links very useful in getting better understanding on them
o o o

Good article on ThreadLocal on IBM DeveloperWorks Managing data : Good example Refer Java API Docs

When InvalidMonitorStateException is thrown? Why? This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods. What is the difference between sleep(), suspend() and wait() ? Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread. t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone. object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like

sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object. What happens when I make a static method as synchronized? Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances. Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ? Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks. In case the method is not declared synchronized Jave will call even if you are playing with shared data. So you have to be careful while doing such thing. The decision of declaring a method as synchronized has to be based on critical section access. If your method does not access a critical section (shared resource or data structure) it need not be declared synchronized. Below is the example which demonstrates this, The Common class has two methods synchronizedMethod1() and method1() MyThread class is calling both the methods in separate threads, view plainprint? Can two threads call two different synchronized instance methods of an Object? No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed. See the below sample code which demonstrate it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods view plainprint? What is a deadlock? Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to

release the lock, unless one of the user processes is terminated. In terms of Java API, thread deadlock can occur in following conditions:
o o

When two threads call Thread.join() on each other. When two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.

What is Starvation? and What is a Livelock? Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter. LiveLock Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:
o

When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made. When all the threads in a program are stuck in infinite loops.

Starvation Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU. In Java, thread starvation can be caused by setting thread priorities inappropriately. A lowerpriority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time. How to find a deadlock has occurred in Java? How to detect a Deadlock in Java?

Earlier versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5 there are some powerful methods added in the java.lang.management package to diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application.
o

findMonitorDeadlockedThreads() - This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor. findDeadlockedThreads() - It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.

What is immutable object? How does it help in writing concurrent application? An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. Examples of immutable objects from the JDK include String and Integer. Immutable objects greatly simplify your multi threaded program, since they are
o o

Simple to construct, test, and use. Automatically thread-safe and have no synchronization issues.

To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor. How will you take thread dump in Java? How will you analyze Thread dump? A Thread Dump is a complete list of active threads. A java thread dump is a way of finding out what each thread in the JVM is doing at a particular point of time. This is especially useful when your java application seems to have some performance issues. Thread dump will help you to find out which thread is causing this. There are several ways to take thread dumps from a JVM. It is highly recommended to take more than 1 thread dump and analyze the results based on it. Follow below steps to take thread dump of a java process

What is a thread leak? What does it mean in Java? Thread leak is when a application does not release references to a thread object properly. Due to this some Threads do not get garbage collected and the number of unused threads grow with time. Thread leak can often cause serious issues on a Java application since over a period of time too many threads will be created but not released and may cause applications to respond slow or hang. How can I trace whether the application has a thread leak? If an application has thread leak then with time it will have too many unused threads. Try to find out what type of threads is leaking out. This can be done using following ways
o o o o o

Give unique and descriptive names to the threads created in application. - Add log entry in all thread at various entry and exit points in threads. Change debugging config levels (debug, info, error etc) and analyze log messages. When you find the class that is leaking out threads check how new threads are instantiated and how they're closed. Make sure the thread is Guaranteed to close properly by doing following Handling all Exceptions properly. Make sure the thread is Guaranteed to close properly by doing following Handling all Exceptions properly. releasing all resources (e.g. connections, files etc) before it closes.

What is thread pool? Why should we use thread pools? A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment. One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Below are key reasons to use a Thread Pool
o

Using thread pools minimizes the JVM overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application,

allocating and de-allocating many thread objects creates a significant memory management overhead. You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).

Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks. Can we synchronize the run method? If yes then what will be the behavior? Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object Can we synchronize the constructor of a Java Class? As per Java Language Specification, constructors cannot be synchronized because other threads cannot see the object being created before the thread creating it has finished it. There is no practical need of a Java Objects constructor to be synchronized, since it would lock the object being constructed, which is normally not available to other threads until all constructors of the object finish

This is not an exhaustive list of questions and I am sure I have missed many important questions from Multi-threading area. Can you think of a question which should be included in this list? Please feel free to share any question/suggestion in the comments section. How are Observer and Observable used? 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 the difference between the >> and >>> operators? The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out What is the difference between yielding and sleeping? 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. Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection Can an object's finalize() method be invoked while it is reachable? An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable.However, an object's finalize() method may be invoked by other objects. What are order of precedence and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left What is the advantage of the event-delegation model over the earlier event-inheritance model? The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the eventdelegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. How are Java source code files named? A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension

What is an object's lock and which object's have locks? An object's 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 object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object. If a class is declared without any access modifiers, where may the class be accessed? A class that is declared without any access modifiers is said to have package 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 SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar. What is the difference between the File and RandomAccessFile classes? 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 is numeric promotion? Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required. What are synchronized methods and synchronized statements? 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 method's 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. Java and C++ A: Some of the similarities and differences are in the table: Features Pointer Java C/C++ Yes

No Operator Overload No

Typedef, Define, Preprocessors Structures, Unions Enums Functions Goto statement No Yes No No Yes No (only methods within classes) Yes No Yes No(types should be converted explicitly) No. Variable is part of a class Yes No Yes Yes Yes

Automatic Coercions Global Variables Templates

Private, Protected, Public Inheritance Default parameters Garbage Collection Multi-thread support Multiple Inheritance Yes. Supports only interface inheritance and not implementation inheritance! Yes Exception Handling Yes. try/catch must be defined if the function declares that it may throw an exception. Yes. You may not include the try/catch even if the function throws an exception. Function Overload Internationalization Include of other Objects #import Yes Yes Yes Yes #include No Yes No Yes Yes No Yes No

Comments

"//","/* */,/** */ "//","/* */"

What are the main differences between Java and C++? Everything is an object in Java( Single root hierarchy as everything gets derived from java.lang.Object) Java does not have all the complicated aspects of C++ ( For ex: Pointers, templates, unions, operator overloading, structures etc..) The Java language promoters initially said "No pointers!", but when many programmers questioned how you can work without pointers, the promoters began saying "Restricted pointers." You can make up your mind whether its really a pointer or not. In any event, theres no pointer arithmetic. There are no destructors in Java. (automatic garbage collection) Java does not support conditional compile (#ifdef/#ifndef type). Thread support is built into java but not in C++. Java does not support default arguments. Theres no scope resolution operator :: in Java. Java uses the dot for everything, but can get away with it since you can define elements only within a class. Even the method definitions must always occur within a class, so there is no need for scope resolution there either.Theres no "goto " statement in Java. Java doesnt provide multiple inheritance (MI), at least not in the same sense that C++ does. Exception handling in Java is different because there are no destructors. Java says "write once, run anywhere". What are some ways this isn't quite true? Any time you use system calls specific to one operating system and do not create alternative calls for another operating system, your program will not function correctly. Solaris systems and Intel systems order the bits of an integer differently. (You may have heard of little endian vs. big endian) If your code uses bit shifting, or other binary operators, they will not work on systems that have opposide endianism. Describe java's security model. Java's security model is one of the most interesting and unique aspects of the language. For the most part it's broken into two pieces: the user adjustable security manager that checks various API operations like file access, and the byte code verifier that asserts the validity of compiled byte code. public abstract class SecurityManager java.lang.SecurityManager is an abstract class which differentapplications subclass to implement a particular security policy. It allows an application to determine whether or not a particular operation will generate a security exception.

Vous aimerez peut-être aussi