- 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.
- Do I need to import java.lang package any time? Why?
No. It’s imported by default.
- 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).
- 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.
- Does importing a package imports the sub-packages as well?
- 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
newoperator cannot be deleted manually.
- 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.
- Does garbage collection guarantee that a program will not run out of memory?
- How can you force garbage collection?
You can’t force GC but you can announce it:
- What comes to mind when you hear about a young generation in Java?
Garbage collection. Read more here
- What comes to mind when someone mentions a shallow copy in Java?
- 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.
- Can an object’s finalize() method be invoked while it is reachable?
Yes, but not by the garbage collector.
- Can an unreachable object become reachable again?
Yes, if the finalize method stores it’s reference in a reachable object.
- 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.
- 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.
- 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.
- 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.
- What does memory consistency mean?
All threads should have the same image of the data at any time.
- What is a deadlock and how does it manifest?
A deadlock occurs when two threads are waiting each other and can’t proceed.
- 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.
- 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
doubleare atomic. Read and writes on all variables declared volatile are atomic.
- 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.
- Explain different ways of using a thread.
You can inherit from
Threadclass or implement the
- When a thread is created and started, what is its initial state?
- 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.
- 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.
- What method must be implemented by all Threads?
- 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.
- What’s the difference between the methods sleep() and wait()?
sleeptemporary ceases execution of the thread for a specified time.
waitceases execution until
notifyis called on the object or
notifyAllis called by another thread.
- How can i tell what state a thread is in?
- What methods is Java providing for thread communications?
notify, notifyAll, wait
- 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.
- 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.
- 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.
- When a thread blocks on I/O, what state does it enter?
- What’s new with the stop(), suspend() and resume() methods in JDK 1.2?
- What is the difference between yielding and sleeping?
While sleeping, the thread does not lose ownership of the monitor. Yielding loses ownership.
- What invokes a thread’s run() method?
It’s called by the JVM after the thread has been started.
- How can you restart a thread?
It’s not legal to start a thread more than once.
- What method is invoked to cause an object to begin executing as a separate thread?
- 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.
- 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.
- 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.
You can find here the operator table.
- What is the difference between the >> and >>> operators?
They perform bitwise signed and unsigned shifts, respectively.
- 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.
- 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.
- Which Java operators are right associative?
=, +=, -=, *=, /=, %=, <<=, >>=, >>>= &=, ^=, |=, ++ (prefix), -- (prefix), + (unary), - (unary), !, ~, (type), new
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.
- Is main/next/delete/exit/null/sizeof/virtual a keyword in Java?
None of these are Java keywords.
- 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
finallycode is executed even if the function returns a value in try/catch and can change the return value.
- What are the final fields and final methods?
- What is
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.
- What if I write
static public voidinstead of
public static void?
Program compiles, no error, the same thing.
- How is the
Transient modifier applies to members that are not stored during serialization.
- How is
Volatile fields can be modified asynchronously by multiple threads.
- How are
constkeywords used in Java?
Although these are actually keywords, they are not used and don’t serve any purpose.