Java Interview Qs Flashcards

1
Q

List all the primitives in Java

A
byte
short
int
long
float
double
char
boolean
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the difference between StringBuilder() and StringBuffer()?

A

StringBuffer() is threadsafe

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

What are the 4 principles of Object Oriented Programming?

A

Abstraction
Polymorphism
Inheritance
Encapsulation

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

Explain abstraction.

A

handle complexity by hiding unnecessary details from the user

Abstraction means using simple things to represent complexity. We all know how to turn the TV on, but we don’t need to know how it works in order to enjoy it. In Java, abstraction means simple things like objects, classes, and variables represent more complex underlying code and data. This is important because it lets us avoid repeating the same work multiple times.

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

Explain polymorphism.

A

“SAME NAME, MANY FORMS. This Java OOP concept lets programmers use the same word to mean different things in different contexts. It allows programmers to write code that doesn’t have to change when new subtypes are introduced into the program.

One form of polymorphism in Java is method overloading. That’s when there are multiple functions with the same name but with different arguments. Functions can be overloaded by change in number of arguments and/or change in type of arguments.

The other form is method overriding. That’s when the different meanings are implied by the values of the supplied variables. When overriding a method, the arguments must be the same as the super type and the return types must be compatible. The method cannot be less accessible than the super method call.

TWO TYPES:
Runtime Time Polymorphism handled during runtime: example (Overriding)
Compile Time Polymorphism (static polymorphism) handled in the compiler: example (Overloading)”

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

Explain inheritance.

A
"This is a special feature of Object Oriented Programming in Java. It lets programmers create new classes that share some of the attributes of existing classes. This lets us build on previous work without reinventing the wheel.
    * The ability for a sub class to access the super class's members implicitly through the keyword `extends`; Members include methods as well as variables."

Do not use ‘parent/ child’ to describe this relationship

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

Explain encapsulation.

A

This is the practice of keeping fields within a class private, then providing access to them via public methods. It’s a protective barrier that keeps the data and code safe within the class itself. This way, we can re-use objects like code components or variables without allowing open access to the data system-wide.

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

What are the 4 access modifiers and their access specifiers

A

Public: Global, Package, Class, Subclass, Variable
Protected: Package, Class, Subclass
Default: Package, Class,
Private: Class, Variable

“Default” is leaving the field/method without an access modifier

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

What are the 5 SOLID principles?

A
Single Responsibility
Open/Close Principle
Liskov's Substitution Principle
Interface Segregation Principle
Dependency Inversion
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain “Single Responsibility”

A

a class should have only a single responsibility (i.e. changes to only one part of the software’s specification should be able to affect the specification of the class).

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

Explain “Open/Close Principle”

A

“open for extension, but closed for modification.” classes’ properties can be inherited and used by subclasses etc, but not altered directly.

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

Explain “Liskov’s Substitution Principle”

A

“objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”

Enables you to replace objects of a parent class with objects of a subclass without breaking the application. This requires all subclasses to behave in the same way as the parent class. To achieve that, your subclasses need to follow these rules:

  • Don’t implement any stricter validation rules on input parameters than implemented by the parent class.
  • Apply at the least the same rules to all output parameters as applied by the parent class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Explain “Interface Segregation Principle”

A
"many client-specific interfaces are better than one general-purpose interface."
in other words, when you implement an interface, do you want your class flooded with empty methods you'll never use, or just the few that offer the functionality you are looking for?
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Explain “Dependency Inversion”

A

one should “depend upon abstractions, [not] concretions.”

High-level modules, which provide complex logic, should be easily reusable and unaffected by changes in low-level modules, which provide utility features. To achieve that, you need to introduce an abstraction that decouples the high-level and low-level modules from each other.

In other words–don’t extend ArrayList class to get those functions; implement List interface instead.

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

What is the difference between overloading and overriding?

A

Overloading occurs when two or more methods in one class have the same method name but different parameters. Overriding means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class. Overriding changes the BEHAVIOR of the method.

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

What is the difference between an abstract class and an interface?

A

An abstract class can contain non abstract methods and default methods, an interface can only contain method signatures.

A class can only extend one abstract class, but it can implement multiple interfaces.

An abstract class can have any access modifiers on its methods and fields, an interface can only be public. Interface fields are public static final.

