Advanced Java Interview Questions And Answers

Q.1.What is a java object and java application??
A. Java object is an object that is provided by the execution of an application. When an application is compiled an object of that application is being made. Java application on the other hand is a program that is being written in Java and being read by the Java virtual machine.
Q.2.What is the purpose of garbage collection in Java, and when is it used?
A. 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.
Q.3.Advantages and disadvantages of Java Sockets.
A. Advantages of Java Sockets :- Sockets are flexible and easy to implemented for general communications.- Sockets cause low network traffic unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request.Disadvantages of Java Sockets :- Socket based communications allows only to send packets of raw data between applications.- Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
Q.4.Describe synchronization in respect to multithreading.
A. 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 variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Q.5.Explain different way of using thread?
A. The 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.
Q.6.What is the difference between multitasking and multithreading?
A. Multitasking includes two ways for representation :1. Preemptive multitasking: where the system terminates the idle process without asking the user. For example: Unix/Linux, Windows NT2. Non-preemptive multitasking: where the system ask the process to give the control to other process for execution. For example: Windows 3.1 and Mac OS 9.Multithreading :1. Multithreaded programs are the program that extend the functionality of the multitasking by dividing the program in thread and then execute the task as individual threads.2. Threads run in a different area and each thread utilizes some amount of CPU and memory for execution.
Q.7.What is synchronization and why is it important?
A. 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.
Q.8.What are the different ways to handle exceptions?
A. There are two ways to handle exceptions, 1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and 2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.
Q.9.When you serialize an object, what happens to the object references included in the object?
A. 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.
Q.10.When you serialize an object, what happens to the object references included in the object?
A. 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.
Q.11.What is Externalizable interface?
A. 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.
Q.12.How can I customize the seralization process? i.e. how can one have a control over the serialization process?
A. 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.
Q.13.How do I serialize an object to a file?
A. 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.
Q.14.Objects are passed by value or by reference?
A. 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 .
Q.15.What is the difference between declaring a variable and defining a variable?
A. In declaration we just mention the type of the variable and it’s name. We do not initialize it. But defining means declaration + initialization.e.g String s; is just a declaration while String s = new String (“abcd”); Or String s = “abcd”; are both definitions.
Q.16.What are Checked and UnChecked Exception?
A. A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making 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 Unchecked 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 exception 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() methodChecked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
Q.17.What is static in java?
A. A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making 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 Unchecked 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 exception 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() methodChecked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
Q.18. What is the difference between an Interface and an Abstract class?
A. Java provides and supports the creation both of abstract classes and interfaces. Both implementations share some common characteristics, but they differ in the following features:All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods.
A class may implement a number of Interfaces, but can extend only one abstract class.
In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
Abstract classes can implement interfaces without even providing the implementation of interface methods.
Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.
Q.19. What differences exist between HashMap and Hashtable?
A. There are several differences between HashMap and Hashtable in Java:

  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  3. One of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn’t be as easy if you were using Hashtable.
Q.20. What is the difference between Exception and Error in java?
A. 

  • An Error “indicates serious problems that a reasonable application should not try to catch.”
  • An Exception “indicates conditions that a reasonable application might want to catch.”
Q.21. How does Garbage Collection prevent a Java application from going out of memory?
A. It doesn’t! Garbage Collection simply cleans up unused memory when an object goes out of scope and is no longer needed. However an application could create a huge number of large objects that causes an OutOfMemoryError.
Q.22. What is reflection and why is it useful?
A. The name reflection is used to describe code which is able to inspect other code in the same system (or itself) and to make modifications at runtime.For example, say you have an object of an unknown type in Java, and you would like to call a ‘doSomething’ method on it if one exists. Java’s static typing system isn’t really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called ‘doSomething’ and then call it if you want to.
Q.23. How can I synchornize two Java processes?
A. It is not possible to do something like you want in Java. Different Java applications will use different JVM’s fully separating themselves into different ‘blackbox’es. However, you have 2 options:

  • Use sockets (or channels). Basically one application will open the listening socket and start waiting until it receives some signal. The other application will connect there, and send signals when it had completed something. I’d say this is a preferred way used in 99.9% of applications.
  • You can call winapi from Java (on windows).
