Key Concepts Interview Questions

Why is main() method static?

To access a static method class object is not needed. The method can be accessed directly with the help of ClassName. So when a program is started the jvm search for the class with main method and calls it without creating an object of the class.

What is difference between abstract class and interface?
  • A class is called abstract when it contains at least one abstract method. It can also contain n numbers of concrete method.Interface can contain only abstract (non implemented) methods.

  • The abstract class can have public, private, protect or default variables and also constants. In interface the variable is by default public final. In nutshell the interface doesn't have any variables it only has constants.

  • A class can extend only one abstract class but a class can implement multiple interfaces.

  • If an interface is implemented its compulsory to implement all of its methods but if an abstract class is extended its not compulsory to implement all methods.

  • The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.

What is the difference between static and instance methods?
  • Instance method belongs to the instance of a class therefore it requires an instance before it can be invoked, whereas static method belongs to the class itself and not to any class instance so it doesn’t need an instance to be invoked.

  • Instance methods use dynamic (late) binding, whereas static methods use static (early) binding. When the JVM invokes a class instance method, it selects the method to invoke based on the type of the object reference, which is always known at run-time.

  • On the other hand, when the JVM invokes a static method, it selects the method to invoke based on the actual class of the object, which may only be known at compile time.

Can static block throw exception?
  • Yes, static block can throw only Runtime exception or can use a try-catch block to catch checked exception.

  • Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught, logged and application can exit.

  • If System.exit() is not done, then application may continue and next time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader.

What are the different types of references in java?

Java has a more expressive system of reference than most other garbage-collected programming languages, which allows for special behavior for garbage collection. A normal reference in Java is known as a strong reference. The java.lang.ref package defines three other types of references— soft, weak and phantom references. Each type of reference is designed for a specific use.

  • A SoftReference can be used to implement a cache. An object that is not reachable by a strong reference (that is, not strongly reachable) but is referenced by a soft reference is called softly reachable. A softly reachable object may be garbage collected at the discretion of the garbage collector. This generally means that softly reachable objects will only be garbage collected when free memory is low, but again, it is at the discretion of the garbage collector. Semantically, a soft reference means "keep this object unless the memory is needed."

  • A WeakReference is used to implement weak maps. An object that is not strongly or softly reachable, but is referenced by a weak reference is called weakly reachable. A weakly reachable object will be garbage collected during the next collection cycle. This behavior is used in the class java.util.WeakHashMap. A weak map allows the programmer to put key/value pairs in the map and not worry about the objects taking up memory when the key is no longer reachable.

  • A PhantomReference is used to reference objects that have been marked for garbage collection and have been finalized, but have not yet been reclaimed. An object that is not strongly, softly or weakly reachable, but is referenced by a phantom reference is called phantom reachable. This allows for more flexible cleanup than is possible with the finalization mechanism alone. Semantically, a phantom reference means "this object is no longer needed and has been finalized in preparation for being collected."

Learn more about Java Programming

Does java support multiple interitance? Why?

Java doesn't support multiple inheritance but it provide a way through which it can enact it. Consider the scenario is C++

The above problem in java is taken care with the use of interfaces. In Java similar problem would look like:

How to change the heap size of a JVM?

The old generation's default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively : java -Xms -Xmx program

For example : java -Xms64m -Xmx128m program

What is memory leak?

A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesn't get garbage collected.

What is difference between instanceof and isInstance(Object obj)?

Differences are as follows :

  1. instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class.

  2. instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.

Java supports pass by value or pass by reference?

Java supports only pass by value. The arguments passed as a parameter to a method is mainly primitive data types or objects. For the data type the actual value is passed.

Java passes the references by value just like any other parameter. The pointer to the object is passed as value. Thus, method manipulation will alter the objects, since the references point to the original object but will not initialize the new object.

Consider the example : The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.

What is the difference between equals() and ==?

== operator is used to compare the references of the objects. public boolean equals(Object o) is the method provided by the Object class.

The default implementation uses == operator to compare two objects. But since the method can be overridden like for String class. equals() method can be used to compare the values of two objects.

Can an abstract class have a static method?

Yes an abstract class has a static method and it can be accessed by any other class (even not a concrete class).

When an obj is passed through a function, one can set the properties but cannot set a new memory location?

It is because when u pass an object the address value is passed and stored in some new address like if address 1234 is passed, it is stored in 4567 location.

So if u change in the value of an object it will take the address from 4567 and do 1234.setXXX(). If you set the object to null it will set 4567 = null.

Why static methods cannot access non static variables or methods?

A static method cannot access non static variables or methods because static methods doesn't need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will no be initialized since the object is not created and this could result in an error.

What is difference between stringbuffer and stringbuilder?

The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Criteria to choose among StringBuffer and StringBuilder :

  • If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.

  • If your text can change and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

Consider a scenario in which the admin want to sure that if some one has written System.exit() at some part of application then before system shutdown all the resources should be released. How is it possible?

This is possible using Runtime.getRuntime().addShutdownHook(Thread hook).

Straight from Java Spec :

This method registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events :

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked.

  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.

When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method. Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine.

What is the difference between final, finally and finalize() in Java?
  • final - declared as constant. A final variable act as constant, a final class is immutable and a final method cannot be overridden.

  • finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc.

  • finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc. because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

How does Java allocate stack and heap memory?
  • Each time an object is created in Java it goes into the part of memory known as heap.

  • The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack.

  • When a method is invoked and stack pointer is decremented when a method call is completed. In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space.

  • The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronization through your code.

Explain re-entrant, recursive and idempotent methods/functions?

A method in stack is re-entrant allowing multiple concurrent invocations that do not interfere with each other.

What is difference between static block and the init block?

The static block is loaded when the class is loaded by the JVM for the 1st time only whereas init {} block is loaded every time class is loaded. Also first the static block is loaded then the init block.

Why inner class can access only final variable?
  • Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns.

  • When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't final then the copy of the variable in the method could change, while the copy in the local class didn't, so they'd be out of synch.

  • Anonymous inner classes require final variables because of the way they are implemented in Java. An anonymous inner class (AIC) uses local variables by creating a private instance field which holds a copy of the value of the local variable.

  • The inner class isn't actually using the local variable, but a copy. It should be fairly obvious at this point that a "Bad Thing" can happen if either the original value or the copied value changes; there will be some unexpected data synchronization problems.

  • In order to prevent this kind of problem, Java requires you to mark local variables that will be used by the AIC as final (i.e., unchangeable). This guarantees that the inner class' copies of local variables will always match the actual values.

What is fully abstract class?

An abstract class which has all methods as abstract and all fields are public static final.

What is dynamic binding and static binding?

Method invocation The Java programming language provides two basic kinds of methods: instance methods and class (or static) methods.

The differences are :

  1. Instance methods require an instance before they can be invoked, whereas class methods do not.

  2. Instance methods use dynamic (late) binding, whereas class methods use static (early) binding.

When the Java virtual machine invokes a class method, it selects the method to invoke based on the type of the object reference, which is always known at compile-time.

On the other hand, when the virtual machine invokes an instance method, it selects the method to invoke based on the actual class of the object, which may only be known at run time.

What is Java Reflection?

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

A Drawbacks of Reflection :

    Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

  • Performance Overhead : Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

  • Security Restrictions : Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.

  • Exposure of Internals : Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

Can an abstract class have a constructor?

Yes an abstract class has a default and parameterized constructors.

Learn more about Java Concepts in our Video Tutorial