Both can let you use classes of the same supertype.

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

For Interface and Abstract Class, why would you use one over the other?

A

You can implement multiple interfaces but you can only extend one abstract class. Also, you can flesh out methods more fully in an abstract class; Interfaces are for empty methods.

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

What is the difference between “Collection” and “Collections”

A

Collections is a utility class present in java.util. package to define several utility method (like sorting,searching ) for collection object. Collections is a class that defines methods that are used to operate on a collection.

Collection is an interface; the root interface in the collection hierarchy. It provides classes and interfaces to represent a group of individual objects as a single unit.

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

What is an ArrayStoreException? Is it checked or unchecked?

A

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. It is an unchecked error that occurs at runtime.

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

Describe JVM, JDK, and JRE

A

JDK: Java development kit is the tool necessary to compile, document and package Java programs. (like SDK)

JRE: A subset of the Java Development Kit (JDK) for end-users and developers who want to redistribute the runtime environment alone. The Java runtime environment consists of the Java virtual machine, the Java core classes, and supporting files. Abstracts away machine differences for java programs to run.

JVM: The java virtual machine is a specification that provides run-time environment in which java byte code can be executed. (Environment where Java programs can be run)

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

What is a HashMap?

A

HashMap is a Map based class that is used for storing Key & value pairs, does not sort the stored keys and Values

TALK ABOUT BUCKETS AND COLLISION

Key-value pairs are stored in what is known as buckets which together make up what is called a table, which is actually an internal array.

Hash maps store both key and value in the bucket location as a Map.Entry object.

A collision, or more specifically, a hash code collision in a HashMap, is a situation where two or more key objects produce the same final hash value and hence point to the same bucket location or array index.

This scenario can occur because according to the equals and hashCode contract, two unequal objects in Java can have the same hash code.

Java implements a hash code collision resolution technique.

It’s the hash value of the key that determines the bucket the object will be stored in. And so, if the hash codes of any two keys collide, their entries will still be stored in the same bucket.

And by default, the implementation uses a linked list as the bucket implementation.

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

Why is a HashMap unsorted?

A

Two reasons:
One, it IS sorted by Java’s own internal logic; entries are sorted by hashcode. It is not sorted in any human-readable way
Two, HashMaps are SETS of key-value pairs, and sets are (often) unsorted sets of unique values.

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

What is the difference between Comparable and Comparator?

A

Comparable: This interface has one method, compareTo() which compares a specific object to another. Class with objects to be sorted must implement this Comparable interface.

Comparator: It’s its own class that is designed to compare objects of the same type and is specifically for custom comparisons. This interface has two methods, equals() and compare(). Class with objects to be sorted do not need to implement this Comparator interface.

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

What is the Class Loader?

A

Part of JVM which is used to load classes and interfaces.

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

What are the 5 exception keywords?

A

Try, Catch, Finally, Throw, Throws

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

Difference between throw and throws?

A
"Throws" goes in signature: 
    void method() throws Exception {}
"Throw"" goes in method body: 
    void method() { throw new Exception; }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Difference between Final, Finally, Finalize?

A

Final: Final is a keyword used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.

Finally: Finally is a code block used to place important code, it will be executed whether exception is handled or not.

Finalize: Finalize is a method used to perform clean up processing just before object is garbage collected.

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

What is Dictionary in Java?

A

The Dictionary class is the abstract parent of classes like Hashtable , which maps keys to values. Any non- null object can be used as a key and as a value.

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

Which collection is the fastest?

A

Every collection type is suitable for a particular scenario. There is no fastest or best collection.

Need to access using INDEX -> ArrayList
Need to access using KEY -> HashMap
Need to access using VALUE -> HashSet
Need fast traversal or fast add/remove of elements -> LinkedList

Sets are internally backed by Map implementation, so performance technically is the same, although the performance of both degrades towards that of a LinkedList when hashing of key object is poor (many hash collisions)

ArrayList is backed by Arrays internally, so they are very fast for by-index access of elements

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

What is the difference between instance methods and static methods?

A

Static methods contain the keyword static in their signature and can be called without an instantiation of the class they belong to.

Instance methods are the opposite - do not contain static keyword in the signature and require you to call them from an instance of the class.

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

What is an instance variable?

A

An attribute, or field of an object.

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

What is the finalize method?

A

