Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

What are the advantages of Kotlin over Java?

Answer»

Following are the advantages of Kotlin over Java:-

  • Data class: In Java, you must create getters and SETTERS for each object, as well as properly write hashCode (or allow the IDE to build it for you, which you must do every time you update the class), TOSTRING, and equals. Alternatively, you could utilize lombok, but that has its own set of issues. In Kotlin, data classes take care of everything.
  • Patterns of getter and setter: In Java, for each variable, you use it for, rewrite the getter and setter methods. You don't have to write getter and setter in kotlin, and if you must, custom getter and setter take a lot less typing. There are ADDITIONAL delegates for identical getters and setters.
  • Extension Functions: In Java, there is no support for extension functions. Kotlin on the other hand provides support for extension functions which makes the code more clear and cleaner.
  • Support for one common codebase: You may extract one common codebase that will TARGET all of them at the same time using the Kotlin Multi-Platform framework.
  • Support for Null Safety: Kotlin has built-in null safety support, which is a lifesaver, especially on Android, which is full of old Java-style APIs.
  • Less prone to errors: There is less space for error because it is more CONCISE and expressive than Java.
2.

Explain about the “when” keyword in the context of Kotlin.

Answer»

The “when” keyword is used in Kotlin to substitute the switch operator in other languages such as Java. When a certain condition is met, a specific BLOCK of code must be run. Inside the when expression, it compares all of the branches one by one until a match is discovered. After finding the first match, it proceeds to the conclusion of the when block and executes the code immediately following the when block. We do not need a break STATEMENT at the end of each CASE, unlike switch cases in Java or any other programming language.

For example,

// KOTLINfun main(args: Array<String>) { var temp = "Interview" when(temp) { "Interview" -> println("Interview Bit is the solution.") "Job" -> println("Interview is the solution.") "SUCCESS" -> println("Hard Work is the solution.") }}

Output:-

Interview Bit is the solution.

Explanation:- In the above code, the variable temp has the VALUE “Interview”. The when condition matches for the exact value as that of temp’s and executes the corresponding code statements. Thus, “Interview Bit is the solution” is printed.

3.

Differentiate between open and public keywords in Kotlin.

Answer»

The keyword “open” refers to the TERM "open for expansion". The open annotation on a class is the POLAR opposite of the final annotation in Java: it allows others to inherit from it. By default, a class cannot be inherited in Kotlin. In Kotlin, an open method signifies that it can be overridden, whereas it cannot be by default. Instead, any methods in Java can be overridden by default.

In Kotlin, all the CLASSES are final by default. If no visibility modifier is specified, the public is USED by default, which means our declarations will be accessible everywhere inside the program.

4.

What do you understand about Companion Object in the context of Kotlin?

Answer»

In some languages, such as Java, the STATIC keyword is used to declare class members and utilise them without creating an object, i.e. by simply calling them by their class name. In Kotlin, there is nothing called the “static” keyword. So, if we want to achieve the functionality of static member functions, we USE the companion objects. This is also referred to as Object Extension. 

We must use the companion keyword in front of the object definition to construct a companion object.

// Syntax in KOTLINclass CompanionClass { companion object CompanionObjectName { // code }}val obj = CompanionClass.CompanionObjectName

We can also remove the CompanionObject name and replace it with the term companion, resulting in the companion object's default name being Companion, as SHOWN below:

// KOTLINclass CompanionClass { companion object { // code }}val obj = CompanionClass.Companion

All the required static member functions and member variables can be kept INSIDE the companion object created. For example,

class Sample { companion object Test { var a: Int = 1 fun testFunction() = println("Companion Object’s Member FUNCTION called.") }}fun main(args: Array<String>) { println(Sample.a) Sample.testFunction()}

Output:-

1Companion Object’s Member function called.
5.

What do you understand about function extension in the context of Kotlin? Explain.

Answer»

In Kotlin, we can add or delete method functionality using extensions, even without inheriting or ALTERING them. Extensions are statistically resolved. It provides a callable function that may be INVOKED with a dot operation, rather than altering the existing class.

Function Extension - Kotlin ALLOWS users to specify a method outside of the main class via function extension. We'll see how the extension is implemented at the functional level in the following example:

// KOTLINclass Sample { var STR : String = "null" fun printStr() { print(str) } }fun main(args: Array<String>) { var a = Sample() a.str = "Interview" var B = Sample() b.str = "Bit" var c = Sample() c.str = a.add(b) c.printStr()}// function extensionfun Sample.add(a : Sample):String{ var temp = Sample() temp.str = this.str + " " +a.str return temp.str}

Output:-

Interview Bit

Explanation:-

We don't have a method named "addStr" inside the "Sample" class in the preceding example, but we are implementing the same method outside of the class. This is all because of function extension.

6.

How can you concatenate two strings in Kotlin?

Answer»

Following are the different ways by which we can concatenate two STRINGS in Kotlin:

Using String Interpolation:- We use the technique of string interpolation to concatenate the two strings. Basically, we SUBSTITUTE the strings in place of their placeholders in the initialisation of the third string.

VAL s1 = "Interview"val s2 = "Bit"val s3 = "$s1 $s2" // stores "Interview Bit"

Using the + or plus() operator:- We use the ‘+’ operator to concatenate the two strings and store them in a third variable.

val s1 = "Interview"val s2 = "Bit"val s3 = s1 + s2 // stores "InterviewBit"val s4 = s1.plus(s2) // stores "InterviewBit"

Using STRINGBUILDER:- We concatenate two strings using the StringBuilder object. First, we append the first string and then the second string. 

val s1 = "Interview"val s2 = "Bit"val s3 =  StringBuilder()    s3.append(s1).append(s2)val s4 = s3.toString() // stores "InterviewBit"
7.

Explain the various methods to iterate over any data structure in Kotlin with examples.

Answer»

Following are the different WAYS to iterate over any data structure in Kotlin :

  • For Loop - The for loop is used to scan any data structure that SUPPLIES an iterator in this case. It is not used in the same way as the for loop in other programming languages such as Java or C.

In Kotlin, the for loop has the following Syntax:

for(item in collection) { // code }

Here, collection refers to the data structure to be iterated and item refers to each element of the data structure.

For example,

// KOTLINfun main(args: Array<String>) { var numbersArray = arrayOf(1,2,3,4,5,6,7,8,9,10) for (num in numbersArray){ if(num % 2 == 0){ print("$num ") } }}

Output -

2 4 6 8 10
  • While Loop - It is made up of a code block and a condition to be checked for each iteration. First, the while condition is assessed, and if it is true, the code within the block is executed. Because the condition is verified every time before entering the block, it repeats until the condition turns false. The while loop can be thought of as a series of if statements that are repeated.

The while loop's syntax is as follows:

while(condition) { // code }

For example,

// KOTLINfun main(args: Array<String>) { var number = 1 while(number <= 5) { PRINTLN(number) number++; }}

Output -

12345
  • Do While Loop - The condition is assessed after all of the statements inside the block have been executed. If the do-while condition is true, the code block is re-executed. As long as the expression evaluates to true, the code block EXECUTION procedure is repeated. The loop ends if the expression becomes false, and control is passed to the sentence following the do-while loop. Because it verifies the condition after the block is executed, it's also KNOWN as a post-test loop.

The do-while loop's syntax is as follows:

do { // code {while(condition)

For example,

// KOTLINfun main(args: Array<String>) { var number = 4 var sum = 0 do { sum += number number-- }while(number > 0) println("Sum of first four natural numbers is $sum")}

Output -

Sum of first four natural numbers is 10
8.

What are the different types of constructors available in Kotlin? Explain them with proper examples.

Answer»

<P>There are two types of Kotlin constructors:

  • Primary Constructor  - This type of constructor is initialised in the class header and is provided after the class name. It is declared using the “constructor” keyword. Parameters are optional in this type of constructor. For example,
class Sample constructor(val a: Int, val b: Int) { // code}

If no annotations or ACCESS modifiers are provided, the constructor keyword can be omitted. The initialization code can be placed in a separate initializer block prefixed with the init keyword because the primary constructor cannot contain any code. 

For example, 

// KOTLINfun main(args: Array<String>) { val s1 = Sample(1, 2)}class Sample(a : Int , b: Int) { val p: Int var q: Int // initializer block init { p = a q = b println("The first parameter value is : $p") println("The second parameter value is : $q") }}

Output:-

The first parameter value is: 1The second parameter value is: 2

Explanation - The values 1 and 2 are SUPPLIED to the constructor arguments a and b when the object s1 is created for the class Sample. In the class p and q, two attributes are specified. The initializer block is called when an object is created, and it not only sets up the attributes but also PRINTS them to the standard output.

  • Secondary Constructor - Secondary constructors allow for the initialization of variables as well as the addition of logic to the class. They have the constructor keyword prefixed to them. For example,
// KOTLINfun main(args: Array<String>) { val s1 = Sample(1, 2)}class Sample { constructor(a: Int, b: Int) { println("The first parameter value is : $p") println("The second parameter value is : $q") }}

Output:-

The first parameter value is: 1The second parameter value is: 2

The compiler determines which secondary constructor will be called based on the inputs provided. We don't specify which constructor to use in the above program, so the compiler chooses for us.

In Kotlin, a class can contain one or more secondary constructors and at most one primary constructor. The primary constructor INITIALIZES the class, while the secondary constructor initialises the class and adds some additional logic.

9.

Differentiate between Kotlin and Java.

Answer»

Following are the differences between Kotlin and Java:-

BasisKotlinJava
Null SafetyBy default, all sorts of variables in Kotlin are non-nullable (that is, we can't assign null values to any variables or objects). Kotlin code will fail to build if we try to assign or return null values. If we absolutely want a null value for a variable, we can declare it as follows: value num: Int? = null NullPointerExceptions are a big source of annoyance for Java developers. Users can assign null to any variable, however, when accessing an object reference with a null value, a null pointer exception is thrown, which the user must manage.
Coroutines Support We can perform long-running expensive tasks in SEVERAL threads in Kotlin, but we also have coroutines support, which halt execution at a GIVEN moment without blocking threads while doing long-running demanding operations.The corresponding thread in Java will be blocked anytime we launch a long-running network I/0 or CPU-intensive task. Android is a single-threaded operating system by default. Java allows you to create and execute numerous threads in the background, but managing them is a difficult operation.
Data Classes If we need to have data-holding classes in Kotlin, we may define a class with the keyword "data" in the class declaration, and the COMPILER will take care of everything, including constructing constructors, getter, and setter methods for VARIOUS fields.Let's say we need a class in Java that only holds data and nothing else. Constructors, variables to store data, getter and setter methods, hashcode(), function toString(), and equals() functions are all required to be written explicitly by the developer.
Functional ProgrammingKotlin is procedural and functional programming (a programming paradigm where we aim to bind everything in functional units) language that has numerous useful features such as lambda expressions, operator overloading, higher-order functions, and lazy evaluation, among others.Java does not allow functional programming until Java 8, however it does support a subset of Java 8 features when developing Android apps.
Extension FunctionsKotlin gives developers the ability to add new functionality to an existing class. By prefixing the name of a class to the name of the new function, we can build extended functions.In Java, we must create a new class and inherit the parent class if we want to enhance the functionality of an existing class. As a result, Java does not have any extension functions.
Data Type Inference We don't have to declare the type of each variable based on the assignment it will handle in Kotlin. We can specify explicitly if we want to.When declaring variables in Java, we must declare the type of each variable explicitly.
Smart CastingSmart casts in Kotlin will take care of these casting checks with the keyword "is-checks," which checks for immutable values and conducts implicit casting.We must examine the type of variables in Java and cast them appropriately for our operation.
CHECKED ExceptionsWe don't have checked exceptions in Kotlin. As a result, developers do not need to declare or catch exceptions, which has both benefits and drawbacks.We have checked exceptions support in Java, which enables developers to declare and catch exceptions, resulting in more robust code with better error handling.
10.

Explain Safe call, Elvis and Not Null Assertion operator in the context of Kotlin.

Answer»

Safe Call operator ( ?. ) -  Null comparisons are trivial, but the number of nested if-else expressions can be EXHAUSTING. So, in Kotlin, there's a Safe call operator,?, that simplifies things by only doing an action when a specified reference holds a non-null value. It allows us to use a single expression to perform both a null CHECK and a method call.

For example,

The following expression in Kotlin

name?.toLowerCase()

is equivalent to the following

if(name != null)  name.toLowerCase()else null

Elvis Operator ( ?: ) - When the original variable is null, the Elvis operator is used to return a non-null value or a default value. In other words, the elvis operator returns the left expression if it is not null, otherwise, it yields the right expression. Only if the left-hand side expression is null is the right-hand side evaluated. 

For example,

The following expression in Kotlin

val sample1 = sample2 ?: "Undefined"

is equivalent to the following

val sample1 = if(sample2 != null)  sample2 else  "Undefined"

Furthermore, on the right side of the Elvis operator, we may use throw and return expressions, which is particularly handy in functions. As a result, instead of returning a default value on the right side of the Elvis operator, we can throw an exception. For example,

val sample1 = sample2 ?: throw IllegalArgumentException("Invalid")

Not Null Assertion Operator ( !! ) - If the value is null, the not null assertion (!!) operator changes it to a non-null type and throws an exception.

Anyone who wants a NullPointerException can ask for it explicitly with this operator.

For example,

// KOTLINfun main(args: Array<String>) { var sample : String? = null str!!.length}

The above CODE snippet gives the following OUTPUT:-

Exception in THREAD "main" kotlin.KotlinNullPointerException
11.

Explain the concept of null safety in Kotlin.

Answer»

Kotlin's type system aims to eradicate null REFERENCES from the code. If a program throws NullPointerExceptions at runtime it might result in application failure or system crashes. If the Kotlin compiler finds a null REFERENCE it throws a NullPointerException.

The Kotlin type system distinguishes between references that can hold null (nullable references) and those that cannot (non-null references). Null cannot be stored in a String variable. We get a compiler error if we try to assign null to the variable. 

var a: String = "interview"a = null // results in compilation error

If we want the above string to be ABLE to hold null value as well, we can declare it of type nullable using the ‘?’ operator after the String keyword as follows :

var a: String? = "interview"a = null // no compilation error

Kotlin PROVIDES Safe Call (?.), Elvis (?:) and Not Null Assertion (!!) operators which define what needs to be done in case of a null encounter. This makes the code more reliable and less prone to errors. Thus, Kotlin ENFORCES null safety by having nullable, non-nullable type variables and the different operators to tackle null encounters.

12.

What are data classes in Kotlin? Explain with a proper example.

Answer»

The Data class is a simple class that holds data and PROVIDES typical functions. To declare a class as a data class, use the data keyword. 

Syntax:

data class className ( list_of_parameters)

The following functions are automatically derived by the COMPILER for the data classes:

  • equals() - The equals() function returns true if two objects have the identical CONTENTS. It operates similarly to "==," ALTHOUGH for Float and Double values it works differently.
  • hashCode() - The hashCode() function returns the object's hashcode value.
  • copy() - The copy() function is used to DUPLICATE an object, changing only a few of its characteristics while leaving the rest unaltered.
  • toString() - This function returns a string containing all of the data class's parameters.

To ensure consistency, data classes must meet the following requirements:

  • At least one parameter is required for the primary constructor.
  • val or var must be used for all primary constructor parameters.
  • Abstract, open, sealed, or inner data classes are not possible.
  • Only interfaces may be implemented by data classes.

Example:

data class Sample(var input1 : Int, var input2 : Int)

The above code snippet creates a data class Sample with two parameters.

fun main(agrs: Array<String>) { val temp = Sample(1, 2) println(temp) } 

Here, we create an instance of the data class Sample and pass the parameters to it.

Output:-

Sample(input1=1, input2=2)
13.

How are variables declared in Kotlin? What are the different types of variables in Kotlin? Explain with examples.

Answer»

Every variable in Kotlin must be declared before it can be USED. An attempt to use a variable without declaring it results in a syntax error. The type of data you are authorised to put in the memory ADDRESS is determined by the variable type declaration. The type of variable can be determined from the initialised value in the case of local variables.

For example,

var site = "interviewbit"

The above code declares a variable “site” of type String because the value with which the variable is initialised is a String.

There are broadly two types of variables in Kotlin. They are as follows:-

  • Immutable Variables — Immutable variables are also known as read-only variables. They are declared using the val keyword. Once these variables have been declared, we cannot change their values.

The syntax is as follows :

val variableName = value

For example,

val sample = "interview"sample = "interviewbit" // results in compile time error

The second line in the above code SNIPPET would RESULT in a compile-time error as expected.

Because it can be initialized with the value of a variable, an immutable variable is not a constant. It means that the value of an immutable variable does not need to be known at compile-time and that if it is defined inside a construct that is called several times, it can take on a different value with each function call. For example, 

var sample = "interview"val newSample = sample // no compile time error

The above code snippet runs fine and does not produce any errors.

  • Mutable Variables - In a mutable variable, the value of the variable can be changed. We use the keyword “var” to declare such variables.

The syntax is as follows :

var variableName = value

For example,

var sample = "interview"sample = "FUN" // no compile time error

The above code snippet runs fine and does not produce any errors.

14.

What are the various data types available in Kotlin? Explain them.

Answer»

Primitive data types are the most BASIC data types in Kotlin, and all others are reference types like array and string. Kotlin contains all data types as objects. FOLLOWING are the different data types available in Kotlin:-

Integer Data Type -

Data TypeSpace Required
byte8 bits
short16 bits
int32 bits
long64 bits

Floating Point Data Type - 

Data TypeSpace Required
float32 bits
double64 bits

BOOLEAN Data Type - 

True or false is the only bit of information represented by the Boolean data type. In Kotlin, the Boolean type is the same as in Java. 

Data TypeSpace Required
boolean1 bit

Character Data Type - 

Small letters (a-z), capital letters (A-Z), numerals (0-9), and other symbols are represented by the character data type.

Data TypeSpace Required
char8 bits

String Data Type -

Strings are represented in Kotlin by the type String. A string value is OFTEN a sequence of characters enclosed in double quotations ("). The space required in this CASE depends on the number of characters in the string.

Array Data Type -

The Array class in Kotlin is used to represent arrays. It has the get and set functions that, due to operator overloading conventions, can be used as  ‘[]’  as well. The space required by the array also depends on the number of elements it posses.