Kotlin Programming Interview Questions and Answers PDF Download

Kotlin-Interview-Questions-and-Answers

Kotlin Programming Interview Questions and Answers PDF Download: Dear users, In this article we have provided latest Kotlin interview questions and answers for freshers and experienced candidates. You can either download the Kotlin programming FAQ’s in PDF format through the below provided download link or you can read it online through this article. Bookmark (Ctrl+D) this page for future reference and keep visiting freshersnow.com for latest and frequently asked job interview questions.



★★ You can also check: Latest Technical Interview Questions ★★

Contents

Latest Kotlin Interview Questions and Answers

1. What is Kotlin?

Kotlin is a static type, object-oriented programing (OOP) language that is interoperable with the Java virtual machine, Java libraries, and Android. Kotlin saves time for developers as the less verbose language provides briefer and less redundant code. Kotlin can be compiled into JavaScript or an LLVM encoder.

2. How do you declare variables in Kotlin? How does the declaration differ from the Java counterpart?

There are two major differences between Java and Kotlin variable declaration:



The type of declaration in Java the declaration :

String s = "Java String";
int x = 10;

In Kotlin the declaration looks like:

val s: String = "Hi"
var x = 5

In Kotlin, the declaration begins with a value and a var followed by the optional type. Kotlin can automatically detect the type using type inference.

Default value
The following is possible in Java: String s:

The following variable declaration in Kotlin is not valid. val s: String

3. How does string interpolation work in Kotlin? Explain with a code snippet?

String interpolation is used to evaluate string templates. We use the symbol $ to add variables inside a string.

Example

val name = "Journaldev.com"
val desc = "$name now has Kotlin Interview Questions too. ${name.length}"
Using {}

4. What are the Features of Kotlin?

  • Concise: Kotlin is concise than Java, you would need to write approx 40% fewer lines of code compared to Java.
  • Interoperability: Kotlin is highly interoperable with Java and there is no difficulty using Kotlin in a Java project.
  • Open Source: The Kotlin is an open source programming language.
  • Trust: You can trust Kotlin as this is developed by a popular and well-known company JetBrains. JetBrains is known for creating several development tools and the popular Java IDE IntelliJ IDEA is developed by this same company.
  • Feature-rich: The Kotlin provides several advanced features such as Operator overloading, Lambda expressions, string templates, etc.
  • Easy: Kotlin is easy to learn programming language. If you have come from a Java background, you would find it easy to learn Kotlin.
  • Less error-prone: As I mentioned in the beginning, Kotlin is a statically-typed the programming language, which makes you able to catch errors at compile-time as Statically typed programming languages do type checking at compile-time.

5. How to compare two strings in Kotlin?

Compares string in Kotlin are possible in the following ways:

Using “==” operator:
You can use ah operator for comparison of two string. In Kotlin == operator is used.

Using compareTo() extension function

Syntax

fun String.compareTo(
other: String,
ignoreCase: Boolean = false
): Int

Example

Java
fun main(args: Array & lt; String & gt;) {
val x: String = "Kotlin is  simple"
val y: String = "Kotlin language is" + " easy"
if (x == y) {
println(" x and y are similar.")
} else {
println(" x and y are not similar.")
}
}

6. Give me the name of the extension methods Kotlin provides to java.io.File?

bufferedReader(): Use for reading contents of a file into BufferedReader
readBytes() : Use for reading contents of file to ByteArray
readText(): Use of reading contents of a file to a single String
forEachLine(): Use for reading a file line by line in Kotlin
readLines(): Use to reading lines in the file to List

7. What is the entry point to a Kotlin program? Provide an example?

Like most of the other procedural languages, the main() function is the entry point to a Kotlin program.

fun main(args: Array<String>) {
    val user1 = User(name="Yogi", age=27)
    printUser(user1)
}
fun printUser(user: User){
    println(user)
}
data class User(val name: String, val age: Int);

8. How do you check if two Strings are equal valued?

Using == (double equal to) operator.

fun main(args: Array<String>) {
    val a: String = "kotlin is easy"
    val b: String = "kotlin is" + " easy"
    if(a==b){
        println(" a and b are equal.")
    } else {
        println(" a and b are not equal.")
    }
}

9. What are TabLayout and it’s Class declaration?

TabLayout provides a horizontal layout to display tabs. We can create sliding and nonsliding tabs and display more screens on a single screen using tabs.

Class Declaration:

public class TabLayout extends HorizontalScrollView
XML Declaration: 
<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    app:tabGravity="fill"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/colorAccent"
    app:tabIndicatorColor="#1c1c1d"
    />

10. Explain about types of Functions in Kotlin?

There are two types of functions:

1.Kotlin Standard Library Function

Standard library functions are built-in functions in Kotlin that are readily available for use.

Example