The method called before garbage collection on any Java object.

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

What is an access modifier?

A

A clause that describes who or what can access or modifiy the state of an object. Examples: public, private, default, protected

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

What is an abstract class?

A

A class that contains one or more abstract methods, and therefore can never be instantiated. Abstract classes are defined so that other classes can extend them and make them concrete by implementing the abstract methods.

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

What is an abstract method?

A

A method that has no implementation. ex interface methods are abstract

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

What is an API?

A

Application Programming Interface. The specification of how a programmer writing an application that accesses the behavior and state of classes and objects. A software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message, or check the weather on your phone, you’re using an API.

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

What is autoboxing?

A

Automatic conversion between reference (Wrapper classes) and primitive types.

DONE BY COMPILER

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

what is a class variable?

A

A data item associated with a particular class as a whole–not with particular instances of the class. Class variables are defined in class definitions. Also called a static field

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

What is a class path?

A

An environmental variable which tells the Java virtual machine and Java technology-based applications where to find the class libraries, including user-defined class libraries.

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

What does DOM stand for?

A

Document object model.

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

What is an enumerated type?

A

A type whose legal values consist of a fixed set of constants. An example of this would be an enum.

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

Explain garbage collection

A

The automatic detection and freeing of memory that is no longer in reference. The Java runtime system performs garbage collection so that programmers never explicitly free objects.

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

What is generics?

A

Definition: “A generic type is a generic class or interface that is parameterized over types.”

Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.

Rather than specifying obj to be of an int type, or a String type, or any other type, you define the Box class to accept a type parameter . Then, you can use T to represent that generic type in any part within your class.

Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.

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

Explain type erasure

A

The deletion of paramatized types at runtime.

To implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded

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

Explain JAR (Java Archive)

A

Platform-independent file format that aggregates many files into one. Multiple applets written in the Java programming language, and their requisite components can be bundled in a JAR file and subsequently downloaded to a browser in a single HTTP transaction.

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

Why is java considered dynamic?

A

It can run on any operating system that has a JVM.

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

What does it mean to be multithreaded?

A

Designed to have parts of its code execute concurrently (in parallel)

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

What does it mean to be protected?

A

Signifies that the method or variable can only be accessed by elements residing in its class, subclasses, or classes in the same package.

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

What is a Command pattern?

A

A request is wrapped under an object as command and passed to invoker object. Invoker object looks for the appropriate object which can handle this command and passes the command to the corresponding object which executes the command.

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

What is an Adapter pattern?

A

Converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

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

What is a Facade pattern?

A

provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher- level interface that makes the subsystem easier to use.

It simplifies an interface and decouples a client from a subsystem of components. It hides complexities of a system and provides an interface to the client from where the client can access the system.

An example can be the startup of a computer. When a computer starts up, it involves the work of cpu, memory, hard drive, etc. To make it easy to use for users, we can add a facade which wrap the complexity of the task, and provide one simple interface instead.

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

What is the difference between Adapter and Facade?

A

Adapter links two incompatible interfaces and facade is used when you want an easier or simpler interface to work with.

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

What is template Method pattern?

A

Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

54
Q

What is an anonymous inner class?

A

It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overloading methods of a class or interface, without having to actually subclass a class.

55
Q

What is a lambda expression?

A

A function that can be defined without belonging to any specific class. Lambda expressions are commonly used to implement simple event listeners, or in functional programming with the Java Streams API. They enable you to treat functionality as a method argument, or code as data.

Notation looks like this: (parameters) -> { method body };

56
Q

What is a functional interface?

A

An interface that contains exactly one abstract method. Lambda expressions can be used to represent instances of functional interfaces, and you can use functional interfaces to put method references and lambda expressions into Collections.

57
Q

List the functional interfaces and their functional methods.

A

PREDICATE
That takes a single value as parameter, and returns true or false.
T -> Boolean
boolean test(T t);

FUNCTION
The Function interface represents a function (method) that takes a single parameter and returns a single value.
T -> R
R apply(T t);

CONSUMER
Function that consumes a value without returning any value. A Java Consumer implementation could be printing out a value, or writing it to a file, or over the network etc.
T -> void
void accept(T t);

SUPPLIER
Function that supplies a value of some sorts.
void -> T
T get();

58
Q

What is functional programming?

A

