Showing posts with label Java interview. Show all posts
Showing posts with label Java interview. Show all posts

Wednesday, 28 September 2016

How to convert a binary to integer and vice versa ?


int decimalValue = Integer.parseInt(strNum, 2);    // Binary to Decimal
String binaryValue = Integer.toString(num, 2)   // Decimal to Binary






Use 8 for Octal and 16 for Hexadecimal numbers.

Monday, 2 May 2016

Can we execute the java program after calling System.exit(0) ?


Yes, By adding shutdown hook

void addShutdownHook(Thread hook) registers a new JVM shutdown hook.


When JVM shuts down ?

1. Normal exit
   * When the last non-daemon thread exits
   * When System.exit() invoked

2. Interrupted by User
    * When pressing ^C
    * System-wide event like, Shutdown, Reboot, Log off


Why Shutdown hook is useful ?

Shutdown hook can be used to :
  • Perform resource cleanup like, closing log file, sending some alerts
  • Save the state when JVM shuts down


Implementation of Shutdown hook
A shutdown hook is an initialized but un-started thread.

Once the shutdown sequence has begun, 
  • It can be stopped only by invoking the halt method, which forcibly terminates the virtual machine.
  • It is impossible to register a new shutdown hook or de-register a previously-registered hook, Otherwise it will cause an IllegalStateException.

Example
Defining Shutdown hook as a thread
class ShutDownHook extends Thread {
    public void run(){ 
        System.out.println("Shutdown hook tasks - Cleanup, Save state..."); 
    }
}

Inside main method, Add the shutdown hook / thread
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new ShutDownHook());


Example (same using anonymous class)
Runtime runtime = Runtime.getRuntime();

runtime.addShutdownHook(new Thread() {
    public void run(){ 
        System.out.println("Shutdown hook tasks - Cleanup, Save state..."); 
    }
});

Why ConcurrentHashMap doesn't allow null keys and null values ?


Reason #1. Purpose of null key
 If map.get(key) returns null, you can't detect whether the key explicitly maps to null or the key isn't mapped.

Reason #2. Ambiguities
In the ConcurrentHashMap implementation, map can be changed in between.

If it supports null key, in below code key k may be deleted in between get and containsKey calls and code will return null instead of KeyNotPresentException (expected)


if (map.containsKey(k)) {
     return map.get(k);
else {
     throw new KeyNotPresentException();
}

Saturday, 19 March 2016

How to increase the heap memory of the JVM ?


Use the JVM argument : 
-Xmx <maximum heap size>

Thread safety of components


Servlet / JSP : Not threadsafe
Servlet request attributes : Threadsafe

Hibernate session : Threadsafe
Hibernate Session factory : Not Threadsafe

* Threadsafe : Accessed by single thread at any moment without any malfunction

Interface vs. 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.

What is the purpose of garbage collection in Java, and when is it used ?


Garbage collection identifies and discards 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.

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 are pass by reference and passby value ?


Pass by reference means the passing the address itself rather than passing the value.
Pass by value means passing a copy of the value to be passed.

HashMap vs. Map


Map is Interface and Hashmap is class that implements that.

HashMap vs. HashTable


The HashMap class is roughly equivalent to Hashtable, except that it is not synchronized and permits nulls.
(HashMap allows null as key and value whereas Hashtable doesn't allow)


HashMap does not guarantee order of the elements will remain constant over time.

HashMap is not synchronized and Hashtable is synchronized.


Swing vs. AWT


AWT are heavy-weight componenets.

Swings are light-weight components.

So, Swing works faster than AWT.

Constructor vs. Method


A constructor is a member function of a class that is used to initialize objects of that class.
It has the same name as the class itself, has no return type, and is invoked using the new operator.

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.

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.

 

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

Visible in other packages, field is visible everywhere (Class must be public too)

private

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.

protected

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.

default

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.

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.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.


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 non static method. In other words, you can't change a static method into an instance method in a subclass.

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 if the main method is declared as private ?


The program compiles properly but at runtime it will give "Main method not public" message.

What if the static modifier is removed from the signature of the main method ?


Program compiles, but at runtime throws an error "NoSuchMethodError".