fun main(args: Array<String>) {
    var number = 5.5
    print("Result = ${Math.sqrt(number)}")
}

Output:

Result = 2.345207879911715

2. User-defined functions

As mentioned, you can create functions yourself. Such functions are called user-defined functions. Before you can use (call) a function, you need to define it.

Example

define a function in Kotlin:
fun callMe() {
    // function body
}

10. Which are Kotlin Visibility Modifiers Inside Package?

A package organizes a set of related functions, properties and classes, objects, and interfaces.

ModifierDescription
publicdeclarations are visible everywhere
privatevisible inside the file containing the declaration
internalvisible inside the same module
protectednot available for packages

11. Why is Kotlin preferred over Java?

Kotlin use the easy coding process as it is simpler than Java and has many features required, that is not provided by Java yet like Extension functions, Null Safety, range expressions, etc. In the Kotlin, we can code approximately 40% less number of code lines as compared with Java.

12. State the advantages of Kotlin?

Advantages:

  • Kotlin is easy and simple to learn as its syntax is similar to that of Java.
  • It is the functional language that is based on JVM (Java Virtual Machine), which removes the boilerplate codes.
  • Kotlin is considered as an expressive language that is easily readable and understandable and the performance is substantially good.
  • It can be used by any desktop, web server or mobile based applications.

13. Write a program of Lambda function: addition of two numbers?

fun main(args: Array<String>){  
    val myLambda: (Int) -> Unit= {s: Int -> println(s) } //lambda function  
    addNumber(5,10,myLambda)  
}  
fun addNumber(a: Int, b: Int, mylambda: (Int) -> Unit ){   //high level function lambda as parameter  
    val add = a + b  
    mylambda(add) // println(add)  
}

Output:
15

14. Write about Kotlin Architecture?

Kotlin compiler will work differently, whenever it is targeting different another kind of languages such as Java and JavaScript. Kotlin compiler creates a byte code and that byte code can run on the JVM, it is exactly equal to the byte code generated by the Java .class file.

kotlin-architecture

 

15. What are platforms that support Kotlin Programming Language?

Following are the platforms which support Kotlin programming language

  • iOS (arm32, arm64, emulator x86_64) MacOS (x86_64)
  • Android (arm32, arm64)
  • Windows (MinGW x86_64)
  • Linux (x86_64, arm32, MIPS, MIPS little endian)
  • web assembly (wasm32)

16. What is Kotlin delegation?

Kotlin supports the “delegation” design pattern by introducing a new keyword “by”. Using the keyword or delegation methodology. Kotlin allows the derived class to access all of the implemented public methods of an interface through a specific object.

Example

Live Demo
interface Base {
   fun printMe() //abstract method
}
class BaseImpl(val x: Int) : Base {
   override fun printMe() { println(x) }   //implementation of the method
}
class Derived(b: Base) : Base by b  // delegating the public method on the object b

fun main(args: Array<String>) {
   val b = BaseImpl(10)
   Derived(b).printMe() // prints 10 :: accessing the printMe() method 
}

Output
10

17. What are inline functions in Kotlin?

In case if you have a functioned without a class but on compile time Kotlin compiler converts the function, make a static object for it and then call that function by an anonymous class the anonymous instance which causes extra memory consumption. To come over it inline keyword is used, it copies the code into a class which is calling this method and our method behaves as a member of class calling it.

18. Why can a developer prefer Kotlin over Java?

Because the Kotlin has several features which even modern versions of Java lack.

  • Kotlin supports the best features of functional programming and OO programming language.
  • Kotlin handles Null Pointer Exceptions easily.
  • Kotlin support lambdas, higher order functions, smart casting.
  • Approximately 40 % fewer number of code lines as compared to Java.

19. Explain about Getters and Setters in Kotlin?

Kotlin has internally generated a default getter and setter for mutable properties, and a getter (only) for read-only properties. This calls these getters and setters internally whenever you access or modify a property using the dot(.) notation.

Example

class User(_id: Int, _name: String, _age: Int) {
    val id: Int = _id
        get() = field
    
    var name: String = _name
        get() = field
        set(value) {
            field = value
        }
    
    var age: Int = _age
        get() = field
        set(value) {
            field = value
        }
}

20. What is the difference between the Java class and the kotlin data class?

The Kotlin language introduced the concept of Data Classes, which represent simple classes used as data containers. As the name indicates it is used to only store data and contains no other business logic.

Example

public class Employee {

  private String empName;
  private int empId;

  public String getEmpName() {
    return empName;
  }

  public void setEmpName(String empName) {
    this.empName = empName;
  }

  public int getEmpId() {
    return empId;
  }