In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. When a pure function is called with some given arguments, it will always return the same result, and cannot be affected by any mutable state or other side effects.

At first, you could think about lambda expressions as a way of supporting functional programming in Java. Functional programming is a paradigm that allows programming using expressions i.e. declaring functions, passing functions as arguments and using functions as statements (rightly called expressions in Java8).

59
Q

What are the FIRST principles of TDD?

A

Tests should be:
Fast - The code seems to be fast because there is nothing complex about its tests.
Independent - The test doesn’t depend on other tests.
Repeatable - The test will get the same result every time.
Self-validating - The test can automatically detect if it’s passed.
Timely - Both the code and the test code are presented here at the same time.

60
Q

What is the difference between composition and inheritance?

A

Composition is instantiating a class as a field (“has a” relationship)

Inheritance is inheriting all fields and methods from parent class (“is a” relationship)

61
Q

What is an advantage of Java (with its JVM) over other languages that work from the hardware?

A

The JVM can be run on any platform, making it dynamic. C++, for instance, runs on the hardware, so it is not dynamic.

62
Q

What is Stream in Java?

A

Streams are used to process collections of objects.

Streams are not data structures, but rather they take input from Collections and Arrays and operate on that data instead.

Streams don’t change the original collection.

Every Stream operation is executed in a “lazy” manner, returning either another Stream (intermediate operation) or the result of the pipeline of operations (terminal operation).

63
Q

What are some intermediate operations of the Stream API?

A

map()
flatmap()
filter()
sorted()

64
Q

What are some terminal operations of the Stream API?

A

collect()
forEach()
reduce()

65
Q

Why would you use an array over an arraylist and vice versa

A

You would use an Array if you are terribly concerned with squeaking out the absolute best performance possible, as they are more efficient than ArrayList.

You would use ArrayList in almost every other situation, as they auto-resize and provide a lot of helpful methods (like add(), remove(), contains()) that are not provided by arrays out of the box. Arrays work much better with primitives and if you wanted to do multidimensional.

Arrays you have to worry about type saftey whereas Arraylist use generics under the hood so they can take any object. Arraylists are much better for insertion.

66
Q

What is Project Lombok? What are some things that it is used for?

A

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

67
Q

What are semaphores?

A

They are very similar to Locks, in terms of their use. They are used to control access to common resources in multi-threaded (parallel) systems.

A semaphore controls access to a shared resource through the use of a counter. If the counter is greater than zero, then access is allowed. If it is zero, then access is denied. The counter is counting permits that allow access to the shared resource. To access the resource, a thread must be granted a permit from the semaphore.

A useful way to think of a semaphore as used in the real-world system is as a record of how many units of a particular resource are available, coupled with operations to adjust that record safely (i.e., to avoid race conditions) as units are acquired or become free, and, if necessary, wait until a unit of the resource becomes available.

68
Q

What is Dijkstra’s algorithm?

A

an algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks.

69
Q

What are the two basic methods of creating threads in Java?

A
  1. Extends Thread class. Create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run() method which is the entry point of the new thread.
  2. The easiest way to create a thread is to create a class that implements the runnable interface. After implementing runnable interface, the class needs to implement the run() method.
70
Q

What are some potential new features that the Java developers are likely to add to the language in future updates?

A

Value Types

  • Objects without identity (but still have efficient memory layout)
  • [In Java, primitives are the only current example of Value Types)

64-bit addressable arrays to support large data sets

Records
- Objects that are defined with much more concise syntax than is needed currently. Ideally these objects would be defined simply by their value members.

Sealed Types
- A mechanism for declaring all possible subclasses of a class

Pattern Matching
- A mechanism that may be added to switch and instanceof expressions that would make it easier to deconstruct types, and use more concise syntax.

Pattern Matching Example
       Old Syntax:
       if (obj instanceof String) {
           String s = (String) obj;
           System.out.println(s);
       }
       Pattern Matching Syntax:
       if (obj instanceof String s) {
           System.out.println(s);
       } else {
           // can't use s here
       }
71
Q

What is OOP?

A

Object Oriented Programming is about creating objects that contain both data and methods. OOP provides a clear structure for programs, helps keep the Java code DRY (don’t repeat yourself) and makes the code easier to maintain, modify, and debug. OOP makes it possible to create full reusable applications with less code and shorter development time.

72
Q

Why might you make a class an enum?

A

if you need a value that you know you are not going to change

example: letters to represent a size, suites for a card deck

73
Q

Why might you prefer composition over inheritance?

A

When you need to create a scenario where something “has a” is best practice. I.E. a Customer has an Account

74
Q

Why might you prefer inheritance over composition?

A

When you need to create a scenario where something “is a” is best practice. I.E. a Savings account is a type of Account

75
Q

What is a thread?

A

The path followed when executing a program;

all have at least 1 thread (known as the main thread)

76
Q

Why might you use Streams?

A

The whole idea of Java streams is to enable functional-style operations on streams of elements. A stream is an abstraction, it’s not a data structure. It’s not a collection where you can store elements. The most important difference between a stream and a structure is that a stream doesn’t hold the data. Remember, a stream is able to do all calculations at the same time.

77
Q

What is deadlock?

A

a situation where two or more threads are blocked forever, waiting for each other.

Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.

The program will hang forever because neither of the threads in position to proceed and waiting for each other to release the lock

78
Q

Breadth-first search VS Depth-first search

A

These two terms differentiate between two different ways of walking a tree.

It is probably easiest just to exhibit the difference. Consider the tree:

          A
          / \
        B   C
        /     / \
       D   E   F

A depth first traversal would visit the nodes in this order

A, B, D, C, E, F

Notice that you go all the way down one leg before moving on.

A breadth first traversal would visit the node in this order

A, B, C, D, E, F

BFS is more suitable for searching vertices which are closer to the given source. DFS is more suitable when there are solutions away from the source.

BFS considers all neighbors first. With DFS, we make a decision and explore all paths through the decision.

79
Q

What are the differences between the different versions of Java?

A

Java 11:
var for Lambda Parameters
JavaFX removed

Java 10:
var Keyword (local variable type inference)

Java 9:
Modules

Java 8:
Lambda Expressions
Method References
Stream API
Default methods in Interfaces
Improvements to annotations

Java 7:
Type-inference for diamond operators
Switch on Strings
Try-with-resources

Java 6:
No major language features added

Java 5:
Generics
Autoboxing/Unboxing
Typesafe Enums
For-each Loop
Varargs
Annotations
80
Q

Are Strings immutable?

A

Yes

81
Q

What are the advantages of a Java design pattern?

A

The design patterns are reusable in multiple projects.

The design patterns provide a solution that helps to define system architecture.

The design patterns provide transparency to the design of an application.

82
Q

What are the Creational Patterns?

A

Creational design patterns involve object instantiation and all provide a way to decouple a client from the objects it needs to instantiate.

83
Q

What is a Factory Pattern?

A

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.

Example: Account -> many kinds of accounts

84
Q

Explain Structural Patterns in Java.

A

Structural Patterns are used to provide solutions and efficient standards regarding class compositions and object structures. They depend on the concept of inheritance and interfaces to allow multiple objects or classes to work together and form a single working whole.

Structural design patterns let you compose classes or objects into large structures.

85
Q

Explain the Singleton Pattern.

A
The Singleton Pattern in Java is a pattern which allows a single instance within an application. Singleton Pattern 
states that one can define a class that has only one instance and provides a global point of access to it. 

In other words, it is the responsibility of the class that only a single instance should be created and all other classes can use a single object.

A singleton class has a private constructor and a static getInstance() method, as you do not an instantiate it when you need it, rather you call the getInstance() method.

86
Q

What are the Adapter Patterns?

A

An adapter pattern converts the interface of a class into another interface the client supports. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

87
Q

What are the uses of Adapter Patterns?

A

It is used:

  • When an object requires to utilize an existing class with an incompatible interface.
  • In case we want to create a reusable class that collaborates with classes which don’t have compatible interfaces.
88
Q

What is the decorator pattern in Java and explain it with an example.

A

The decorator pattern is one of the most popular Java design patterns. It is common because of its heavy usage in the java.io(package). The Decorator Pattern uses composition in place of inheritance to extend the functionality of an object at runtime.

Decorator classes mirror the type of the components they decorate (they are the same type of the components they decorate, either through inheritance or interface implementation).

They change the behavior of their components by adding new functionality before and/or after (or even in place of) method calls to the component.

