Thursday, February 21, 2013

Is Java Pass by Reference or Pass by Value?

The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java. The difficult thing can be to understand that Java passes "objects as references" passed by value. This can certainly get confusing and I would recommend reading this article from an expert:

Wednesday, February 20, 2013

Top 10 Tricky Java interview questions and Answers

Tricky Java interview questions are those question which has some surprise element on it and if you answer tricky Java question with common sense, you are likely to fail because they are tricky, they require something special to know. Most of the tricky Java questions comes from method overloading and overriding, Checked and Unchecked Exception and subtle Java programming details like Integer overflow. Most important thing to answer tricky Java question is attitude and analytical thinking , which helps even if you don't know the answer. Anyway in this Java article we will see 10 Java questions which is real tricky and requires more than average knowledge of Java programming language to answer. As per my experience there are always one or two tricky or tough Java interview question on any core Java or J2EE interviews, so its good to prepare tricky questions from Java in advance. 10 Tricky Java interview question - Answered Tricky Java interview question and answer for experienced programmerHere is my list of 10 tricky Java interview questions, Though I have prepared and shared lot of difficult core java interview question and answers, But I have chosen them as Top 10 tricky questions because you can not guess answers of this tricky java questions easily, you need some subtle details of Java programming language to answer these questions.  




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.

 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. See Can you override private method in Java or more details.


 Does Java support multiple inheritance ? This is the trickiest question in Java, if C++ can support direct multiple inheritance than why not Java is the argument Interviewer often give. See Why multiple inheritance is not supported in Java to answer this tricky Java question.  


What will happen if we put a key object in a HashMap which is already there ? This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys. See How HashMap works in Java for more tricky Java questions from HashMap.

 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. See Rules of method overriding in Java for more details.  



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; } where id is an integer number ? Well three is nothing wrong in this Java question until you guarantee that id is always positive. This Java question becomes tricky when you can not guaranteed id is positive or negative. If id is negative than subtraction may overflow and produce incorrect result. See How to override compareTo method in Java for complete answer of this Java tricky question for experienced programmer.


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. See how to avoid deadlock in Java for a sample code example.  


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.



What is difference between StringBuffer and StringBuilder in Java ? Classic Java questions which some people thing tricky and some consider very easy. StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for more differences.





 Can you access non static variable in static context? Another tricky Java question from Java fundamentals. No you can not access static variable in non static context in Java. Read why you can not access non-static variable from static method to learn more about this tricky Java questions. This was my list of 10 most common tricky question in Java . It's not a bad idea to prepare tricky Java question before appearing for any core Java or J2EE interview. One or two open ended or tricky question is quite common in Java interviews.

Why String is immutable or final in Java

This is one of the most popular interview question on String in Java which starts with discussion of What is immutable object in Java , what are the benefits of immutable object , why do you use it and which scenarios do you use it. This is some time also asked as "Why String is final in Java" . It can also come once interviewee answers some preliminarily strings questions e.g. What is String pool in Java , What is the difference between String and StringBuffer , What does intern method do in String, What is special about String Class in Java, Why String is popular HashMap key in Java, Does String is thread-safe in Java, How to compare two String in Java , How SubString works in Java and What is the difference between StringBuffer vs StringBuilder Why char array is preferred over String for passwords Though there could be many possible answer for this question and only designer of String class can answer this , I think below two does make sense 1)Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say String A = "Test" String B = "Test" Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable. 2)String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes. In case if String is not immutable , this would lead serious security threat , I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file. This is some time asked as Why Char array is better than String for Storing password in Java in interviews as well. 3)Since String is immutable it can safely shared between many threads ,which is very important for multi threaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of. 4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation. 5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter" I believe there could be some more very convincing reasons also , Please post those reasons as comments and I will include those on this post. I think above reason holds good for another java interview questions "Why String is final in Java" also to be immutable you have to be final so that your subclass doesn't break immutability. what do you guys think ? Read more: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz2LVtUBqxt

Difference between JIT and JVM in Java - Interview Question

Main difference between JIT and JVM is that, JIT is part of JVM itself and used to improve performance of JVM. JIT stands for Just In time compilation and JVM stands for Java Virtual Machine. JVM is a virtual machine used in Java programming platform to execute or run Java programs. Main advantage of JVM is that, it makes Java platform independent by executing byte codes. Java source code is compiled into class files, which contains byte code. These byte codes are then executed by JVM. Now here comes JIT. Since execution of byte code is slower than execution of machine language code, because JVM first needs to translate byte code into machine language code. JIT helps JVM here by compiling currently executing byte code into machine language. JIT also offers caching of compiled code which result in improved performance of JVM. by the way difference between JVM and JIT is also a good Java interview question to ask. Well, this is just a simple explanation, JIT is lot more complex than this. There are sophisticated algorithm which helps JIT to pick most executed code for compiling into machine code. Earlier we have seen difference between JRE and JDK and in this post we will understand difference between JVM and JIT. Let's see next section for more difference between JIT vs JVM. JVM vs JIT Difference between JVM and JIT in Java programming Here are couple of more differences between JVM and JIT in Java programing platform : 1) Main difference between JVM and JIT is there purpose, main goal of JVM is to provide platform independence while objective of JIT is to improve performance of JVM, by compiling more code into machine language. Just keep in mind that this compilation also takes time, so translating all code into native code is not worth doing. That's why JIT mostly compile frequently used code into native code. 3) Another difference between JIT and JVM is that, JIT is part of JVM. One example of JIT is Oracle's Hotspot JIT which comes with Hotspot JVM. 2) At last, JVM is older concept than JIT. JIT actually get invented to improve performance of JVM. That's all on difference between JVM and JIT in Java. As I said, JIT is part of JVM and used to improve JVM performance by dynamically compiling or translating Java byte codes into native machine language code during execution time.