0% found this document useful (0 votes)
11 views12 pages

Viva

Uploaded by

a90685766
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views12 pages

Viva

Uploaded by

a90685766
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Scala Theory Viva Questions and Answers

1. Basics of Scala

Q: What is Scala, and how is it different from Java?


A: Scala is a hybrid functional and object-oriented programming language that runs on the Java Virtual
Machine (JVM). It differs from Java by offering features like immutability, pattern matching, and concise
syntax. Scala also supports higher-order functions and lazy evaluation, making it more suitable for
functional programming.

Q: Explain Scala's features as a functional and object-oriented programming language.


A: Scala blends functional programming (e.g., immutability, higher-order functions) with object-oriented
features (e.g., inheritance, polymorphism). It allows you to use functions as first-class citizens while also
enabling modular design with traits and classes.

Q: What are case classes, and why are they used?


A: Case classes in Scala are immutable classes that are optimized for pattern matching. They
automatically provide methods like equals, hashCode, and toString, making them ideal for representing
immutable data.

Q: Define immutability. Why is it important in Scala?


A: Immutability means that an object’s state cannot be changed after it is created. It is important in Scala
because it avoids side effects, making programs easier to reason about and concurrent programming
safer.

Q: What are higher-order functions in Scala? Provide examples.


A: Higher-order functions are functions that take other functions as parameters or return functions as
results.
Example:

def applyFunction(f: Int => Int, x: Int): Int = f(x)

val square = (x: Int) => x * x

applyFunction(square, 5) // Output: 25

Q: Explain the concept of lazy evaluation.


A: Lazy evaluation delays the computation of a value until it is needed. In Scala, this is implemented
using lazy val.
Example:

lazy val x = {

println("Computing x")

10

Q: What is the difference between val, var, and lazy val?


A:
• val: Immutable, once assigned cannot be changed.

• var: Mutable, can be reassigned.

• lazy val: Evaluated only when accessed for the first time.

Q: What are traits, and how do they differ from abstract classes?
A: Traits are like interfaces with the ability to include concrete methods. Unlike abstract classes, traits
can be mixed into multiple classes. Abstract classes can have constructors, but traits cannot.

Q: Describe the purpose of companion objects in Scala.


A: Companion objects are singleton objects that share the same name as a class. They provide methods
or variables that are common to all instances of the class.

2. Collections

Q: What are the main types of collections in Scala?


A: The main types are:

• Sequences (List, Vector)

• Sets (Set, HashSet)

• Maps (Map, HashMap)


Scala collections are categorized into mutable and immutable.

Q: Explain the difference between mutable and immutable collections in Scala.


A:

• Mutable collections can be updated in place (e.g., ArrayBuffer).

• Immutable collections cannot be modified after creation (e.g., List). Instead, they create new
collections when operations are performed.

Q: How does a Map work in Scala, and how can it be created?


A: A Map is a collection of key-value pairs.
Example:

val map = Map("a" -> 1, "b" -> 2) // Immutable map

val mutableMap = scala.collection.mutable.Map("a" -> 1, "b" -> 2)

Q: What is the use of the flatMap function in Scala?


A: flatMap is used to transform and flatten collections.
Example:

val list = List(1, 2, 3)

val result = list.flatMap(x => List(x, x * 10)) // Output: List(1, 10, 2, 20, 3, 30)
Concurrency and Parallelism in Scala

1. Basics

Q: What is the Future class in Scala? How is it used?


A:
A Future represents a value that may not yet be available but will be computed asynchronously. It allows
non-blocking operations.
Example:

import scala.concurrent.Future

import scala.concurrent.ExecutionContext.Implicits.global

val futureResult = Future {

Thread.sleep(1000)

42

futureResult.onComplete {

case Success(value) => println(s"Got the result: $value")

case Failure(e) => println(s"Failed with: $e")

2. Actors

Q: What are Actors in Scala, and how do they relate to concurrency?


A:
Actors are lightweight entities that process messages asynchronously, a core feature of the Akka library.
They encapsulate state and communicate through message passing, avoiding direct access to shared
data.
Example:

import akka.actor._

class MyActor extends Actor {

def receive: Receive = {

case "Hello" => println("Hello, World!")


case _ => println("Unknown message")

val system = ActorSystem("ActorSystem")

val actor = system.actorOf(Props[MyActor], "MyActor")

actor ! "Hello"

3. Akka Framework

Q: Explain the purpose of Akka in Scala applications.


A:
Akka is a toolkit for building concurrent, distributed, and resilient message-driven applications. It
provides the Actor model, enabling developers to handle concurrency at a higher level without dealing
with low-level thread management.

4. Advanced Concepts

Q: What is the difference between Future and Promise in Scala?


A:

• Future: Represents a computation that is being executed and whose result will be available in
the future.

• Promise: A writable, one-time container that completes a Future. It allows the user to explicitly
fulfill or fail the associated Future.
Example:

import scala.concurrent.Promise

val promise = Promise[Int]()

val future = promise.future

promise.success(42) // Fulfills the promise

future.map(println) // Prints 42

Q: How can concurrency issues like race conditions be avoided in Scala?


A:
Concurrency issues can be avoided by:

• Using immutable data structures.


• Leveraging Akka actors to manage state in a thread-safe manner.

• Using synchronized or volatile keywords for shared mutable variables.

• Preferring higher-level abstractions like Future or Promise.

MongoDB Theory Viva Questions and Answers

1. Basics of MongoDB

Q: What is MongoDB, and how does it differ from relational databases?


A:
MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. Unlike relational
databases, MongoDB:

• Does not use tables, rows, and columns.

• Allows schema-less data models.

• Is horizontally scalable using sharding.

Q: Explain the structure of a MongoDB document.


A:
A MongoDB document is a JSON-like structure consisting of field-value pairs. Example:

"_id": "1",

"name": "Alice",

"age": 25,

"skills": ["Java", "MongoDB"]

Q: What is a collection in MongoDB?


A:
A collection is a group of MongoDB documents, similar to a table in relational databases. Collections do
not enforce a schema, allowing documents with different structures.

Q: How are primary keys managed in MongoDB?


A:
Every MongoDB document has a unique _id field, which serves as the primary key. If not provided,
MongoDB generates an ObjectId automatically.

2. CRUD Operations
Q: How do you insert a document into a MongoDB collection?
A:
Documents can be inserted using insertOne or insertMany. Example:

db.collection.insertOne({ name: "Alice", age: 25 });

db.collection.insertMany([{ name: "Bob", age: 30 }, { name: "Charlie", age: 35 }]);

Q: Explain the difference between insertOne and insertMany.


A:

• insertOne: Inserts a single document.

• insertMany: Inserts multiple documents in a single operation.

Q: How do you query documents in MongoDB?


A:
Documents can be queried using the find method. Example:

db.collection.find({ age: { $gt: 25 } }); // Finds documents where age > 25

Q: What is the purpose of the $set operator in MongoDB?


A:
The $set operator is used to update specific fields in a document.
Example:

db.collection.updateOne({ name: "Alice" }, { $set: { age: 26 } });

Q: How do you delete documents in MongoDB?


A:
Documents can be deleted using deleteOne or deleteMany.
Example:

db.collection.deleteOne({ name: "Alice" });

db.collection.deleteMany({ age: { $lt: 30 } });

3. Indexes

Q: What are indexes in MongoDB, and why are they important?


A:
Indexes improve query performance by allowing MongoDB to search efficiently. Without indexes,
MongoDB must scan all documents in a collection.

Q: How do you create an index in MongoDB?


A:
Indexes can be created using the createIndex method.
Example:

db.collection.createIndex({ name: 1 }); // Ascending index on the "name" field


Q: Explain the difference between a single field index and a compound index.
A:

• Single field index: Indexes only one field (e.g., { name: 1 }).

• Compound index: Indexes multiple fields (e.g., { name: 1, age: -1 }).

Q: What are the potential downsides of using too many indexes?


A:

• Increased storage requirements.

• Slower write operations due to index updates.

4. Aggregation

Q: What is the MongoDB aggregation framework?


A:
The aggregation framework processes data records and returns computed results. It supports operations
like filtering, grouping, and transforming data.

Q: Explain the purpose of the $match and $group stages in aggregation.


A:

• $match: Filters documents based on a condition.

• $group: Groups documents and performs aggregate calculations like sum or average.

Example:

db.collection.aggregate([

{ $match: { age: { $gt: 25 } } },

{ $group: { _id: "$age", count: { $sum: 1 } } }

]);

Q: How is the $lookup operator used in MongoDB?


A:
$lookup performs a left join between two collections.
Example:

db.orders.aggregate([

$lookup: {

from: "products",

localField: "productId",
foreignField: "_id",

as: "productDetails"

]);

Q: What is a pipeline in MongoDB aggregation?


A:
A pipeline is a series of stages ($match, $group, etc.) that process data step-by-step.

5. Replication and Sharding

Q: What is replication in MongoDB, and how does it ensure data availability?


A:
Replication is the process of maintaining copies of the same data on multiple servers to ensure
availability and fault tolerance. A primary node handles writes, while secondary nodes replicate the data.

Q: Explain the role of the primary and secondary nodes in a MongoDB replica set.
A:

• Primary node: Handles all write operations.

• Secondary nodes: Replicate data from the primary and handle read operations when configured.

Q: What is sharding in MongoDB, and why is it used?


A:
Sharding partitions data across multiple servers to handle large datasets and improve query
performance. A shard key determines how data is distributed.

Neo4j Theory Viva Questions and Answers

1. Introduction to Neo4j

Q: What is Neo4j, and what makes it different from relational databases?


A:
Neo4j is a graph database that stores data as nodes, relationships, and properties instead of rows and
tables. It is designed for managing highly connected data, enabling efficient traversal of relationships.

Q: What is a graph database, and why is it used?


A:
A graph database represents data in a graph structure with nodes (entities), relationships (connections),
and properties (attributes). It is used to handle use cases like social networks, recommendation engines,
and fraud detection due to its ability to traverse relationships efficiently.

Q: Explain the components of a graph: nodes, relationships, and properties.


A:

• Nodes: Represent entities (e.g., a person or product).

• Relationships: Represent connections between nodes (e.g., FRIENDS_WITH, BOUGHT).

• Properties: Attributes of nodes or relationships (e.g., name, price).

Example: A person node with a relationship FRIENDS_WITH to another person node.

2. Cypher Query Language

Q: What is Cypher, and why is it used in Neo4j?


A:
Cypher is Neo4j's declarative query language for querying and updating graphs. It is similar to SQL but
optimized for graph data.

Example:

MATCH (n:Person {name: 'Alice'}) RETURN n;

Q: How do you match a pattern in Neo4j using Cypher?


A:
The MATCH clause is used to specify patterns in the graph.
Example:

MATCH (p:Person)-[:FRIENDS_WITH]->(f:Person)

RETURN p.name, f.name;

This query finds people (p) and their friends (f).

Q: How can you create nodes and relationships using Cypher?


A:

• Create a node:

• CREATE (p:Person {name: 'Alice', age: 25});

• Create a relationship:

• MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})

• CREATE (a)-[:FRIENDS_WITH]->(b);

Q: Explain the use of RETURN, MATCH, and CREATE in Cypher.


A:
• MATCH: Finds patterns in the graph.

• CREATE: Adds nodes or relationships.

• RETURN: Outputs query results.

3. Graph Traversals

Q: What is a graph traversal in Neo4j?


A:
Graph traversal is the process of visiting nodes and relationships in a graph to extract data. Neo4j
optimizes traversal with its native graph engine.

Q: How can you perform a shortest path query in Neo4j?


A:
Use the shortestPath function:

MATCH p=shortestPath((a:Person {name: 'Alice'})-[:FRIENDS_WITH*]-(b:Person {name: 'Bob'}))

RETURN p;

Q: Explain the purpose of the WITH clause in Cypher.


A:
WITH is used for query chaining and passing intermediate results to subsequent parts of a query. It
allows filtering, aggregation, or sorting before continuing the query.
Example:

MATCH (p:Person)-[:FRIENDS_WITH]->(f:Person)

WITH p, count(f) AS friendsCount

WHERE friendsCount > 2

RETURN p.name, friendsCount;

4. Indexing and Constraints

Q: What are indexes in Neo4j, and how are they created?


A:
Indexes improve the speed of finding nodes or relationships. Create an index using:

CREATE INDEX FOR (p:Person) ON (p.name);

Q: How can you enforce a uniqueness constraint on a property in Neo4j?


A:
Use the CREATE CONSTRAINT clause:

CREATE CONSTRAINT ON (p:Person) ASSERT p.email IS UNIQUE;


Q: What is the benefit of using constraints in a graph database?
A:
Constraints ensure data integrity by enforcing rules like uniqueness or mandatory fields.

5. Advanced Neo4j Concepts

Q: What are graph algorithms, and how are they used in Neo4j?
A:
Graph algorithms analyze relationships and structures in the graph to uncover insights like shortest
paths, centrality, and community detection. They are used in use cases like recommendation systems
and fraud detection.

Example:
The PageRank algorithm measures the importance of nodes in a network.

Q: Explain the use of labels in Neo4j.


A:
Labels categorize nodes into types. For example, a node can have the label Person to indicate it
represents a person.

Q: What is the purpose of APOC (Advanced Procedures On Cypher)?


A:
APOC is a library of procedures and functions for advanced graph processing. It includes utilities for data
import/export, graph algorithms, and data transformation.

Q: How does Neo4j handle ACID compliance?


A:
Neo4j supports ACID (Atomicity, Consistency, Isolation, Durability) compliance by ensuring transaction
safety, data consistency, and recovery from failures.

6. Integration and Performance

Q: How can Neo4j be integrated with other programming languages?


A:
Neo4j provides official drivers for popular languages like Java, Python, and JavaScript. Integration can be
achieved using REST APIs or the Bolt protocol.

Q: What are some best practices for optimizing Cypher queries?


A:

• Use indexes for faster lookups.

• Avoid Cartesian products by using the WITH clause for filtering.

• Minimize the use of MATCH without specific patterns.


Q: How does Neo4j ensure scalability and performance?
A:
Neo4j scales through horizontal sharding and clustering. It also uses an optimized traversal engine and
caches to ensure high performance for complex graph queries.

You might also like