  public void setEmpId(int empId) {
    this.empId = empId;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + empId;
    result = prime * result + ((empName == null) ? 0 : empName.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Employee other = (Employee) obj;
    if (empId != other.empId)
      return false;
    if (empName == null) {
      if (other.empName != null)
        return false;
    } else if (!empName.equals(other.empName))
      return false;
    return true;
  }
}

21. How to declare a sealed class?

Just put the sealed modifier before the name of the class.

Example

sealed class Car {
    data class Maruti(val speed: Int) : Car()
    data class Bugatti(val speed: Int, val boost: Int) : Car()
    object NotACar : Car()

}

The benefit of using sealed classes comes into play when you use them in an expression.

22. Write about the Kotlin Property Initialization?

To initialize a property in the constructor, there are two important ways of property initialization in Kotlin.

  • lateinit
  • lazy

Generally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient.

Example

public class Test {
  lateinit var mock: Mock
  @SetUp fun setup() {
     mock = Mock()
  }
  @Test fun test() {
     mock.do()
  }
}

The lazy() function that takes a lambda and returns an instance of lazy which can serve as a delegate for implementing a lazy property.

Example

public class Example{
  val name: String by lazy { “Amit Shekhar” }
}

23. What is Ranges operator in Kotlin?

Ranges operator helps to iterate through a range. Its operator forms are (..)).

Example

for (i in 1..4)
print(i)

24. What is Null Safety in Kotlin?

Kotlin it handles Null Pointer Exceptions and used to eliminate the risk of occurrence of NullPointerException in real-time.

The ways to handle Null Safety –

1. Checks for null in conditions
2. Use Safe Call Operator (?.)
3. Use Elvis Operator (?:)

Example

fun main(args: Array){
  // variable is declared as non-null by default
  var str: String = "Hi, Anil!"

  // kotlin prevents you assign a null to a non-nullable variable
  // str=null //assing null to a causes complilation error
  println("str is : $str") 

  // variable is declared as nullable
  var str1: String? = "Hi, Anil!"    
  println("str1 is : $str1")
  str1 = null
  println("str1 is : $str1")
}

25. Why use Kotlin for Android Development?

Three very important points are as follows:

Concise: Drastically reduce the amount of boilerplate code you need to write.
Safe: It avoid entire classes of errors such as null pointer exceptions.
Interoperable: The Leverage existing frameworks and libraries of the JVM with 100% Java Interoperability.

26. Why there is a need for Kotlin Coroutines?

When we call the fetchAndShowUser function, it will throw the NetworkOnMainThreadException as the network call is not allowed on the main thread.

Example

fun fetchUser(): User {
    // make network call
    // return user
}

fun showUser(user: User) {
    // show user
}

fun fetchAndShowUser() {
    val user = fetchUser()
    showUser(user)
}

27. Why Use Kotlin?

1. Kotlin is quite simple and safe compared to Java
2. Kotlin is open-source
3. Supports OOPs object-oriented programming
4. Kotlin compiles to bytecode
5. Kotlin used for server-side development
6. Kotlin used for Android apps development also
7. Kotlin is multi-platform

28. What are Coroutines in Kotlin and define?

Coroutines are the lightweight thread in Kotlin that convert async callbacks for long-running tasks, such as a database or network access, into sequential code.

Example

coroutine {
    progress.visibility = View.VISIBLE
 
    val user = suspended { userService.doLogin(username, password) }
    val currentFriends = suspended { userService.requestCurrentFriends(user) }
 
    val finalUser = user.copy(friends = currentFriends)
    toast("User ${finalUser.name} has ${finalUser.friends.size} friends")
 
    progress.visibility = View.GONE
}

29. What is Elvis operator?

The Elvis operator in the Kotlin is an operator that receives two inputs and returns the first argument if it is non-null or the second one otherwise

  • It is represented by a question mark followed by a colon ?:
  • It is a variant of the ternary conditional operator but for null-safety checking

Example

x ?: y // yields `x` if `x` is not null, `y` otherwise.

30. What are Kotlin array basic operations?

val num = arrayOf(1, 2, 3, 4, 5)  // array is created

println(Arrays.toString(num))  // to print contents of the array using toString method from Arrays class

val num2 = num.plus(1) // creating a new array by adding 1 element to existing array.

val slice = num.sliceArray(1..3)  // it will display slice from array...i.e (2,3,4) from array num

num.first() // get first element of the array..it means 1 from array num
num.last()  // get last element of the array..it means 5 from array num

num.sum() // sum of the elements in array: 15

val soertNum = num.sortedArray() // sort the array
val sortNumsDesc = num.sortedArrayDescending()

println("Size is ${num.size}") // to print size of the array

Converting Generic Array to Primitive Array using to IntArray

val array1 = arrayOf(1,2,3,4)
var intArray1 : IntArray = array1.toIntArray()

Download Latest Kotlin Interview Questions & Answers in PDF Format: Click Here

LEAVE A REPLY

Please enter your comment!
Please enter your name here