Saturday, December 19, 2015

133 Core Java Interview Questions Answers From Last 5 Years - The MEGA List



http://javarevisited.blogspot.kr/2015/10/133-java-interview-questions-answers-from-last-5-years.html

  • Multithreading, concurrency and thread basics
  • Date type conversion and fundamentals
  • Garbage Collection
  • Java Collections Framework
  • Array
  • String
  • GOF Design Patterns
  • SOLID design principles
  • Abstract class and interface
  • Java basics e.g. equals and hashcode
  • Generics and Enum
  • Java IO and NIO
  • Common Networking protocols
  • Data structure and algorithm in Java
  • Regular expressions
  • JVM internals
  • Java Best Practices
  • JDBC
  • Date, Time and Calendar
  • XML Processing in Java
  • JUnit
  • Programming

  • Multithreading, Concurrency and Thread basics Questions

    1) Can we make array volatile in Java?
    Yes, you can make an array volatile in Java but only the reference which is pointing to an array, not the whole array. What I mean, if one thread changes the reference variable to points to another array, that will provide volatile guarantee, but if multiple threads are changing individual array elements they won't be having happens before guarantee provided by volatile modifier.

    2) Can volatile make a non-atomic operation to atomic?
    One example I have seen is having a long field in your class. If you know that a long field is accessed by more than one thread e.g. a counter, a price filed or anything, you better make it volatile. Why? because reading to a long variable is not atomic in Java and done in two steps, If one thread is writing or updating long value, it's possible for another thread to see half value (fist 32-bit). While reading/writing a volatile long or double (64 bit) is atomic.


    6) How do you call wait() method? using if block or loop? Why? (answer)
    wait() method should always be called in loop because its possible that until thread gets CPU to start running again the condition might not hold, so its always better to check condition in loop before proceeding. Here is the standard idiom of using wait and notify method in Java:
    // The standard idiom for using the wait method
    synchronized (obj) {
       while (condition does not hold)
          obj.wait(); // (Releases lock, and reacquires on wakeup)
          ... // Perform action appropriate to condition
    }
    7)  What is false sharing in the context of multi-threading? 
    false sharing is one of the well-known performance issues on multi-core systems, where each process has its local cache. false sharing occurs when threads on different processor modify variables that reside on same cache line as shown in the following image:

    Java Interview questions for experienced programmers

    False sharing is very hard to detect because the thread may be accessing completely different global variables that happen to be relatively close together in memory. Like many concurrency issues, the primary way to avoid false sharing is careful code review and aligning your data structure with the size of a cache line.


    8) What is busy spin? Why should you use it?
    Busy spin is one of the technique to wait for events without releasing CPU. It's often done to avoid losing data in CPU cached which is lost if thread is paused and resumed in some other core. So, if you are working on low latency system where your order processing thread currently doesn't have any order, instead of sleeping or calling wait(), you can just loop and then again check the queue for new messages. It's only beneficial if you need to wait for very small amount of time e.g. in micro seconds or nano seconds. LMAX Disrupter framework, a high performance inter-thread messaging library has a BusySpinWaitStrategy which is based on this concept and uses busy spin loop for EventProcessors waiting on barrier.
    9) How do you take thread dump in Java?
    You can take a thread dump of Java application in Linux by using kill -3 PID, where PID is the process id of Java process. In Windows, you can press Ctrl + Break. This will instruct JVM to print thread dump in standard out or err and it could go to console or log file depending upon your application configuration. If you have used Tomcat then when

    10) is Swing thread-safe? (answer)
    No, Swing is not thread safe. You cannot update Swing components e.g. JTable, JList or JPanel from any thread, in fact they must be updated from GUI or AWT thread. That's why swings provides invokeAndWait() and invokeLater() method to request GUI update from any other threads. This methods put update request in AWT threads queue and can wait till update or return immediately for asynchronous update.
    11) What is thread local variable in Java? (answer)
    Thread-local variables are variables confined to thread, its like thread's own copy which is not shared between multiple thread. Java provides ThreadLocal class to support thread-local variables. It's one of the many way to achieve thread-safety. Though be careful while using thread local variable in manged environment e.g. with web servers where worker thread out live any application variable. Any thread local variable which is not removed once its work is done can potentially cause memory leak in Java application.
    12) Write wait-notify code for producer-consumer problem? (answer)
    Please see the answer for a code example. Just remember to call wait() and notify() method from synchronized block and test waiting condition on the loop instead of if block.
    13) Write code for thread-safe Singleton in Java? (answer)
    14) The difference between sleep and wait in Java? (answer)
    Though both are used to pause currently running thread, sleep() is actually meant for short pause because it doesn't release lock, while wait() is meant for conditional wait and that's why it release lock which can then be acquired by another thread to change the condition on which it is waiting.


    15) What is an immutable object? How do you create an Immutable object in Java? (answer)
    Immutable objects are those whose state cannot be changed once created. Any modification will result in a new object e.g. StringInteger, and other wrapper class. Please see the answer for step by step guide to creating Immutable class in Java.


    16) Can we create an Immutable object, which contains a mutable object?
    Yes its possible to create a Immutable object which may contain mutable object, you just need to be little bit careful not to share the reference of mutable component, instead you should return copy of it if you have to. Most common example is an Object which contain the reference of java.util.Date object.
    17) What is the right data type to represent a price in Java? (answer)
    BigDecimal if memory is not a concern and Performance is not critical, otherwise double with predefined precision.
    22) Which class contains clone method? Cloneable or Object? (answer)
    java.lang.Cloneable is marker interface and doesn't contain any method clone method is defined in the object class. It is also knowing that clone() is a native method means it's implemented in C or C++ or any other native language.


    23) Is ++ operator is thread-safe in Java? (answer)
     No its not a thread safe operator because its involve multiple instructions like reading a value, incriminating it and storing it back into memory which can be overlapped between multiple threads.
    24) Difference between a = a + b and a += b ? (answer)
    The += operator implicitly cast the result of addition into type of variable used to hold the result. When you add two integral variable e.g. variable of type byte, short, or int then they are first promoted to int and they addition happens. If result of addition is more than maximum value of a then a + b will give compile time error but a += b will be ok, as shown below
    byte a = 127;
    byte b = 127;
    b = a + b; // error : cannot convert from int to byte
    b += a; // ok
    25) Can I store a double value in a long variable without casting? (answer)
    No, you cannot store a double value into a long variable without casting because the range of double is more  that long and you we need to type cast.
    26) What will this return 3*0.1 == 0.3? true or false? (answer)
    false, because some floating point numbers can not be represented exactly.
    27) Which one will take more memory, an int or Integer? (answer)
    An Integer object will take more memory an Integer is the an object and it  store meta data overhead about the object and int is primitive type so its takes less space.


    public final class Integer extends Number implements Comparable<Integer> {
        private final int value;
    }
    28) Why is String Immutable in Java? (answer)
    The String is Immutable in java because java designer thought that string will be heavily used and making it immutable allow some optimization easy sharing same String object between multiple clients. See link for the more detailed answer.
    29) Can we use String in the switch case? (answer)
    yes from java 7 onward we can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch.
    28) Why is String Immutable in Java? (answer)
    The String is Immutable in java because java designer thought that string will be heavily used and making it immutable allow some optimization easy sharing same String object between multiple clients. See link for the more detailed answer.
    29) Can we use String in the switch case? (answer)
    yes from java 7 onward we can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch.
    30) What is constructor chaining in Java? (answer)
    When you call one constructor from other then its known as constructor chaining in Java. This happens when you have multiple, overloaded constructor in the class.

    JVM Internals and Garbage Collection Interview Questions

    31) What is the size of int in 64-bit JVM?
    The size of an int variable is constant in Java, it's always 32-bit irrespective of platform. Which means the size of primitive int is same in both 32-bit and 64-bit Java virtual machine.

    32) Difference between Serial and Parallel Garbage Collector? (answer)
    Even though both the serial and parallel collectors cause a stop-the-world pause during Garbage collection. Main difference between them is that a serial collector is a default copying collector which uses only one GC thread for garbage collection, while a parallel collector uses multiple GC threads for garbage collection.

    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