Q.24. What is difference between fail-fast and fail-safe?
A. The Iterator’s fail-safe property works with the clone of the underlying collection and thus, it is not affected by any modification in the collection. All the collection classes in java.util package are fail-fast, while the collection classes in java.util.concurrent are fail-safe. Fail-fast iterators throw a ConcurrentModificationException, while fail-safe iterator never throws such an exception.
Q.25. What is a JavaBean exactly?
A. Basically, a “Bean” follows the standart:

  • is a serializable object (that is, it implements java.io.Serializable, and does so correctly), that
  • has “properties” whose getters and setters are just methods with certain names (like, say, getFoo() is the getter for the “Foo” property), and
  • has a public 0-arg constructor (so it can be created at will and configured by setting its properties).

There is no syntactic difference between a JavaBean and another class – a class is a JavaBean if it follows the standards.

Q.26. Is Java “pass-by-reference” or “pass-by-value”?
A. Java is always pass-by-value. Unfortunately, when we pass the value of an object, we are passing the reference to it. There is no such thing as “pass-by-reference” in Java. This is confusing to beginners.The key to understanding this is that something like

Dog myDog;

is not a Dog; it’s actually a pointer to a Dog.

So when you have

Dog myDog = new Dog("Rover");
foo(myDog);

you’re essentially passing the address of the created Dog object to the foo method.

Q.27. What is the difference between throw and throws?
A. The throw keyword is used to explicitly raise a exception within the program. On the contrary, the throws clause is used to indicate those exceptions that are not handled by a method. Each method must explicitly specify which exceptions does not handle, so the callers of that method can guard against possible exceptions. Finally, multiple exceptions are separated by a comma.
Q.28. What is structure of Java Heap?
A. The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector.
Q.29. What is the tradeoff between using an unordered array versus an ordered array?
A. The major advantage of an ordered array is that the search times have time complexity of O(log n), compared to that of an unordered array, which is O (n). The disadvantage of an ordered array is that the insertion operation has a time complexity of O(n), because the elements with higher values must be moved to make room for the new element. Instead, the insertion operation for an unordered array takes constant time of O(1).
Q.30. Can == be used on enum?
A. enums have tight instance controls that allows you to use == to compare instances. Here’s the guarantee provided by the language specification.
Q.31. What are the differences between == and equals?
A. As a reminder, it needs to be said that generally, == is NOT a viable alternative to equals. When it is, however (such as with enum), there are two important differences to consider:

  1. == never throws NullPointerException
enum Color { BLACK, WHITE };

Color nothing = null;
if (nothing == Color.BLACK);      // runs fine
if (nothing.equals(Color.BLACK)); // throws NullPointerEx
  1. == is subject to type compatibility check at compile time
enum Color { BLACK, WHITE };
enum Chiral { LEFT, RIGHT };

if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine
if (Color.BLACK == Chiral.LEFT);      // DOESN'T COMPILE!!! Incompatible types!
Q.32. What is the main difference between StringBuffer and StringBuilder?
A. 

  • StringBuffer is synchronized, StringBuilder is not. When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem.
  • StringBuilder is faster than StringBuffer because it’s not synchronized. Using synchronized methods in a single thread is overkill.
Q.33. Why does Java have transient fields?
A. The transient keyword in Java is used to indicate that a field should not be part of the serialization.By default, all of object’s variables get converted into a persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the need to persist those variables. So you can declare those variables as transient. If the variable is declared as transient, then it will not be persisted.
Q.34. What is static initializer?
A. The static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called. If you had to perform a complicated calculation to determine the value of x — or if its value comes from a database — a static initializer could be very useful.Consider:

class StaticInit {
    public static int x;
    static {
        x = 32;
    }
    // other class members such as constructors and
    // methods go here...
}
Q.35. Is there anything like static class in java?
A. Java has no way of making a top-level class static but you can simulate a static class like this:Declare your class final – Prevents extension of the class since extending a static class makes no sense
Make the constructor private – Prevents instantiation by client code as it makes no sense to instantiate a static class
Make all the members and functions of the class static – Since the class cannot be instantiated no instance methods can be called or instance fields accessed
Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member