Saturday, June 14, 2014

Java67: Top 10 Tricky Java interview questions and Answers



Java67: Top 10 Tricky Java interview questions and Answers
What does the following Java program print? ==>0 ???
public class Test {
    public static void main(String[] args) {
        System.out.println(Math.min(Double.MIN_VALUE, 0.0d));
    }
}
Double.MIN_VALUE is the smallest positive non-zero value which can be represented by a Java double 
public static final double NaN = 0.0d / 0.0;
public static final double POSITIVE_INFINITY = 1.0 / 0.0;

What will happen if you put return statement or System.exit () on try or catch block ? Will finally block execute?
This question challenge that misconcept by putting return statement in try or catch block or calling System.exitfrom 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 ?
Anyway, you can not override private or static method in Java, if you create similar method with same return type and same method arguments in child class then it will hide the super class method, this is known as method hiding. Similarly you cannot override private method in sub class because it's not accessible there, what you do is create another private method with same name in child class. 

What does the the expression 1.0 / 0.0 will return? will it throw Exception? any compile time error?

it will not throwArithmeticExcpetion and return Double.INFINITY. Also note that the comparison x == Double.NaN always evaluates to false, even if x itself is a NaN. 

To test if x is a NaN, one should use the method call Double.isNaN(x) to check if given number is NaN or not. If you know SQL, this is very close to NULL there.
  550
    static public boolean isInfinite(double v) {
551
        return (v == ) || (v == );
552
    }
538
    static public boolean isNaN(double v) {
539
        return (v != v); //?
540
    }
http://stackoverflow.com/questions/8819738/why-does-double-nan-double-nan-return-false
NaN means Not a Number. What is not a number? Anything. You can have anything in one side and anything in the other side, so nothing guarantees that both are equals. NaN is calculated with Double.longBitsToDouble(0x7ff8000000000000L) and as you can see in the documentation oflongBitsToDouble:
If the argument is any value in the range 0x7ff0000000000001L through0x7fffffffffffffffL or in the range 0xfff0000000000001L through0xffffffffffffffffL, the result is a NaN.
Does Java support multiple inheritance ?
 because Java does support multiple inheritance of Type by allowing interface to extend other interfaces, what Java doesn't support is multiple inheritance of implementation. This distinction also get blur because of default method of Java 8, which now provides Java, multiple inheritance of behaviour as well. 

public class Test {
    public static void main(String[] args) throws Exception {
        char[] chars = new char[] {'\u0097'};
        String str = new String(chars);
        byte[] bytes = str.getBytes();
        System.out.println(Arrays.toString(bytes));
    }
}
it is reasonable to guess that the str.getBytes() call will return a byte array that contains one element with a value of -105 ((byte) 0x97). However, that's not what the program prints and that's why this question is tricky. As a matter of fact, the output of the program is operating system and locale dependent. On a Windows XP with the US locale, the above program prints [63], if you run this program on Linux or Solaris, you will get different values.

When we call str.getBytes() without specifying a character encoding scheme, the JVM uses the default character encoding of platform to do the job. The default encoding scheme is operating system and locale dependent. On Linux, it is UTF-8 and on Windows with a US locale, the default encoding is Cp1252. This explains the output we get from runing this program on Windows machines with a US locale. No matter which character encoding scheme is used, Java will always translate Unicode characters not recognized by the encoding to 63, which represents the character U+003F (the question mark, ?) in all encodings.

If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?
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; // use Long.compare, notice null check
}
If id becomes negative than subtraction may overflow and produce incorrect result. 

How do you ensure that N thread can access N resources without deadlock
Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. 

What is difference between CyclicBarrier and CountDownLatch in Java
Main difference between both of them is that you can reuseCyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java. 

What is difference between StringBuffer and StringBuilder in Java ?
StringBuffer methods e.g. length()capacity() or append() aresynchronized while corresponding methods in StringBuilder are not-synchronized. Because of this fundamental difference, concatenation of String using StringBuilder is faster than StringBuffer. Actually its considered bad practice to use StringBuffer any more, because in almost 99% scenario, you perform string concatenation on same thread.

Can you access non static variable in static context?
No you can not access non-static variable from static context in Java. If you try, it will give compile time error. This is actually a common problem beginners in Java face, when they try to access instance variable inside main method.

  1. When Singleton doesn't remain Singleton in Java?
  2. is it possible to load a class by two ClassLoader?
  3. is it possible for equals() to return false, even if contents of two Objects are same?
  4. Why compareTo() should be consistent to equals() method in Java?
  5. When do Double and BigDecimal give different answers for equals() and compareTo() == 0. 
  6. How does "has before" apply to volatile work?
  7. Why is 0.1 * 3 != 0.3,
  8. Why is (Integer) 1 == (Integer) 1 but (Integer) 222 != (Integer) 222 and which command arguments change this.
  9. What happens when exception is thrown by a Thread?
  10. Difference between notify() and notifyAll() call?
Read full article from Java67: Top 10 Tricky Java interview questions and Answers

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts