Java Questions Flashcards
What does the static keyword mean, and where should it be used?
static can be used in 3 ways:
- static variables and methods are shared by the entire class, not a specific instance.
- static classes are inner classes that aren’t tied to their enclosing classes.
- static can be used around a block of code in a class to specify code that runs when the virtual machine is first started up, before instances of the class are created.
What does synchronized do?
synchronized says that a method has to hold the object’s lock to execute. If used around a block, like synchronized (obj) { … }, it will grab the lock of obj before executing that block.
What is type erasure?
Type erasure is a JVM phenomenon that means that the runtime has no knowledge of the types of generic objects, like List<integer> (the runtime sees all List objects as having the same type, List<object>).</object></integer>
What are the differences between Map, Hashtable, HashMap, TreeMap, ConcurrentHashMap, LinkedHashMap?
- Map is an interface for a key-value map
- HashMap is a Map that uses a hash table for its implementation
- Hashtable is a synchronized version of HashMap
- TreeMap uses a tree to implement a map
- ConcurrentHashMap allows for multiple threads to access it at the same time safely
- LinkedHashMap preserves the iteration order that things were inserted in (others don’t provide a fixed iteration order)
What are the differences between interfaces, abstract classes, classes, and instances?
- Interfaces are essentially a list of methods that implementations must possess, but have no code or member variables
- Abstract classes cannot be instantiated, but can contain variables, implemented methods, and unimplemented methods
- Classes contain variables and implemented methods only, and can be instantiated
- Instances (or objects) are specific examples of a particular class.
What are the basic interfaces of Java Collections Framework?
Collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface.
Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards.
List is an ordered collection and can contain duplicate elements. You can access any element from it’s index. List is more like array with dynamic length.
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.
Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap and ListIterator.
How do you prevent a class from being subclassed / overridden?
The “final” keyword