Keywords and Concepts In Java

Q16) Can an abstract class have a static method?

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

Q17) Can an abstract class have a constructor?

Ans) Yes an abstract class have a default and parameterized constructors.

Q18) Why static methods cannot access non static variables or methods?

Ans) A static method cannot access non static variables or methods because static methods doesnt 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 intialized since the object is not created and this could result in an error.

Q19) What is difference between stringbuffer and stringbuilder?

Ans) 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 2)because StringBuilder is unsynchronized.
  • If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

Q20) 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?

Ans) 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.

Q21) What is the difference between final, finally and finalize() in Java?

Ans) final - A final variable act as constant, a final class is immutable and a final method cannot be ovrriden.

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.

Q22) How does Java allocate stack and heap memory?

Ans) 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 synchronisation through your code.

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

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

A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iterations from many sorts of algorithms.

All recursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server.

Q24) Can a private variable or method of a class can be accessed?

Ans) Yes its possible using reflection.

Q25) What is difference between static block and the init block?

Ans) 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.

public class LoadingBlocks {

  static{
    System.out.println("Inside static");
  }
  
  {
    System.out.println("Inside init");
  }
  public static void main(String args[]){
    new LoadingBlocks();
    new LoadingBlocks();
    new LoadingBlocks();
  }
}

Output:

Inside static
Inside init
Inside init
Inside init

Q26) Why inner class can access only final variable?

Ans) 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.

Q27) What is fully abstract class?

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

Q28) What is dynamic binding and static binding?

Ans) 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.

Q29) What is Java Reflection?

Ans)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.

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 can not 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.

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

Ans) 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 u set the object to null it will set 4567=null.