BufferedReader and BufferedWriter are some examples of decorator pattern in Java.

89
Q

What is the difference between Strategy and State design Pattern in Java?

A

Strategy and State pattern have the same structure, but their intent is different.

The state pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable and it defines a context object whose behavior varies as per its strategy object. Strategy lets the algorithm vary independently from the client that uses it.

90
Q

What are the advantages of the Composite Design pattern in Java?

A

Composite design pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Advantages of composite design patterns is as follows:

  • It describes the class hierarchy that contains primitive and complex objects
  • It makes it easy to add new kinds of the component
  • We can apply the same operation over both composites and individual objects
  • It facilitates with the flexibility of structure with a manageable class or interface
91
Q

Can you describe the uses of the composite pattern?

A

A partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies.

92
Q

What are the advantages of the Builder design pattern?

A

The Builder Pattern encapsulates the construction of a product and allows it to be constructed in steps.

Advantages:

  • Encapsulates the way a complex object is constructed
  • Allows objects to be constructed in a multi-step and varying process (as opposed to one-step factories)
  • Hides the internal representation of the product from the client
  • Product implementations can be swapped in and out because the client only sees an abstract interface
93
Q

Is Java pass by reference or pass by value?

A

Java is pass by value, which means pass by copy. Java creates a copy of the variable being passed in the method and then does the manipulations.

94
Q

What is the difference between TreeMap, HashMap, LinkedHashMap?

A

All offer a key -> value map and a way to iterate through the keys. The most important distinction between these classes is the time guarantees and the ordering of the keys.

HashMap offers O(1) lookup and insertion. If you iterate through the keys, the ordering of the keys is arbitrary. It is implemented by an array of linked lists.

TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through the keys in sorted order, you can. This means the keys must implement the Comparable interface. TreeMap is implemented by a Red-Black tree.

LinkedHashMap offers O(1) lookup and insertion. Keys are ordered by their insertion order. It is implemented by doubly-linked buckets.

95
Q

What are the benefits of the Java Collections Framework?

A

The benefits of Java Collections Framework include highly efficient performance, reusability, ease of maintenance and opportunities to customize collection types.

96
Q

What are the main interfaces used in the Java Collections Framework? Describe each.

A

5 primary interfaces are: the Collection interface, Set Interface, Queue Interface, List Interface and Map Interface.

The Collection Interface: the core of the framework and foundation on which most projects are built.

Set Interface: it does not allow for index-based searches or duplicate entries.

Queue Interface: stores entries in a queue based on the ordered they were entered.

List Interface: ordered and contain duplicate entries if desired.

Map Interface: key value pairing is essential and it is a data structure that does not allow duplicates as a requirement

97
Q

How would you describe removing redundant elements from an ArrayList object?

A

To remove redundant element from an ArrayList, you should follow three steps.

First, offload elements in the ArrayList to a LinkedHashSet. Next, make sure the ArrayList is empty, and finally, copy all elements of the LinkedHashSet back to an ArrayList.

98
Q

What is the difference between List and Set?

A

The list interface allows duplicate elements. The Set interface does not.

The list maintains it’s insertion order. A set does not maintain any insertion order.

We can add any number of null values in a list. A set can almost always have only one null value.

List implementation classes are: ArrayList, LinkedList. Set implementation classes are HashSet, LinkedHashSet, and TreeSet.

The list provides a get() method to get the value at a specified index. Set does not provide get method to get the elements at a specified index.

If you need to access elements frequently by the index, use list. If you want to create a collection of unique elements then use a set.

Traverse a List via ListIterator. Traverse a set via Iterator.

99
Q

What is the difference between Map and Set?

A

Sets and maps both do not allow duplicate elements and do not maintain any insertion order. Set and Maps do not provide a get method to get the elements at a specified index.

A Set allows almost only one null value, a map allows a single null key at most and any number of null values.

Set implementation classes are HashSet, LinkedHashSet, and TreeSet. Map Implementation classes are HashMap, HashTable, TreeMap, ConcurrentHashMap, LinkedHashMap.

If you want to create a collection of unique elements then we use set. If you want to store data in the form of key value pairs, then we can use the map.

Iterator can be used to traverse the Set elements. Map elements can be traversed through by converting it to a set with with keyset() or entryset().

100
Q

What is the difference between Iterator and Enumeration?

