Thursday, August 16, 2012

Core Java Interview Questions

1) Is Java Compiled or Interpreted languages? Java is both, first it is compiled by Java Compiler into ByteCode(which is a form of machine language just for the JVM). Then JVM interprets this byte code and converts it into machine understandable language.

2) How JVM Memory is organized? Which are stored in which part of JVM Memory? Classes and Methods are stored in Perm Gen space. String internalized are also stored in Perm Gen space. This space is very limited compared to the HeapSize.

3) Difference between PrintWriter and Buffered Writer PrintWriter is used for small and dirty applications where we can display/write the messages on to the console. More over PrintWriter swallows the exceptions, later can read the exceptions by calling checkError() method.

4) Difference between BufferedWriter vs FileWriter BufferedWriter stores the data in the buffer and won't make those many calls to the operating system, it also lets us to specify the size of the buffer, if the buffer size is same/more than the streambuffer, the data is directly written into the file system.

5) Difference between FileWriter vs FileOutputStream Per java specification, use FileWriter to write the character data, and use FileOutputStream to write the raw byte data like images. Internally the FileWriter has to convert the character data into bytes which may reduce the performance. Also FileWriter can not properly handle raw data like images.

6) Convert Java Object JSON and Vice versa /** * */
 import org.apache.log4j.Logger;

 class Sample {
 public int getId() { return id; }

 public void setId(int id) { = id; }
 public int getAge() { return age; }

 @Override public String toString() { return "Sample [id=" + id + ", age=" + age + ", name=" + name + "]"; }
 public void setAge(int age) { this.age = age; }
 public String getName() { return name; }
 public void setName(String name) { = name; }
 private int id;
 private int age;
 private String name;

 public Sample(int id, int age, String name) { super(); = id; this.age = age; = name; } }

/** * @author kiran * */

public class JSONTest {

 private static final Logger log = Logger.getLogger(JSONTest.class.getName());
 /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub
 Sample s1 = new Sample(1,25,"Kiran");
 Sample s2 = new Sample(2,30,"Rams");
 Gson gson = new Gson();
 String json1 = gson.toJson(s1);
 String json2 = gson.toJson(s2);
 String jsonFilePath = "simple.json";
 File file = new File(jsonFilePath);
 try {
 FileWriter fw = new FileWriter(file);
 BufferedWriter bwr1 = new BufferedWriter(fw);
 bwr1.write(json2); //fw.write(json); // fw.close(); bwr1.close();"Saved the json file to the file simple.json");
 System.out.println("Json file outout : "+ json1+" "+ json2);"Now Reading the contents from JSON file simple.json");
 FileReader reader = new FileReader(file);
 BufferedReader br = new BufferedReader(reader);
 FileWriter outFile = new FileWriter("outfilejson.txt");
 int length = 0;
 BufferedWriter bw2 = new BufferedWriter(outFile);
 String bufLine = null;
 while((bufLine = br.readLine())!= null) {"Writing the line using the BufferedOutputStream : "+ bufLine); bw2.write(bufLine); } /* while((!=-1)
{  System.out.println("writing the char/int :"+ length); outFile.write((length)); } */ /* reader.close(); outFile.flush(); outFile.close();*/ bw2.close(); br.close(); }
 catch(Exception ex) {
 } } }

 7) Java Classloaders Java classloader is the key component of the Java Virtual Machine(JVM). A class file contains the byte code and references to other classes. Classloader identifies the byte code of the class and creates the instance of the java.lang.Class class, this makes this class available for the JVM for execution. JVM follows lazy loading of the classes,as it does not need to which classes get loaded during run time. Java classloaders have a hierarchy, when ever a class needs to be loaded, the resposibility is delegated to its parent classloader. Bootstrap class loader is at the top of the list. Bootstrap class loader loads the java2 core classes, Application classes are loaded by System Class loaders. Each class loader has a parent class loader except Bootstrap class loader. When the client requests a class, that class is loaded if it has been previously loaded by the jvm, jvm caches each class that is loaded previously. If the class is not loaded already the request is delegated to the parent class loader u pto Bootstrap classloader. If the parent class loader fails to load a class, then the current class loader tries to load this class. If the class is not found, then java.lang.ClassNotFoundException is thrown. We can write our own custom class loaders. With Custom Class loaders we can customize the behavior of the class loaders, like calling the parent class loaders when a class is requested. We can override this behaviour, example- all the web/application containers have their own implementation of the classloader, because of that only webapplication is able to use different versions of jarfiles/classes from what is contained in the web/application server. If the same class is loaded by two different class loaders and we try to compare them will cause ClassCastException. We need custom class loaders to control the JVM behavior of loading classes. Classloader Hierarchy - BootStrap ClassLoader->Ext ClassLoader-> App ClassLoader.

8) ClassNotFoundException vs NoClassDefFoundError ClassNotFoundException is a checked exception and NoClassDefFoundError is the error type. Both of these are related to the unavailability of the required class during runtime. ClassNotFoundException occurs when the JVM/classloader tries to load a class and the class definition is no longer found. If a class is loaded by two different class loaders and we try to access the class which is loaded by a different classloader, then we get ClassNotFoundException. ClassNotFoundException occurs bacause of the explicit loading of the class using , Class.forName(), ClassLoader.loadClass()... NoClassDefFoundError occurs when the class exists during compile and not found during run time, it could happen because the class is loaded by two different class loaders and proper class is not found.

9) When to use extends Class and When to use implements Interface Use Interface when there is a chance of several changes to your code. Use extends Class when there is some default implementation of a class that can be used by the child classes. Also to be able to extend other classes, go for implementing the interface that way You can extend the other classes.

