Tuesday 31 March 2015

Top Most Frequently Asked Interview Core Java Interview Questions And Answers

 Core Java Interview Questions And Answers:


 1. What is the most important feature of Java?
Java is a platform independent language.

     2. What is JVM ? Why is Java called the “Platform Independent                Programming Language” ?

     A Java virtual machine (JVM) is a process virtual machine that can execute        Java bytecode. Each Java source file is compiled into a bytecode file, which is      executed by the JVM. Java was designed to allow application programs to be      built that could be run on any platform, without having to be rewritten or          recompiled by the programmer for each separate platform. A Java virtual          machine makes this possible, because it is aware of the specific instruction        lengths and other particularities of the underlying hardware platform.
     3. What do you mean by platform independence?
A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.

4. What is difference between JDK,JRE and JVM?

JVM

JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (so JVM is plateform dependent).

JRE

JRE stands for Java Runtime Environment. It is the implementation of JVM and physically exists.

JDK

JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.

5. How many types of memory areas are allocated by JVM?

Many types:
  1. Class(Method) Area
  2. Heap
  3. Stack
  4. Program Counter Register
  5. Native Method Stack

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

The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It has two components:
  1. Runtime Environment
  2. API(Application Programming Interface)
7. What gives Java its 'write once and run anywhere' nature?

The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.

8. Is Empty .java file name a valid source file name?

Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname Let's take a simple example:
  1. //save by .java only  
  2. class A{  
  3. public static void main(String args[]){  
  4. System.out.println("Hello java");  
  5. }  
  6. }  
  7. //compile by javac .java  
  8. //run by     java A  

compile it by javac .java

run it by java A

9. If I don't provide any arguments on the command line, then the String array of Main method will be empty or null?

It is empty. But not null.

10. What if I write static public void instead of public static void?

Program compiles and runs properly.

11. What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

12. What is classloader?

The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

13. Can you override private or static method in Java ?

Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java.  Anyway, you can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding.

14. What is immutable object? Can you write immutable object?

Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

15. What is the difference between creating String as new() and literal?

When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.


String s = new String("Test");

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.


16. How do you handle error condition  while writing stored procedure or accessing stored procedure from java?

This is one of the tough Java interview question and its open for all, my friend didn't know the answer so he didn't mind telling me. my take is that stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

17. Can you write critical section code for singleton?
This core Java question is followup of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe.

18. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)

19. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

20. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.

21.  What do you understand by thread-safety ? Why is it required ? And finally, how to achieve thread-safety in Java Applications ? 


Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In a way, it describes what behaviors are legal in multi-threaded code. It determines when a Thread can reliably see writes to variables made by other threads. It defines semantics for volatile, final & synchronized, that makes guarantee of visibility of memory operations across the Threads.


Let's first discuss about Memory Barrier which are the base for our further discussions. There are two type of memory barrier instructions in JMM - read barriers and write barrier.

A read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory, so that changes made by other threads becomes visible to the current Thread.
A write barrier flushes out the contents of the processor's local memory to the main memory, so that changes made by the current Thread becomes visible to the other threads.

22. What is difference between Executor.submit() and Executer.execute() method ?There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

23. What is the difference between factory and abstract factory           pattern?Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.



24.JMM semantics for synchronized

When a thread acquires monitor of an object, by entering into a synchronized block of code, it performs a read barrier (invalidates the local memory and reads from the heap instead). Similarly exiting from a synchronized block as part of releasing the associated monitor, it performs a write barrier (flushes changes to the main memory)
Thus modifications to a shared state using synchronized block by one Thread, is guaranteed to be visible to subsequent synchronized reads by other threads. This guarantee is provided by JMM in presence of synchronized code block.



25.  What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?

This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept by putting return statement in try or catch block or calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.

26. If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?
One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception. 

27. What is the issue with following implementation of compareTo() method in Java

public int compareTo(Object o){
   Employee emp = (Employee) emp;
   return this.id - o.id;
}


28. How do you ensure that N thread can access N resources without deadlock?

If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java question can be tricky even for experienced and senior programmer, who are not really exposed to deadlock and race conditions. Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. 

29. What is difference between CyclicBarrier and CountDownLatch in Java?

Relatively newer Java tricky question, only been introduced form Java 5. Main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.

30. Explain different way of using thread?
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.
                                                                                                     31. What are the Data Types supported by Java ? What is Autoboxing and Unboxing ?
 The eight primitive data types supported by the Java programming language are:
  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char

32. What does the “static” keyword mean ? Can you override private or static method in Java ? 

