InterviewSolution
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:-
|
|
| 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.CompanionObjectNameWe 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.CompanionAll 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 BitExplanation:- 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 :
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
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
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:
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: 2Explanation - 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.
Output:- The first parameter value is: 1The second parameter value is: 2The 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:-
|
||||||||||||||||||||||||||||
| 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 nullElvis 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 errorIf 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 errorKotlin 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:
To ensure consistency, data classes must meet the following requirements:
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:-
The syntax is as follows : val variableName = valueFor example, val sample = "interview"sample = "interviewbit" // results in compile time errorThe 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 errorThe above code snippet runs fine and does not produce any errors.
The syntax is as follows : var variableName = valueFor example, var sample = "interview"sample = "FUN" // no compile time errorThe 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 -
Floating Point Data Type -
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.
Character Data Type - Small letters (a-z), capital letters (A-Z), numerals (0-9), and other symbols are represented by the character data type.
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. |
|||||||||||||||||||||||||