A

Iterator and enumeration are interfaces that allow you to iterate a Collection to examine all of its elements. They both have the same basic purpose but iterator has more advanced features than enumeration. For example, it can remove an element from a collection.

101
Q

What is the difference between Iterator and List Iterator?

A

Iterator can traverse elements present in Collection only in the forward direction. ListIterator can traverse elements present in Collection both in forward and backward directions.

Iterator helps to traverse Map, List, and Set. List Iterator can only traverse List and not the other two.

Indexes cannot be obtained by using Iterator. ListIterator has methods like nextIndex() and previousIndex() to obtain indexes of elements at any time while traversing List.

Iterator cannot modify or replace elements present in Collection. ListIterator can modify or replace elements with the help of set(E e).

Iterator cannot add elements and it throws ConcurrentModificationException. ListIterator can easily add elements to a collection at any time.

Certain methods of Iterator are next(), remove(), and hasNext(). Certain methods of ListIterator are next(), previous(), hasNext(), hasPrevious(), add(E e)

102
Q

What is a stack data structure?

A

A stack is a linear data structure in which elements can be inserted and deleted only from one side of the list, called the top. A stack follows LIFO. (last in first out)

The insertion of element into a stack is called a push and the deletion of an element from the stack is called a pop operation.

We always keep track of the last element present in the list with a pointer called top.

103
Q

What is a queue data structure?

A

A queue is a linear data structure in which elements can be inserted only from one side of the list called rear and the elements can only be deleted from the other side called the front. Follows FIFO (first in first out).

The insertion of an element is called an enqueue and the deletion of an element is called a dequeue.

There are two pointers:

  1. ) the front pointer points to the element that was inserted first and is still present
  2. ) the rear pointer points to the element inserted at the last
104
Q

What is the difference between a stack and a queue?

A

Stack is based on LIFO, a queue is based on FIFO.

With stack, insertion and deletion only takes place from one end of the list called the top. With queue, insertion and deletion takes place from opposite ends of the list. The insertion takes place from the rear and deletion takes place from the front of the list.

Stack insert is called a push, queue insert is called an enqueue.

Stack deletion is called a pop, queue deletion is called a dequeue.

Stack has one pointer called the top which points to the last element present in the list. Queue has two pointers, front pointer points to the front element that exists and is still present and the rear pointer points to the last inserted element.

Stacks are used for solving problems with recursion, queue is used in solving problems with sequential processing.

105
Q

What are Fail Fast vs Fail Safe iterators?

A

Fail fast iterators immediately throw a concurrent modification exception if there is a structural modification of the collection while they are iterating over it. (Concurrent modification means to modify an object concurrently when another task is already running over it).

Fail safe iterators do not throw an exceptions if a collection is structurally modified because they operate on a clone of the collection not on the original collection.

106
Q

What is the difference between a HashMap and a HashTable?

A

Both are collections that implement the map interface and neither maintains the insertion order of their elements.

Hashtable is thread-safe and can be shared between multiple threads in an application. Hashmap is not synchronized and cannot be accessed by multiple threads without additional synchronization code. HashMap is faster and uses less memory.

Hashtable does not allow null and HashMap allows one null key and many null values.

Hashtable uses Enumerator to iterator over values. HashMap uses Iterator to iterate over values. Iterator can remove objects from the underlying collection and is fail-fast.

107
Q

What is a String?

A

A String is represented internally by an array of byte values. A String is composed of an immutable array of Unicode characters.

108
Q

How can we create a String object in Java?

A

Through a String literal:
String s =”abc”

Through the new keyword:
String s = new String("abc")

(There are 13 ways though)

109
Q

Is String a primitive or a Derived Type?

A

A String is a derived type since it has state and behavior. It has methods like substring(), indexOf(), and equals() which primitives cannot have.

It has some special characteristics:

  • Strings are not stored on the local call stack like primitives are, they are stored in a special memory region called the string pool.
  • Like primitives, we can use the + operator.
  • Can create an instance of string w/o the New keyword
110
Q

What are the benefits of Strings being immutable?

A

Strings are immutable to improve performance and security.

The String pool is only possible if the strings, once created, are never changed as they are supposed to be reused.

The code can safely pass a string to another method, knowing it cannot be altered by that method.

Immutability makes this class thread-safe.