The static keyword denotes that a member variable or method can be accessed, without requiring an instantiation of the class to which it belongs. A user cannot override static methods in Java, because method overriding is based upon dynamic binding at runtime and static methods are statically binded at compile time. A static method is not associated with any instance of a class so the concept is not applicable.

33. Can you access non static variable in static context ? 

A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance.


34. What is Function Overriding and Overloading in Java ? 

Method overloading in Java occurs when two or more methods in the same class have the exact same name, but different parameters. On the other hand, method overriding is defined as the case when a child class redefines the same method as a parent class. 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.

35. What is a Constructor, Constructor Overloading in Java and Copy-Constructor ?

 A constructor gets invoked when a new object is created. Every class has a constructor. In case the programmer does not provide a constructor for a class, the Java compiler (Javac) creates a default constructor for that class. The constructor overloading is similar to method overloading in Java. Different constructors can be created for a single class. Each constructor must have its own unique parameter list. Finally, Java does support copy constructors like C++, but the difference lies in the fact that Java doesn’t create a default copy constructor if you don’t write your own.

36. What are pass by reference and pass by value ?

 When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.

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

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

39. What is the difference between an Interface and an Abstract class ?

 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.
40. Does Java support multiple inheritance ?

 No, Java does not support multiple inheritance. Each class is able to extend only on one class, but is able to implement more than one interfaces.

41. What is the use of Join method?

The join method allows one thread to wait for the completion of another. If " t " is a Thread object whose thread is currently executing,
t.join();
Causes the current thread to pause execution until t’s thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.
Like sleep, join responds to an interrupt by exiting with an InterruptedException.

42.  Just-In-Time(JIT) compiler?

It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

43. What is the use of volatile in Java?

Threads are allowed to hold the values of variables in local memory (e.g. in a machine register).
If a variable is marked as volatile, every time when the variable is used, it must be read from the main memory, similarly every time the variable is written, the value must be stored in main memory.

44. How static variable work in java?

  • Static code is loaded before the class is instantiated and stays in memory until the JVM exits as opposed to instance variable which are loaded and unloaded which is called “Dynamic” code.
  • Each class has one copy of each of its static members in memory.
  • Each instance of the class has access to that single static memory location.
  • The single member is same for every instance.
  • Static member does not have access to instance members.

45. What is Contract between hashcode and equal method?

The Java super class java.lang.Object has two very important methods defined.
public boolean equals(Object obj)
public int hashCode()
It is very important to understand the contract between equals and hashcode. The general contract of hashCode is
Whenever hashCode method is invoked on the same object more than once during the execution of the application, the hashCode method consistently return same integer value.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object)method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

46. What is Hash Code collision?

The idea of hashing is to store an element into array at a position index computed as below.
  • obtain element_hash_code of the element by processing the element's data and generating an integer value.
  • use a simple mod operation to map into the array's range: index = hash(element) = abs(element_hash_code % array_capacity)
The hashcode collision occurs when the index calculated by hash function results same for two or more elements.

47. What is Re-factoring in Software?

Re-factoring is the continuous process of changing a software system in such a way that it does not alter the external behavior of the code yet improves internal structure of the code.
It is advisory that developer should have habit to apply re-factoring as continuous process to improve the code structure.
Re-factoring helps to keep the code clone and minimize the chances of introducing bug.
Re-factoring made the internal structure of the software, easier to understand and cheaper to enhance the functionality of the software.
Note: There are different types of Re-factoring, to know more about re-factoring read re-factoring, improvement of existing code by Martin Fowler.

48. Why Singleton pattern is better than creating Singleton class with static instance?

With Singleton pattern you can create the object when you required, but static instance get created at the time of class loading i.e. we can lazily instantiate object with singleton pattern.
With Singleton pattern we can use inheritance, for example when we require default behavior of the Singleton class then we can use that, with static you cannot.

49. What is the Difference between synchronized and synchronized block?

In case of a Synchronized method a thread may need to have the lock for a longer time as compared to the synchronized block.
Another difference between synchronized method and block is that we don’t specify the particular object whose monitor is required to be obtained by thread for entering a synchronized method, whereas we can specify the particular object in case of synchronized block.

50. What is the difference between final, finally and finalize()?

final
- It is a modifier which can be applied to a class, method or variable.
- It is not possible to inherit the final class, override the final method and change the final variable.

finally
- It is an exception handling code section.
- It gets executed whether an exception is raised or not by the try block code segment.

finalize()
- It is a method of Object class.
- It is executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.


No comments:

Post a Comment