10) Java Memory issues or Production issues DB --- Database indexes are not created properly. Stale data is not cleared in DB. Application ------------ Synchronization is not handled properly in the java application, should consider using synchronization when using non-threadsafe collections like Hash Map, otherwise you may get corrupted data or infinite loops. Use synchronization carefully, over usage may degrade the application performance. Handle proper communication with external systems like giving optimal time out for JMS, Web Service calls, also consider using Asynchronous communication instead of Synchronous communication wherever applicable. Handle Java Memory leaks properly, with Code reviews, static code analysis. Study the HeapDump and ThreadDump to study how the application is doing. Introduce Proper Chaching to the appliaction to improve performance. Excessive Caching can also lead to fill the Heap size and degrade the performance and may force many garbage collection cycles. Proper monitoring of the application using Heap/Thread dumps can also help to prevent the production issues.

11) Comparable vs Comparator in Java By implementing Comparable you can compare/sort the class objects using compareTo() method, this is done based on the natural ordering. It can be achieved using by Collectoions.sort(). Java Wrapper classes by default implement the Comparable interface, so their objects stored in collections can be sorted using Collections.sort(ArrayList), or Arrays.sort(). The sorting is based on the natural ordering of the elements. The objects that implement Comparable can be used as keys in TreeSet or SortedSet without specifying any Comparator. So if we want to sort the elements based on their natural ordering go for Comparable, otherwise if want to compare objects based on some other attributes use Comparator. Also when you are not the original author of the class, then you can not  make the class implement Comparable, then the only choice is implementing Comparator. By implementing Comparator you can compare/sort the class objects using compare() method, this is based on the order/implementation that we defined in the Comparator implementation.

12) Equals and HashCode in Java The general contract is that if two objects are equals as per the equals method,they should have the same hashcode value, and if two objects are different they may or may not the same hashcode. When ever you want to keep the objects in HashMap, you should override the equals method from Objects class, the default implementation of Object's equals method checks whether these two instances point to the same object or not i.e., same as compares them using ==. Whenever you overwrite the equals method, should overwrite hashcode as the java specification says that two equals objects should have equal hashcode value.

13) Singleton vs Static classes in Java Singleton makes sure that only one object of the class is created any time, where as static class can have multiple instances. Singleton can do lazy initialization of the instance where as the Static class can only do early initiliazation of the Object.

14) Java Memory Management - How the Objects are stored in Memory? How Java Memory is shared? When ever you create a new object something like Test t = new Test(), this object is stored in Heap. Whenever a String is created using a literal or intern that is created in the PermGen space. 15) Race condition in Multi threading This happens when two or more threads operating on an object and some of them can not see the changes done by the other threads. Typical example is Singleton creation, that is before creating the instance we check if the object is null, if two threads see that condition, they may create two singleton objects. Race condition can be prevented by making the block/method synchronized and ensure locking. Also it can be prevented by using Atomic variables like AtomicInteger, whose operations are atomic, where as prior to jdk1.5 anyvariable++ is not atomic, it is a combination of 3 atomic operations(read,update, and write).

16) How Thread join works Thread join lets one thread to make other thread to complete. If t is thread then t.join() lets the current thread to pause execution until thread t completes.

17) Liveness, Deadlock, Livelock, Starvation A concurrent application's ability to execute in a timely manner is called Liveness.The most common Liveness problems are DeadLock,LiveLock, and Starvation. DeadLock - DeadLoack is a situation where two are more threads are blocked forever waiting for action from other Threads. Starvation and Livelock are less likely to occur than a Deadlock. Starvation occurs if a greedy thread takes more time by invoking a synchronized method frequently and other threads spend most of the time waiting for the lock to be released. Livelock - A thread acts in response to other thread's actions, and the other thread also waits for a response from some other thread then it becomes a livelock. Just like Deadlock, here also threads can not make any progress, they are not blocked by each other but too busy responding to other thread to resume work.

18) Lock and ReentrantLock Lock and Reentrant lock are used in place of synchronization to solve concurrency issues. These are also based on synchronization but provides more control to the appliaction like tryLock() method backs out if the lock is not available immediately. LockInterruptibly method backs out of another thread sends interrupt before the lock is acquired.

19) Atomic Variables We can avoid unnecessary synchronization using Atomic Variables, the operations on these variables are atomic like AtomicInteger ai = new AtomicInteger(6); ai.incrementAndGet(), ai.decrementAndGet().

20) Executors Service Executors Service provides three implementations SingleThreadExecutor FixedThreadPool ScheduledThreadPool When you are done with the ThreadPoolExecutor, you must shut it down otherwise running thread will prevent the JVM from shutting down. shutdown() will not shutdown the ThreadPoolExecutor immediately, but will not accept any new thread connections, it will shut down when all the threads in this pool complete execution. If you want to shutdown the executor without worrying about the inprocess thread use shutdownNow(), this will not guarantee that existing threads will complete processing.

21) LinkedHashMap and ConcurrentHashMap LinkedHashMap is used in LRU cache implementations, it maintains the keys in the accessing order rather than in the inserint order. removeEldestEntry() method helps to remove the least recently used element from the Cache. ConcurrentHashMap is used in multithreaded applications where there are one/ a few writers and more Readers. ConcurrentHashMap doesn't synchronize read method, does only on write() method.


sarabjeet said...

i really like that you are giving information on core and advance java concepts. Being enrolled at i found your information very helpful indeed.thanks for it.

kanaparthi kiran said...

Thanks, I will come up with more info very soon.