Java Interview Study
What is the difference between an Abstract class and Interface?
1. Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code.\n2. An class can implement any number of interfaces, but subclass at most one abstract class.\n3. An abstract class can have nonabstract methods. All methods of an interface are abstract.\n4. An abstract class can have instance variables. An interface cannot.\n5. An abstract class can define constructor. An interface cannot.\n6. An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package).\n7. An abstract class inherits from Object and includes methods such as clone() and equals().
What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
What is the difference between a break statement and a continue statement?
A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
What are Checked and UnChecked Exception?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.\nMaking an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·\nUnchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the\nexception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
What is the difference between a constructor and a method?
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.\nA method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
What is final?
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.
If a variable is declared as private, where may the variable be accessed?
A private variable may only be accessed within the class in which it is declared.
What is the argument type of a program's main() method?
A program's main() method takes an argument of the String[] type.
When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.
When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.
What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.\nA class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
What invokes a thread's run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
What is the difference between aggregation and composition?
Aggregation is an association in which one class belongs to a collection. This is a part of a whole \nrelationship where a part can exist without a whole. For example a line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted. So aggregation has a weaker relationship. \n\nComposition is an association in which one class belongs to a \ncollection. This is a part of a whole relationship where a part \ncannot exist without a whole. If a whole is deleted then all parts are \ndeleted. For example An order is a whole and line items are parts. \nIf an order is deleted then all corresponding line items for that \norder should be deleted. So composition has a stronger \nrelationship.
What is the difference between an Interface and an Abstract class?
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
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.
How many times may an object's finalize() method be invoked by the garbage collector?
An object's finalize() method may only be invoked once by the garbage collector.
What are checked exceptions?
Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.
Explain Java class loaders?
Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that \nis already running in the JVM. So, how is the very first class loaded? The very first class is especially loaded with \nthe help of static main( ) method declared in your class. All the subsequently loaded classes are loaded by the \nclasses, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one \nclass loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let's look at \nnon-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of \nprimordial class loader. Let us look at the class loaders created by the JVM.
What is similarities/difference between an Abstract class and Interface?
Differences are as follows:\n\n * Interfaces provide a form of multiple inheritance. A class can extend only one other class.\n * Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.\n * A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.\n * Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.\n\nSimilarities:\n\n * Neither Abstract classes or Interface can be instantiated.
What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
When to use an interface?
For polymorphic interface inheritance, where the client wants to only deal with a type and does not care about the actual implementation use interfaces. If you need to change your design frequently, you should prefer using interface to abstract. Coding to an interface reduces coupling and \ninterface inheritance can achieve code reuse with the help of object composition.
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
What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
How to call the superclass constructor?
If a class called "SpecialPet" extends your "Pet" class then you can \nuse the keyword "super" to invoke the superclass's constructor.
What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
What type of parameter passing does Java support?
In Java the arguments are always passed by value .
Is Java pass by value or pass by reference?
In Java, Objects are passed by reference, and primitives are passed by value.\n\nThis is half incorrect. Everyone can easily agree that primitives are passed by value; there's no such thing in Java as a pointer/reference to a primitive.\n\nHowever, Objects are not passed by reference. A correct statement would be Object references are passed by value.
When to use an abstract class?
In case where you want to use implementation inheritance then it is usually provided by an abstract base class. Abstract classes are excellent candidates inside of application frameworks. Abstract classes let you define some default behavior and force subclasses to provide any specific behavior.
What is the difference between an abstract class and an interface?
In design, you want the base class to present only an interface for its derived classes. This means, you don't want anyone to actually instantiate an object of the base class. You only want to upcast to it (implicit upcasting, which \ngives you polymorphic behavior), so that its interface can be used. This is accomplished by making that class \nabstract using the abstract keyword. If anyone tries to make an object of an abstract class, the compiler prevents \nit.\n\nThe interface keyword takes this concept of an abstract class a step further by preventing any method or function \nimplementation at all. You can only declare a method or function but not provide the implementation. The class, \nwhich is implementing the interface, should provide the actual implementation
Why do we need wrapper classes?
It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.
What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its implements clause.
How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
Is synchronised a modifier?indentifier??what is it??
It's a modifier. 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.
s Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of a Collection.
What are checked and unchecked exceptions?
Java defines two kinds of exceptions :\n\n * Checked exceptions : Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. Examples - SQLException, IOxception.\n * Unchecked exceptions : RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions. Example Unchecked exceptions are NullPointerException, OutOfMemoryError, DivideByZeroException typically, programming errors.
Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .
What is HashMap and Map?
Map is Interface and Hashmap is class that implements that.
What are different types of inner classes?
Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.\nAny class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.\n\nMember classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.\n\nLocal classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a\nmore publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.\n\nAnonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.
Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.
Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA?
Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable
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 one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
When is a method said to be overloaded?
Overloading deals with multiple methods in the same class \nwith the same name but different method signatures. \n \nclass MyClass { \n public void getInvestAmount(int rate) {...} \n \n public void getInvestAmount(int rate, long principal) \n { ... } \n} \n \nBoth the above methods have the same method names \nbut different method signatures, which mean the methods \nare overloaded. \n\nOverloading lets you define the same operation in \ndifferent ways for different dat
When is a method said to be overridden?
Overriding deals with two methods, one in the parent class and \nthe other one in the child class and has the same name and \nsignatures. \n\nOverriding lets you define the same operation in different \nways for different object types. \n \nclass BaseClass{ \n public void getInvestAmount(int rate) {...} \n} \n \nclass MyClass extends BaseClass { \n public void getInvestAmount(int rate) { ...} \n} \n \nBoth the above methods have the same method names and \nthe signatures but the method in the subclass MyClass \noverrides the method in the superclass BaseClass.
What are pass by reference and passby value?
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.
What do you mean by polymorphism?
Polymorphism - means the ability of a single variable of a given type to be used to reference objects of \ndifferent types, and automatically call the method that is specific to the type of object the variable references. In a \nnutshell, polymorphism is a bottom-up method call.
Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.
What if I write static public void instead of public static void?
Program compiles and runs properly.
What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
What is serialization?
Quite simply, object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. A seralizable object must implement the Serilizable interface. We use ObjectOutputStream to write this object to a stream and ObjectInputStream to read it from the stream.
What are runtime exceptions?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
What is singleton class?where is it used?
Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons--for example, we may only want a single instance of a pool of database connections.
What is an Iterator?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.
Is string a wrapper class?
String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each primitive type. They can be used to convert a primitive data value into an object, and vice-versa.
What is the difference between the String and StringBuffer classes?
String objects are constants. StringBuffer objects are not.
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 Collection API?
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.\n\nExample of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.\n\nExample of interfaces: Collection, Set, List and Map.
Which java.util classes and interfaces support event handling?
The EventObject class and the EventListener interface support event processing.
Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.
What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.
Why java does not have multiple inheritance?
The Java design team strove to make Java:\n\n * Simple, object oriented, and familiar\n * Robust and secure\n * Architecture neutral and portable\n * High performance\n * Interpreted, threaded, and dynamic
What is the List interface?
The List interface provides support for ordered collections of objects.
What are the advantages of Object Oriented Programming Languages (OOPL)?
The Object Oriented Programming Languages directly represent the real life objects like Car, Jeep, Account, \nCustomer etc. The features of the OO programming languages like polymorphism, inheritance and \nencapsulation make it powerful. [Tip: remember pie which, stands for Polymorphism, Inheritance and \nEncapsulation are the 3 pillars of OOPL]
What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
Why there are some interfaces with no defined methods (i.e. marker interfaces) in Java?
The interfaces with no defined methods act like markers. They just tell the compiler that the objects of the classes \nimplementing the interfaces with no defined methods need to be treated differently. Example java.io.Serializable , java.lang.Cloneable, java.util.EventListener etc. Marker interfaces are also known as \n"tag" interfaces since they tag all the derived classes into a category based on their purpose.
What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
What is the purpose of garbage collection in Java, and when is it used?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.
Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
When you serialize an object, what happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
What method is invoked to cause an object to begin executing as a separate thread?
The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.
What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods..
What happens to the static fields of a class during serialization?
There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are\n1. Serialization ignores static fields, because they are not part of ay particular state state.\n2. Base class fields are only hendled if the base class itself is serializable.\n3. Transient fields.
Why do threads block on I/O?
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.
What is transient variable?
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.
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 is a user defined exception?
User-defined exceptions may be implemented by\n\n * defining a class to respond to the exception and\n * embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception (to another method where it is handled).
Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not
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.
What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.
Describe synchronization in respect to multithreading.
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.
What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
How can I customize the seralization process? i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following:\n\nfor(;;) ;
an a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object..
Can you call one constructor from another?
Yes, by using this() syntax
What happens if you do not provide a constructor?
ava does not actually require an explicit constructor in \nthe class description. If you do not include a constructor, the Java compiler will create a default constructor in the \nbyte code with an empty argument. This default constructor is equivalent to the explicit "Pet(){}". If a class includes \none or more explicit constructors like "public Pet(int id)" or "Pet(){}" etc, the java compiler does not create the \ndefault constructor "Pet(){}".
What if the main method is declared as private?
he program compiles properly but at runtime it will give "Main method not public." message.
Explain different way of using thread?
he thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
o what value is a variable of the String type automatically initialized?
null
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
public : Public class is visible in other packages, field is visible everywhere (class must be public too)\nprivate : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.\nprotected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.\ndefault :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.