Prepare Interview

Exams Attended

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address
Check our LIVE MOCK INTERVIEWS

Kotlin Interview Questions and Answers

Intermediate / 1 to 5 years experienced level questions & answers

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

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,

// KOTLIN
fun main(args: Array) {
var sample : String? = null
str!!.length
}

The above code snippet gives the following output:-

Exception in thread "main" kotlin.KotlinNullPointerException

Is it helpful? Add Comment View Comments
 

Ques 2. Differentiate between Kotlin and Java.

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.

Is it helpful? Add Comment View Comments
 

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

  • 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, 

// KOTLIN
fun main(args: Array) {
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: 1
The 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,
// KOTLIN
fun main(args: Array) {
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: 1
The 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.

Is it helpful? Add Comment View Comments
 

Ques 4. Differentiate between open and public keywords in Kotlin.

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.

Is it helpful? Add Comment View Comments
 

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

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,

// KOTLIN
fun main(args: Array) {
var temp = "Interview"
when(temp) {
"Interview" -> println("Without Book is the solution.")
"Job" -> println("Interview is the solution.")
"Success" -> println("Hard Work is the solution.")
}
}

Output:-

Without Book 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, “Without Book is the solution” is printed.

Is it helpful? Add Comment View Comments
 

Most helpful rated by users:

Related interview subjects

JUnit interview questions and answers - Total 24 questions
Spring Framework interview questions and answers - Total 53 questions
Java Design Patterns interview questions and answers - Total 15 questions
Java 17 interview questions and answers - Total 20 questions
Core Java interview questions and answers - Total 306 questions
Tomcat interview questions and answers - Total 16 questions
Apache Wicket interview questions and answers - Total 26 questions
Java Applet interview questions and answers - Total 29 questions
JAXB interview questions and answers - Total 18 questions
JMS interview questions and answers - Total 64 questions
Log4j interview questions and answers - Total 35 questions
Struts interview questions and answers - Total 84 questions
RMI interview questions and answers - Total 31 questions
Apache Camel interview questions and answers - Total 20 questions
JDBC interview questions and answers - Total 27 questions
Java 11 interview questions and answers - Total 24 questions
JPA interview questions and answers - Total 41 questions
EJB interview questions and answers - Total 80 questions
GWT interview questions and answers - Total 27 questions
Kotlin interview questions and answers - Total 30 questions
Glassfish interview questions and answers - Total 8 questions
Google Gson interview questions and answers - Total 8 questions
Java 21 interview questions and answers - Total 21 questions
JSP interview questions and answers - Total 49 questions
J2EE interview questions and answers - Total 25 questions
Apache Tapestry interview questions and answers - Total 9 questions
Java Swing interview questions and answers - Total 27 questions
Java Mail interview questions and answers - Total 27 questions
Hibernate interview questions and answers - Total 52 questions
JSF interview questions and answers - Total 24 questions
Java 8 interview questions and answers - Total 30 questions
Java 15 interview questions and answers - Total 16 questions
JBoss interview questions and answers - Total 14 questions
Web Services interview questions and answers - Total 10 questions
RichFaces interview questions and answers - Total 26 questions
Servlets interview questions and answers - Total 34 questions
Java Beans interview questions and answers - Total 57 questions
Spring Boot interview questions and answers - Total 50 questions
©2023 WithoutBook