Java Interview Questions - Packages

05 Nov 2011 | By Mihai Roman | Comments | Tags java packages
  1. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
    None, you leave it to default package private.
  2. Do I need to import java.lang package any time? Why?
    No. It’s imported by default.
  3. Are the imports checked for validity at compile time? Will the code containing an import to a non-existing package compile?
    Yes, imports are checked for the semantic validity at compile time. The package must be available in the build path (folder or jar file).
  4. Can I import same package/class twice? Will the JVM load the package twice at runtime?
    You can import multiple times. The package will be loaded once.
  5. Does importing a package imports the sub-packages as well?
    No.

Java Interview Questions - Garbage Collection

04 Nov 2011 | By Mihai Roman | Comments | Tags java garbage collection
  1. What is the purpose of garbage collection in Java, and when is it used?
    Garbage collection is the automatic memory management used in Java to remove unused objects from memory. Objects allocated in heap, with the new operator cannot be deleted manually.
  2. How is garbage collection implemented in your JVM of choice?
    Read: http://java.sun.com/performance/reference/whitepapers/6_performance.html#2.2 , mark and sweep.
  3. Does garbage collection guarantee that a program will not run out of memory?
    No.
  4. How can you force garbage collection?
    You can’t force GC but you can announce it: System.gc()
  5. What comes to mind when you hear about a young generation in Java?
    Garbage collection. Read more here
  6. What comes to mind when someone mentions a shallow copy in Java?
    Object cloning.
  7. How can you minimize the need of garbage collection and make the memory use more effective?
    Object pooling, mutable objects, weak references, avoid memory leaks caused by circular references.
  8. Can an object’s finalize() method be invoked while it is reachable?
    Yes, but not by the garbage collector.
  9. Can an unreachable object become reachable again?
    Yes, if the finalize method stores it’s reference in a reachable object.

Java Interview Questions - Concurrency

03 Nov 2011 | By Mihai Roman | Comments | Tags java operators
  1. What is concurrency? Concurrency issues.
    Concurrency is the property of computer systems which allows multiple tasks to be executed in parallel. Tasks can be executed by preemptively time-sharing on a single chip, on multiple cores on the same chip, on different chips or by dividing the task in multiple smaller non-blocking events and queueing them for execution. Concurrency introduces two main issues: consistency and deadlocks.
  2. How is concurrency implemented in Java?
    In Java, concurrency is based on processes and threads. A Java program runs in it’s own process that can start multiple threads.
  3. What is synchronization and why is it important?
    Concurrent tasks may be executed to access shared resources. With synchronization we solve the consistency and interference problems.
  4. Describe synchronization in respect to multithreading.
    Threads communicate by sharing fields and the objects the reference fields refer to. While efficient, this causes thread interference and memory consistency errors that are solved through synchronization.
  5. What does memory consistency mean?
    All threads should have the same image of the data at any time.
  6. What is a deadlock and how does it manifest?
    A deadlock occurs when two threads are waiting each other and can’t proceed.
  7. Describe liveness in respect to concurrency.
    Liveness is the ability of an application to execute in a timely manner. Liveness problems are deadlocks, starvation and livelock. Deadlock occurs when threads wait for each other and can proceed. Starvation occurs when a thread cannot gain access to synchronized resources because of greedy threads. Livelock occurs when threads are too busy responding to each other and essentially can’t proceed, even if they are not blocked.
  8. What are atomic operations?
    An atomic operation is effectively happening at once, it cannot stop in the middle. Read and writes for reference types and all primitives except long and double are atomic. Read and writes on all variables declared volatile are atomic.
  9. Describe immutability. Give examples.
    Immutability refers to objects that cannot change their state after they have been constructed. Strings and wrapper classes are immutable in Java.
  10. Explain different ways of using a thread.
    You can inherit from Thread class or implement the Runnable interface.
  11. When a thread is created and started, what is its initial state?
    Ready state.
  12. What are synchronized methods and synchronized statements?
    Synchronized code can only be executed by one thread at a time. When a thread executes a synchronized method it acquires an intrinsic lock on the method’s object or Class object (in case the method is static). When a thread executes a synchronized statement, it acquired an intrinsic lock on a specified object.
  13. What is daemon thread and which method is used to create the daemon thread?
    Any Java thread can be a daemon thread. Daemon threads live to service other user threads. When the only threads running are daemon threads, the application exists. Use setDaemon(true) to make a thread daemon.
  14. What method must be implemented by all Threads?
    Run().
  15. Why would you use a synchronized block instead of synchronized method?
    Synchronized methods sets an intrinsic lock on the method’s object, effectively making it possible to execute only one method at a time. Use multiple blocks with multiple locks when they don’t generate interference. Also, only with blocks you can set an intrinsic lock on an external object.
  16. What’s the difference between the methods sleep() and wait()?
    sleep temporary ceases execution of the thread for a specified time. wait ceases execution until notify is called on the object or notifyAll is called by another thread.
  17. How can i tell what state a thread is in?
    getState().
  18. What methods is Java providing for thread communications?
    notify, notifyAll, wait
  19. What is the difference between notify() and notifyAll() methods?
    Notify wakes an arbitrary thread that is waiting on the object’s monitor. NotifyAll wakes all threads that wait on the object’s monitor. Both methods should be called by the owner of the object’s monitor. The awakened thread will proceed once the lock is relinquished on the object and has no privilege or disadvantage on gaining a lock on the object.
  20. What is Runnable interface ? Are there any other ways to make a multi-threaded Java application?
    You can implement the Runnable class and delegate running it to a class that extends the Thread class. You can also extend the Thread class and override the run() method.
  21. Why do threads block on I/O?
    In BLOCKED state, the thread waits for a monitor lock. This means that other threads can gain the lock while waiting for I/O.
  22. When a thread blocks on I/O, what state does it enter?
    BLOCKED.
  23. What’s new with the stop(), suspend() and resume() methods in JDK 1.2?
    Deprecated.
  24. What is the difference between yielding and sleeping?
    While sleeping, the thread does not lose ownership of the monitor. Yielding loses ownership.
  25. What invokes a thread’s run() method?
    It’s called by the JVM after the thread has been started.
  26. How can you restart a thread?
    It’s not legal to start a thread more than once.
  27. What method is invoked to cause an object to begin executing as a separate thread?
    start().
  28. Give examples of thread-safe collections. What are their drawbacks?
    Classes from java.util.concurrent package: BlockingQueue, ConcurrentMap, ConcurrentHashMap, ConcurrentNavigableMap, ConcurentSkipListMap. Other common synchronized collections: HashTable, Vector, as opposed to HashMap and ArrayList). Note also StringBuilder that is thread safe as opposed to StringBuffer.
  29. What is thread safe? How do you make sure an API is thread safe?
    Thread safe assumes that your API can be used in a multi-threaded application without adding an extra synchronization layer. Use immutable objects, synchronization and/or use atomic operations.
  30. What is the difference between preemptive scheduling and time slicing?
    Preemptive scheduling assumes that the running thread must get out of running state before executing another thread (e.g. blocking I/O, preempted by a higher priority thread, explicitly call a scheduling methods such as wait, sleep or yield). With time slicing, each thread is allowed to execute for a limited amount of time.