Their hashcodes can be easily cached since they are guaranteed not to change.

111
Q

How is a string stored in memory?

A

String literals are stored in a runtime constant pool, which is allocated from the JVM’s method area. This runtime constant pool for a class or interface is constructed when the class or interface is created by the JVM.

A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored. When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap.

112
Q

Are Interned Strings eligible for garbage collection in Java?

A

All strings in the string pool are eligible for garbage collection if there are no references from that program.

113
Q

What is the String Constant Pool?

A

A special memory region where the JVM stores String instances. It optimizes performance by reducing how often and how many strings are allocated.

The JVM stores only one copy of a particular String in the pool.

When creating a new String, the JVM searches in the pool for a String having the same value.

If found, the JVM returns the reference to that String without allocating any additional memory.

If not found, the JVM adds it to the pool (interns it) and returns its reference.

114
Q

Are Strings thread-safe?

A

Strings are thread-safe because they are immutable. If a thread changes a strings value, then a new String gets created instead of modifying the existing one.

115
Q

What is the underlying character encoding for Strings?

A

Strings are stored in the UTF-16 format internally.

116
Q

How can we compare two Strings in Java? What is the difference between str1 == str2 and str1.equals(str2)?

A

We can compare Strings in two different ways by using the equal to operator (==) and by using the equals() methods. Both are quite different:

str1 == str2 checks for referential equality
st1.equals(str2) checks for lexical equality

Typically, we should always use String.equals() for comparing two Strings for their content.

117
Q

How can we split a String in Java?

A

The String class provides a String.split() method which accepts a regular expression delimiter. It returns a String[] array.

118
Q

What is Stringjoiner?

A

Stringjoiner is a class introduced in Java 8 for joining separate strings into one. We can supply a delimiter, as well as a prefix and a suffix.

119
Q

What is the difference between String, Stringbuffer, and Stringbuilder?

A

Strings are immutable. If we try to change its value, Java creates an entirely new String. For most simple cases, the compiler internally uses StringBuilder. For more complex cases like loops, it creates a new String and deteriorates performance.

StringBuilder and StringBuffer create objects that hold a mutable sequence of characters. StringBuffer is synchronized and is thread safe whereas StringBuilder is not.

120
Q

Why is it safer to store passwords in a Char[] array rather than a string?

A

Strings are immutable, so they do not allow modification. This keeps us from overwriting, modifying, or zeroing out its contents, making Strings unsuitable for sensitive information.

By using char[] array, we have complete control over that information. We can modify it or wipe it completely without even relying on the garbage collector.

121
Q

How can we convert String to Integer and Integer to String in Java?

A

To change an Integer to a String we can use Integer.parseInt().

To do the reverse, we can use Integer.toString()

122
Q

What is String.format() and how can we use it?

A

String.format() returns a formatted string using the specified format string and arguments.

123
Q

How can we convert a String to uppercase and lowercase?

A

String provides String.toUpperCase() String.toLowerCase() methods.

124
Q

How can we get a Character Array from String?

A

String provides toCharArray which returns a copy of it’s internally char-array.

125
Q

How do we convert a Java String into a Byte Array?

A

The method String.getBytes() encodes a String into a Byte array using the platform’s default charset.

126
Q

What is a brute force algorithm?

A

A brute force algorithm is a straightforward method of solving a problem that relies on sheer computing power and trying every possibility rather than advanced techniques to improve efficiency.

127
Q

What is a searching algorithm?

A

Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is stored. These are typically categorized in two main categories:

Sequential Search: The list or array is traversed sequentially and every element is checked.

Interval Search: These algorithms are specifically design for searching in sorted data-structures.

These type of searching algorithms are much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half.

128
Q

Explain Aggregation.

A

Aggregation is a HAS A relationship. Both the entries can survive individually which means ending one entity will not effect the other entity.

129
Q

What is the difference between Composition and Aggregation?

A

In both aggregation and composition, an object of one class “owns” an object of another class. However, aggregation implies a relationship where the subtype can exist without the supertype and Composition implies a relationship where the subtype cannot exist independent of the parent.

130
Q

Of the 4 CRUD methods, which ones are idempotent?

A

Read (since it is getting all)
Update (if you send the same update, it will return the same results)
Delete (if you deleted multiple times it will return the same thing)