Java Interview Questions Flashcards

1
Q

What is ClassLoader in Java?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How would you check if a number is Even or Odd in Java?

A
  1. Modulus operator: if number%2 == 0 –> number is even, else –> number is odd
  2. Integer division: if ((number / 2) * 2) == 0 –> number is even, else –> number is odd
  3. Bitwise & operator (if number & 1 == 0 ) –> number is even, else –> number is odd
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does Java achieve platform independence?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain the difference between ArrayList and HashSet

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is double checked locking in Singleton?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is synchronized in java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

When do you use the volatile variable in Java?

A

To tell the JVM that a variable’s value can be modified by multiple threads, and ensure the JVM doesn’t cache the value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

When do you use a transient variable in Java?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What’s the different between transient and volatile variables in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Difference between Serializable and Externalizable in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are marker interfaces in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Can you override a private method in Java?

A

No. Method overriding can only be done on derived classes, and private methods are not accessible in a subclass, you can not override them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is method overriding in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the difference between Hashtable and hashMap?

A

HashMap and HashTable are similar - Hashmap is non-synchronized, and allows nulls as key and value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What’s the difference between List and Set in Java?

A

List is ordered and allows duplicates. Set is unordered and doesn’t allow duplicates.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What’s the difference between ArrayList and Vector in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What’s the difference between Hashtable and ConcurrentHashMap?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How does ConcurrentHashMap achieve scalability?

A

Divides the map into segments, and only locking during write operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Which two methods will you override for an Object to be used as Key in HashMap?

A

Equals and hashcode

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What’s the difference between wait and sleep in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What’s the difference between notify and notifyAll in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Why would you override hashcode and equals methods in java?

A

To be compliant with equals and hashcode contract, which is required if you are planning to store your object into collection classes (HashMap, ArrayList).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What’s the load factor of HashMap?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What’s the difference between an ArrayList and LinkedList?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Difference between CountDownLatch vs CyclicBarrier in Java multithreading?

A

CountDownLatch can not be reused once count reaches 0, CyclicBarrier can be reused by resetting the barrier.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

When do you use Runnable vs Thread in Java?

A

Basically - always use Runnable, though occasional use cases for extends Thread exist.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is the meaning of Enum being type-safe in Java?

A

You cannot assign an instance of a differrent Enum type to an Enum variable.

28
Q

What’s the difference between the PATH and Classpath in Java?

A

Path is used by the OS while Classpath is used by the JVM to locate binary/class files.

29
Q

What’s the difference between method overloading and overriding in Java.

A

Overriding happens at a subclass level, overriding a parent’s method. Overloading happens in the same class - same method name, with different parameters.

30
Q

How do you prevent a class from being sub-classed in Java?

A

Make it’s constructor private.

31
Q

What’s the difference between StringBuilder and StringBuffer in Java?

A

StringBuilder is not synchronized while StringBuffer is.

32
Q

What’s the difference between Polymorphism and Inheritance in Java?

A

Inheritance allows code reuse and builds relationships between classes - it lets us inherit attributes and methods from another class. Inheritance is required by Polymorphism, which uses those methods to perform different tasks.

33
Q

What is polymorphism?

A

The ability of a class instance to behave as if it were an instance of another class in its inheritance tree.

34
Q

Can you override static methods in Java?

A

No - overriding occurs at runtime, while static method calls are resolved at compile time.

35
Q

What is the difference between abstract class and interface in Java?

A

An abstract class can have a state, it can contain variables which can be modified by non-abstract methods. An interface cannot have a state.
Abstract classes can have constructors, but an interface cannot.

36
Q

What’s the difference between throw and throws keywords in Java?

A

Throws declares the exceptions a methods can throw in the event of an error; the keyword throw actually throws the exception.

37
Q

Difference between fail-safe, and fail-fast iterators in Java?

A

fail-safe doesn’t throw ConcurrentModificationException while fail-fast does… when they detect an outside change on a synchronized collection while iterating over it.

38
Q

Difference between Iterator and Enumeration in Java?

A

Iterator lets you remove an element while iterating over it, while Enumeration doesn’t. Iteration is pretty much the standard.

39
Q

What is IdentityHashMap in Java?

A

A Map, which uses the == equality operator to check equality instead of equals() method.

40
Q

Can Serializable contain non-serializable fields?

A

Yes, but they need to be static or transient.

41
Q

Difference between “this” and “super” in Java?

A

This refers to the current instance, while super refers to an instance of the superclass.

42
Q

What’s the difference between checked and unchecked Exceptions in Java?

A

You must handle checked exceptions with a catch block, while unchecked are not required.

43
Q

What’s the difference between an Error and an Exception in Java?

A

Both derived from java.lang.Throwable, Errors represent errors which are cannot be handled - usually catastrophic. OutofMemoryError, NoClassDefFoundError, etc. Exception represents errors which can be catch and dealt with. Checked Exceptions MUST be caught, while unchecked exceptions do not.

44
Q

What’s the difference between Race condition and Deadlock?

A

Race Condition - two or more threads compete to get certain shared resources.

More than one thread first read the variable, then alter the given value and write it back.

check-then-act

A deadlock occurs when two or more threads are waiting for each other to release the resource they need (lock) and get stuck for infinite time.

45
Q

StringBuffer vs StringBuilder?

A

StringBuffer thread-safe & syncrhronized, StringBuilder is not.

46
Q

What are the 5 major types of memory allocation in java?

A
  1. Class Memory
  2. Heap Memory
  3. Stack Memory
  4. Program Counter Memory
    5 Native Method Stack Memory
47
Q

Default value stored in Local Variable?

A

No default value (unless you assign one when you in)

48
Q

Instantiation vs Initialization

A

Java’s “new” operator instantiates (creates) the object. The “new” operator is followed by a call to a constructor, which initializes the new object.

49
Q

What are copy constructors?

A

A constructor that initializes a class using an object of the same type.

50
Q

What is Object Cloning?

A

Ability to recreate an exact copy of an object to an existing object. Offers same functionality as the original.

51
Q

What are Wrapper Classes in Java?

A

When you declare primitive datatypes, wrapper classes are responsible for converting them into objects. Ex:

int Integer
double Double

52
Q

What is a Singleton?

A

A class who’s constructor is private - can only generate one single object. Used when managing access to a resource which is shared by the entire application (IE database connection).

53
Q

What is a “package” in java?

A

A collective bundle of classes / interfaces / libraries / JAR files. Improves reuseability.

The “Java” package contains Subpackages - lang, util.

54
Q

Can you implement pointers in Java?

A

No - JVM handles memory. C++ pointers allow you to access memory directly.

55
Q

Difference between instance and local variables.

A

Instance variables are declared inside a class, and scope is limited to that specific object.

Local variables are declared inside a method / block of code, and scope is limited to the block of code where it was declared.

56
Q

What is Java String Pool?

A

A collection of strings in Java’s Heap memory. When creating a new string object, JVM checks for the presence of the object in the pool. If available the object reference is shared with the variable, else a new object is created.

57
Q

What is final keyword?

A

When the value is declared, value remains constant.

58
Q

What is JDK?

A

JDK = Java Development Kit, a combined package of JRE (Java Runtime Environment) and Developer tools.

59
Q

What are access specifiers and types of access specifiers?

A

Access specifiers define the scope of an object / class / variable / method.
Public - accessible everywhere.
Private - accessible within the same class only.
Protected - can only be accessed by classes of the same package / sub packages
Default - only accessible inside the package

60
Q

Can a constructor return a value?

A

Yes, it returns the current instance of the class implicitly. Can not explicitly return a value.

61
Q

What is “this” keyword in java?

A

References the current class properties / methods, opposed to parent.

62
Q

What is “super” keyword in Java?

A

References parent class object properties / methods.

63
Q

What is method overloading in Java?

A

Creating multiple method signatures for one method name.

64
Q

Can you overload / override static methods?

A

Method overloading/overriding is based on dynamic binding at run time, and static methods are bonded at compile time.

65
Q

Why is delete function faster in a linked list than an array?

A

Arrays are stored in blocks, so you need to make an adjustment to the storage block. In a linked list, you’re just dropping a reference value from the list.

66
Q

Life cycle of a thread?

A
  1. New Born State
  2. Runnable State
  3. Running State
  4. Blocked State
  5. Dead State
67
Q

Life Cycle of an applet?

A

Initialization
Start
Stop
Destroy
Paint