Advanced Java Interview Questions and Answers -15

Advanced Java Interview Questions and Answers -15

1 is there ever a case when a singleton may return a differnt instance

yes when the singleton is loaded with a different class loader.

2 write a class that implements the following

if the object has been seen before, returns the same integer
if the object has not been seen before returns a different integer.

3  What is the difference between NoClassDefFoundError and a ClassNotFoundException

ClassNotFoundException is thrown when an application tries to load in a class through its string name using:

The forName method in class Class.
The findSystemClass method in class ClassLoader .
The loadClass method in class ClassLoader.

NoClassDefFoundError usually happens when the class that you compiled against is not available at run time. For example the Jar is not on your class path.

4 Does this produce a runtime error

public class Test {

public static void main(String… args) {

Object o = new Object() {
public boolean equals(Object t) {
return t.equals(“hi”);


5 A class that supports serializarion must implement serializable, if its base class is not serizable then what must it have. ?

A default constructor

6 What are the thread states in java ?

State     Description
NEW     A thread that has not yet started is in this state.
RUNNABLE     A thread executing in the Java virtual machine is in this state.
BLOCKED     A thread that is blocked waiting for a monitor lock is in this state.
WAITING     A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING     A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED     A thread that has exited is in this state.

7 Name three JVMs ?

some of them are:
Windows JVM

8 How do you redirect the System.out ( “standard” output stream ) to a file ?


9 Which method should you override when writing a Customer Class Loader ?

class CustomClassLoader extends ClassLoader {
String host;
int port;

public Class findClass(String name) {
byte[] b = loadClassData(name);
return defineClass(name, b, 0, b.length);

private byte[] loadClassData(String name) {
// load the class data from the connection

// then to load your class
Class r = new CustomClassLoader().findClass(“com.x.MyClass”);


Class.forName(“com.x.MyClass”,true,new CustomClassLoader());

10 Describethe following exceptions : CloneNotSupportedException, ClassNotFoundException, ArrayStoreException, ClassCastException, ConcurrentModificationException, IllegalMonitorStateException, UnsupportedOperationException.

Checked Exceptions
CloneNotSupportedException Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object’s class does not implement the Cloneable interface.
ClassNotFoundException Thrown when an application tries to load in a class through its string name, and this fails.

Runtime Exceptions
ArrayStoreException Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
ClassCastException Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
IllegalMonitorStateException Thrown to indicate that a thread has attempted to wait on an object’s monitor or to notify other threads waiting on an object’s monitor without owning the specified monitor.
UnsupportedOperationException Thrown to indicate that the requested operation is not supported.

11 What is the difference between parameters and arguments

parameters – make up the method signature ( these are what you are expecting )
arguments – are what you are sending.

12 what is object orientation

Programming techniques may include features such as data abstraction, encapsulation, modularity, polymorphism, and inheritance

13 If the compareTo method of a comparable object returns zero are they equal

Usually but not always, virtually all Java core classes that implement comparable have natural orderings that are consistent with equals. One exception is java.math.BigDecimal, whose natural ordering equates BigDecimal objects with equal values and different precisions (such as 4.0 and 4.00).

It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave “strangely” when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.

14 List all the types of nested class ?

Class Type     Description
static inner class     the static inner class can only access the static fields of the enclosing class and define its own static fields.
non static inner class     the inner class can access all the fields of the enclosing class, they can define there own fields but these can not be static.
local class     This is a class inside a method, the local inner class can access all the fields from the enclosing class and all final parameters from the enclosing method, they can define there own fields but these can not be static.
anonymous class

15 What is the quickest type of Map ?


16 How to increase the heap memory of the JVM ?

-Xmx (maximum heap size)

17 In java 6, how can you see the assembly code that the JIT is creating ?


18 What is the signature of readResolve() and what is it used for ?

The read resolve method will be called ( if exists ) to create the object. Note : the constructor of the object does not get called if readResolve() is called ( so this is one way to create an object without calling its constructor )

ANY-ACCESS-MODIFIER Object readResolve()
throws ObjectStreamException;

19 Name 10 Ways to Reduce Lock Contention in Threaded Programs ?

1.Protect data, not code.
2.Get rid of expensive calculations while in locks.
3.Use lock striping.
4.Employ interlocked / atomic operations.
5.Use synchronized data structures.
6.Use Reader-Writer Locks where applicable.
7.Use Read-Only data whenever possible.
8.Avoid Object Pooling.
9.Use local variables or thread-local storage.
10. Avoid hotspots.

20 How do you create an array using reflection

import java.lang.reflect.*;

public class array1 {
public static void main(String args[])
try {
Class cls = Class.forName(
Object arr = Array.newInstance(cls, 10);
Array.set(arr, 5, “this is a test”);
String s = (String)Array.get(arr, 5);
catch (Throwable e) {

21 Other than using externizable, how can you handle custom serilization ?

private void writeObject( out)
throws IOException
private void readObject( in)
throws IOException, ClassNotFoundException;

22 Can a top level class be have a protected class modifier

No, only inner class can have protected class modifier access. The top level class can not be private or protected.

23 With java collections, whats the difference between Offer(E e) and Add(E e).

generally the following is true :
Throws exception     Special value
add     offer
remove     poll
get     peek

Add(E e) Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an Exception if no space is currently available.

Offer() Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(E), which can fail to insert an element only by throwing an exception. It is implemented in Queue and Deque.

24  What is the difference between weak and soft references

A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.

25 How do you create a singleton

import org.apache.log4j.Logger;

public final class Singleton {

private static final Logger LOG = Logger.getLogger(Singleton.class);

private static Singleton instance;

// we create a holder tha lazy loads the class
private static class Holder {
static {“instance created”);
instance = new Singleton();

public static Singleton getInstance() {
return instance;


private Singleton() {

public static Singleton getInstance() {
return Holder.getInstance();

public static String helloWorld() {
return “hello”;

public static void main(String… args) {;


30-06-10 12:32:35 [INFO ] [main] Singleton – hello
30-06-10 12:32:35 [INFO ] [main] Singleton – instance created

26 what are memory barriers

27 what is escape analysis


28 what are synthetic bridge methods

Synthetic methods are often referred to as bridge methods in Java generics world. These methods are created by the Java compiler as a result of type erasure when the signature of the inherited methods change when a type extends or implements parameterized classes or interfaces. The compiler generates synthetic methods in subtypes of parameterized supertypes to make sure that subtyping works as expected.

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

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

30 What is the purpose of the System class?

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

31 What restrictions are placed on method overloading?

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

32 Why Java does not support multiple inheritance?

Java does support multiple inheritance via interface implementation.

33 What is Method Overriding? What restrictions are placed on method overriding?

When a class defines a method using the same name, return type, and argument list as that of a method in its superclass, the method in the subclass is said to override the method present in the Superclass. When the method is invoked for an object of the
class, it is the new definition of the method that is called, and not the method definition from superclass.
Restrictions placed on method overriding
• Overridden methods must have the same name, argument list, and return type.
• The overriding method may not limit the access of the method it overrides. Methods may be overridden to be more public, not more private.
• The overriding method may not throw any exceptions that may not be thrown by the overridden method.

34 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 or default access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

35 What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system.
It returns the runtime information like memory availability.
* Runtime.freeMemory() –> Returns JVM Free Memory
* Runtime.maxMemory() –> Returns the maximum amount of memory that the JVM will attempt to use. It also helps to run the garbage collector
* Runtime.gc()

36 What would happen if you say this = null?

It will come up with Error Message
“The left-hand side of an assignment must be a variable”.

37 Which method of the Component class is used to set

the position and size of a component?

38 What is the functionality of instanceOf() ?

instanceOf opertaor is used to check whether an object can be cast to a specific type without throwing ClassCastException.

39 Does a class inherit the constructors of its superclass?

A class does not inherit constructors from any of its super classes.

40 What is a bean? Where can it be used?

A Bean is a reusable and self-contained software component. Beans created using java take advantage of all the security and platform independent features of java. Bean can be plugged into any software application. Bean is a simple class which has set and get methods. It could be used within a JSP using JSP tags to use them.

41 Where and how can you use a private constructor?

Private constructor can be used if you do not want any other class to instantiate the class. This concept is generally used in Singleton Design Pattern. The instantiation of such classes is done from a static public method.

42 What is a singleton class?

This design pattern is used by an application to ensure that at any time there is only one instance of a class created. You can achieve this by having the private constructor in the class and having a getter method which returns an object of the class and creates one for the first time if its null.

43 What is method overloading and method overriding?

Method overloading: When 2 or more methods in a class have the same method names with different arguments, it is said to be method overloading. Overloading does not block inheritance from the superclass. Overloaded methods must have different method signatures
Method overriding : When a method in a class has the same method name with same arguments as that of the superclass,
it is said to be method overriding. Overriding blocks inheritance from the superclass. Overridden methods must have same signature.
Basically overloading and overriding are different aspects of polymorphism.
static/early binding polymorphism: overloading
dynamic/late binding polymorphism: overriding

44 Can an unreachable object become reachable again?

An unreachable object may become reachable again. This can happen when the object’s finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable object.

45 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.

46 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.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

47 What is the difference between String and StringBuffer?

String objects are immutable whereas StringBuffer objects are not. StringBuffer unlike Strings support growable and modifiable strings.

48 Differentiate between a Class and an Object?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. The Class class is used to obtain information about an object’s design. A Class is only a definition or prototype of real life object. Whereas an object is an instance or living representation of real life object. Every object belongs to a class and every class contains one or more related objects.

49 Which java.util classes and interfaces support event handling?

The EventObject class and the EventListener interface support event processing

50 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.

51 In Java, what is the difference between an Interface and an Abstract class?

An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. 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.

52 In C++, what is the usefulness of Virtual destructors?

Virtual destructors are neccessary to reclaim memory that were allocated for objects in the class hierarchy. If a pointer to a base class object is deleted, then the compiler guarantees the various subclass destructors are called in reverse order of the object construction chain.

53 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.

54 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.

55 In what ways do design patterns help build better software?

Design patterns helps software developers to reuse successful designs and architectures. It helps them to choose design alternatives that make a system reusuable and avoid alternatives that compromise reusability through proven techniques as design patterns.

56 Describe 3-Tier Architecture in enterprise application development.

In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-defined set of interfaces. The presentation layer typically consists of a graphical user interfaces. The business layer consists of the application or business logic, and the data layer contains the data that is needed for the application

57 1. User Interface Programming using Java Swings
1.1 Java Swings Basics
1.1.1 Introduction to Swings
1.1.2 Creating a Frame
1.1.3 Positioning a Frame
1.1.4 Displaying Information in a Component
1.1.5 Working with 2D Shapes
1.1.6 Using Colors
1.1.7 Using Special Fonts for Text
1.1.8 Displaying Images

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

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

59 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, invoked using the new operator. It has the same name as the class and has no return type. They are only called once, whereas member functions can be called many times. A 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. Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.
super.method(); is used to call a super class method from a sub class. To call a constructor of the super class, we use the super(); statement as the first line of the subclass’s constructor.

60 What is the default value of an object reference declared as an instance variable?

null unless we define it explicitly.

61 Can a top-level class be private or protected?

No. A top-level class cannot 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/protected the compiler will complain that the “modifier private is not allowed here”.

62 Can you have virtual functions in Java? Yes or No. If yes, then what are virtual functions?

Yes, Java class functions are virtual by default. Virtual functions are functions of subclasses that can be invoked from a reference to their superclass. In other words, the functions of the actual object are called when a function is invoked on the reference to that object.

63 What are mutex and semaphore? What is the difference between them?

A:A mutex is a synchronization object that allows only one process or thread to access a critical code block. A semaphore on the other hand allows one or more processes or threads to access a critial code block. A semaphore is a multiple mutex

64 How is JavaBeans differ from Enterprise JavaBeans?

The JavaBeans architecture is meant to provide a format for general-purpose components. On the other hand, the Enterprise JavaBeans architecture provides a format for highly specialized business logic components.

65 Write a function to reverse a linked list p in C++?

Link* reverse_list(Link* p)
if (p == NULL)
return NULL;

Link* h = p;
p = p->next;
h->next = NULL;
while (p != null)
Link* t = p->next;
p->next = h;
h = p;
p = t;

return h;

66 1.2 Event Handling
1.2.1 Basics of Event Handling
1.2.2 Creating Listeners containing a Single Method Call
1.2.3 Actions
1.2.4 Mouse Events
1.2.5 The AWT Event Hierarchy

67 Java Distributed Objects – Remote Method Invocation
9.1 The Roles of Client and Server
9.2 Remote Method Calls
9.3 The RMI Programming Model
9.4 Parameters and Return Values in Remote Methods
9.5 Remote Object Activation
9.6 Web Services
9.7 JAX – WS

68 Using Native Methods in Java
11.1 Calling a C Function from a Java Program
11.2 Numeric Parameters and Return Values
11.3 String Parameters
11.4 Accessing Fields
11.5 Encoding Signatures
11.6 Calling Java Methods
11.7 Accessing Array Elements
11.8 Handling Errors

69 Java Internationalization
6.1 Locales
6.2 Number Formats
6.3 Date & Time
6.4 Collation
6.5 Message Formatting
6.6 Text Files and Character Sets
6.7 Resource Bundles
6.8 An Example

70 Java Security
8.1 Class Loaders
8.2 Bytecode Verification
8.3 Security Managers & Permissions
8.4 User Authentication
8.5 Digital Signatures
8.6 Code Signing
8.7 Encryption

71 Which of the following are true about final variable declaration?

public class Test {
final int i;
public Test(){

72 Can a class can be declared protected?

public strictfp class Myclass {
// … contents of class here …

73 x = a+b;

System.out.println(“Result = “+x);

74 Can Inner class can be a final class?

public class Test {
int Test ;
public void Test(){
double Test;

75 will it compile?

public abstract class Test {

76 Scripting, Compiling and Annotation using Java

10.1 Scripting for the Java Platform
10.2 The Compiler API
10.3 Using Annotations
10.4 Annotation Syntax
10.5 Standard Annotations
10.6 Source Level Annotation Processing
10.7 Bytecode Engineering
11.9 Using the Invocation API
11.10 An Example using Native Methods

77          i=10;

Will the above code will run?
public class Test {
final int i;
public Test(){

78 i = i*i;

return i ;

79 is this valid?

int calculateSquare(final double i){

80 Streams & Files

2.1 Streams
2.2 Text Input and Output
2.3 Reading& Writing Binary Data
2.4 ZIP Archives
2.5 Object Streams & Serialization
2.6 File Management
2.7 New I/O Concepts
2.8 Regular Expressions

81 int a=2,b=3;

double x;

82 Creating User Interface Components with Swing
1.3.1 Swing and the MVC Design Pattern
1.3.2 Introduction to Layout Management
1.3.3 Text Input
1.3.4 Choice Components
1.3.5 Menus
1.3.6 Sophisticated Layout Management
1.3.7 Dialog Boxes
83 . Java Beans
7.1 Why use Beans
7.2 The Bean Writing Process
7.3 Using Beans to build an Application
7.4 Naming Patterns for Bean Properties and Events
7.5 Bean Property Types
7.6 BeanInfo Classes
7.7 Property Editors
7.8 Customizers
7.9 JavaBean Persistence
84 Java Networking Concepts
4.1 Connecting to a Server
4.2 Implementing Servers
4.3 Interruptible Sockets
4.4 Sending e-mail
4.5 Making URL Connections

85 Database Programming using Java
5.1 JDBC Design
5.2 The Structured Query Language (SQL)
5.3 JDBC Configuration
5.4 Executing SQL Statements
5.5 Query Execution
5.6 Scrollable and Updatable Result Sets
5.7 Row Sets
5.8 Metadata
5.9 Transactions
5.10 Connection Management in Web and Enterprise Applications
5.11 Introduction to LDAP

86 1.4 Advanced Swing Concepts
1.4.1 Using Lists
1.4.2 Using Tables
1.4.3 Using Trees
1.4.4 Using Text Components
1.4.5 Using Progress Indicators
1.4.6 Using Component Organizers

87 Java XML Processing
3.1 Introduction to XML
3.2 Parsing an XML Document
3.3 Validating XML Documents
3.4 Locating Information with XPath
3.5 Using Namespaces
3.6 Streaming Parsers
3.7 Generating XML Documents
3.8 XSL Transformations

88 Java Beans
7.1 Why use Beans
7.2 The Bean Writing Process
7.3 Using Beans to build an Application
7.4 Naming Patterns for Bean Properties and Events
7.5 Bean Property Types
7.6 BeanInfo Classes
7.7 Property Editors
7.8 Customizers
7.9 JavaBean Persistence

89 why we always put the word new while creating object?

Here we are creating an object, instance of class so everytime it is mendatory to allocate memory space to that instance.

So by new key word we are allocating memory to that object

90 why printstream class static object inside System class

There is always one static object (out) inside System class because to connect console with the system class we need the out as well as println(), is a method of Printstream class, So to call that method from system class we need one  object of Printstream class inside System class and to instantiate that object at the starting of the program we make that object as static.

91 Why internationalization often named as i18n?

The term internationalization is abbreviated as i18n, because there are 18 letters between the first “i” and the last “n.”

92 Why does the InputStreamReader class has a read()

When end of stream is reached we always get the value -1. It is not possible with char. How do we know when stream is empty? We can not use EOF, EOL and so on.

93 What is Unicode characters?

Characters defined in Java are called Unicode characters.

94 what is the meaning of abstract?

The meaning of abstract is without body or you can say concept or idea without any instance.

In java terminology abstract is a keyword and we can define abstract method and classes.

If you want to know more about abstract classes and method

95 What is the main difference between Java platform and other platforms?

The Java platform differs from most other platforms in that it’s a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components: 1. The Java Virtual Machine (Java VM) 2. The Java Application Programming Interface (Java API)

96 What is the Java Virtual Machine (JVM) ?

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

97  What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

98 what is new in JSP?

JSP is a dynamic web page and it runs on server side

Jsp stands for “Java server page”.

JSP are built by SUN Microsystem.

JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy.

JSP simply place JAVA inside the HTML pages means it’s an embedded of html tag and jsp’s own tag.

99 What is difference between Hashmap and Hashtable?

There is almost no difference, since hashmap is Hash table based implementation of the Map interface (citation from API). The difference is that Hashtable is synchronized.

100 What is a platform?

A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000/XP, Linux, Solaris, and MacOS.

Also Read:




This site uses Akismet to reduce spam. Learn how your comment data is processed.