Java Interview Questions - Operators

02 Nov 2011 | By Mihai Roman | Comments | Tags java operators

You can find here the operator table.

  1. What is the difference between the >> and >>> operators?
    They perform bitwise signed and unsigned shifts, respectively.
  2. What is the difference between the Boolean & operator and the && operator?
    & is actually a bitwise operator that’s being applied on two boolean operands. The boolean operator will not evaluate the right operand if the left operand is already false.
  3. What are order of precedence and associativity, and how are they used?
    In complex expressions, the order in which the operations are performed is determined by the operator precedence. In expressions with operators with the same precedence order, the operations are performed in order from left to right or right to left, depending on the type of association.
  4. Which Java operators are right associative?
    =, +=, -=, *=, /=, %=, <<=, >>=, >>>= &=, ^=, |=, ++ (prefix), -- (prefix), + (unary), - (unary), !, ~, (type), new

Java Interview Questions - Keywords

01 Nov 2011 | By Mihai Roman | Comments | Tags java keywords

Complete list of Java keywords: abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, transient, try, void, volatile, while.

Reserved words for literal use: true, null, false.

  1. Is main/next/delete/exit/null/sizeof/virtual a keyword in Java?
    None of these are Java keywords.
  2. Final, finally, finalize in Java?*
    Final is a modifier that can be applied to classes, methods, fields, variables and parameters. Classes cannot be extended, methods cannot be overridden, fields cannot be assigned multiple times and must be instantiated in the constructors, variables can only be assigned once and parameters cannot be assigned. Finalize is the method called just before the object is garbage collected. Finally indicated the code block to be executed in connection with a try/catch block. The finally code is executed even if the function returns a value in try/catch and can change the return value.
  3. What are the final fields and final methods?
    See above.
  4. What is static in Java?
    The static keyword is used to declare fields, methods or inner classes. Objects hold a single copy of the fields no matter how many instance are there. Static member classes are actually top-level classes and not inner classes.
  5. What if I write static public void instead of public static void?
    Program compiles, no error, the same thing.
  6. How is the transient keyword used?
    Transient modifier applies to members that are not stored during serialization.
  7. How is volatile keyword used?
    Volatile fields can be modified asynchronously by multiple threads.
  8. How are goto and const keywords used in Java?
    Although these are actually keywords, they are not used and don’t serve any purpose.
1 2 3 4 5 6 7 8 9