Java Interview Questions Flashcards
What is ClassLoader in Java?
Loads classes at runtime.
Delegation - forwards request of class loading to parent class loader; only loads the class if parent can’t find.
Visibility - allow child class loader to see all classes loaded by parent ClassLoader.
Uniqueness - loads a class exactly once (achieved by delegation - ensures child ClassLoader doesn’t reload a class already loaded by a parent.
Bonus - NoClassDefFoundError, java.lang.ClassNotFoundException.
How would you check if a number is Even or Odd in Java?
- Modulus operator: if number%2 == 0 –> number is even, else –> number is odd
- Integer division: if ((number / 2) * 2) == 0 –> number is even, else –> number is odd
- Bitwise & operator (if number & 1 == 0 ) –> number is even, else –> number is odd
How does Java achieve platform independence?
via bytecode, and Java Virtual Machine (JVM). Java Complier (javac) creates a .class file, which is a collection of bytecode (NOT machine instructions), which a JVM can interpret.
JVM’s are platform dependent, but the bytecode interpreted by the JVM is not.
Explain the difference between ArrayList and HashSet
Array List is List implementation, HashSet is Set implementation.
List implementations are ordered based on order they were added, Set doesn’t guarantee an this order.
Lists allow you to access elements directly by index, Set doesn’t.
List allows duplicates, HashSet does not.
Array List backed by an array, HashSet backed by HashMap.
Both are non-syncronized collection classes; not meant for multi-threading -> but you can make them synchronized (Collections.synchronizedCollection())
Both have iterators to traverse the collection.
What is double checked locking in Singleton?
Singletons have just once instance throughout its lifetime. You need to ensure only once instance of the class gets created, and to provide a method to access that single instance( getInstance() for example)
In multi-threaded programs, you need to ensure only one instance gets created, even if multiple calls are made to the getInstance().
This is done with double-checked locking. Two checks are made to see if the instance member variable is initialized. The first is non-synchronized, the second is inside the synchronized block and only executes one time during the lifespan.
What is synchronized in java?
Synchronized methods prevent thread interference and memory consistency errors; if an object is visible to more than one thread, all reads / writes to that object are done through synchronized methods.
When do you use the volatile variable in Java?
To tell the JVM that a variable’s value can be modified by multiple threads, and ensure the JVM doesn’t cache the value.
When do you use a transient variable in Java?
When you want to make a variable non-serializable in a class which implements the Serializable interface. Serialize converts an object to byte stream to which can be deserialized into a copy of the object. Any variables you don’t want serialized should be be noted with “transient”.
private transient int myVariable
What’s the different between transient and volatile variables in Java?
Serialization vs Concurrency
Transient relates to serialization, indicating a variable shouldn’t be included when an object is serialized.
Volatile indicates an object can be modified by multiple threads in memory, therefor the JVM should not cache it’s value.
Difference between Serializable and Externalizable in Java?
Serializable is a marker interface - contains no methods / fields.
Externalizable interface contains two methods: writeExternal(), readExternal()
Serializable takes responsibility for serializing the suerclass state.
Externalizable requires you to implement the Serialization process.
Serializable doesn’t have a ton of options in regards to performance improvements - just… reduce the number of fields.
In Externalizable interfaces, you have full control over the Serialization process.
Maintenance - Serializable is prone to breaking when the structure of the class changes; Externalizable allows you to create your own custom binary format for your object.
What are marker interfaces in Java?
An interface with no fields or methods - essentially an empty interface. AKA Tag interface. They’re used to tell the compiler or JVM it needs to support some special operation on the class - If it sees Serializable, it performs some operation to support serialization of objects of that class.
For custom Marker Interfaces, Annotations tend to be better.
Examples - Serializable, Cloneable, and Remote.
Can you override a private method in Java?
No. Method overriding can only be done on derived classes, and private methods are not accessible in a subclass, you can not override them.
What is method overriding in Java?
Allows the creation of two methods with the same name and method signature on an object, and the actual method is called at run time depending on the type of object.
Can only override in a subclass.
Method name and signature must be the same in Super class and Sub class.
Accessibility of the overridden can not be reduced - if overridden method is public, overriding method can not be protected, private, package-private;
Accessibility can be increased by overriding method.
Cannot override private, static, or final methods.
What is the difference between Hashtable and hashMap?
HashMap and HashTable are similar - Hashmap is non-synchronized, and allows nulls as key and value.
What’s the difference between List and Set in Java?
List is ordered and allows duplicates. Set is unordered and doesn’t allow duplicates.
What’s the difference between ArrayList and Vector in Java?
Major points - ArrayList is non-synchronized and faster, while Vector is synchronized and slow.
Bother are ordered collections and allow duplicates, both can be referenced by index.
Vector is thread-safe and synchronized, while ArrayList is neither.
Vector is also a legacy class.
What’s the difference between Hashtable and ConcurrentHashMap?
Both are thread-safe, but the way they achieve their thread-safety differs. All methods in Hashtable are synchronized making them slow. ConcurrentHashMap is specifically designed for concurrent use. Scalable because of the stripped locking technique - it never locks the whole map.
How does ConcurrentHashMap achieve scalability?
Divides the map into segments, and only locking during write operations.
Which two methods will you override for an Object to be used as Key in HashMap?
Equals and hashcode
What’s the difference between wait and sleep in Java?
Sleep is meant for introducing pause, releasing CPU, and giving another thread an opportunity to execute.
Wait is used for inter-thread communication in java.
Wait must be called from a synchronized context (synchronized method or block), sleep can be called normally.
What’s the difference between notify and notifyAll in Java?
Notify notifies one random thread waiting for that lock while notifyAll informs all threads waiting for a monitor. Generally notifyAll is better unless you’re sure only one thread is waiting.
Why would you override hashcode and equals methods in java?
To be compliant with equals and hashcode contract, which is required if you are planning to store your object into collection classes (HashMap, ArrayList).
What’s the load factor of HashMap?
The load factor controls the resizing of the HashMap. When the load factor is .75, or 75% full, it triggers a resizing. The size of the bucket is doubled, and old entries are copied into a new bucket.
What’s the difference between an ArrayList and LinkedList?
Both are ordered, index-based, and allow duplicates.
ArrayLists are backed by an Array, LinkedLists are backed by linked list data structure. This results in performance differences in add, remove, contains, and iterator methods.
If you’re adding / removing from the start or end of a List, Linked list might see performance benefits… but usually ArrayLists are more practical.
Difference between CountDownLatch vs CyclicBarrier in Java multithreading?
CountDownLatch can not be reused once count reaches 0, CyclicBarrier can be reused by resetting the barrier.
When do you use Runnable vs Thread in Java?
Basically - always use Runnable, though occasional use cases for extends Thread exist.