webounstraininghub.in

Edit Content
Click on the Edit Content button to edit/add the content.

Elevate Your Code with Kotlin's Concise Syntax

Sharpen Skills, Ace Interviews

Kotlin : Backend Development Interview Questions

Kotlin is a statically typed programming language that runs on the JVM and is fully interoperable with Java. It's preferred for Android development because it reduces boilerplate code, provides null safety, and offers modern language features that enhance productivity.

Key features include null safety, extension functions, lambdas, smart casts, higher-order functions, and data classes.

Kotlin's type system aims to eliminate null pointer exceptions by differentiating between nullable and non-nullable types. Nullable types are declared with a ?, and the compiler ensures that null checks are handled.

val is used to declare read-only variables (immutable), while var is used for mutable variables that can be reassigned.

Kotlin allows you to specify default values for function parameters. If a parameter is not provided when the function is called, the default value is used.

Extension functions allow you to add new functions to existing classes without modifying their source code. They are declared using the class name followed by a dot and the function name.

A data class is a special class in Kotlin that is used to hold data. It automatically provides implementations for methods like equals(), hashCode(), and toString() based on the primary constructor parameters.

Coroutines are a concurrency design pattern in Kotlin that allows you to write asynchronous code sequentially. They are lightweight threads that help in performing long-running tasks without blocking the main thread.

The object keyword is used to declare a singleton, an object declaration that is instantiated only once in the program. It can also be used to create anonymous inner classes and companion objects.

These are scope functions that allow you to work with an object in a concise way:

  • apply: Executes a block of code on the object and returns the object itself.
  • let: Executes a block of code on the object and returns the result of the block.
  • run: Combines the functionality of let and apply.
  • also: Similar to apply, but returns the object and is used for side effects.

Kotlin uses is for type checks and smart casts automatically cast a variable to the target type within a condition. The as keyword is used for explicit casting.

== checks for structural equality (similar to equals() in Java), whereas === checks for referential equality (i.e., whether two references point to the same object).

A sealed class is a restricted class hierarchy that allows you to represent restricted class hierarchies. It ensures that all subclasses are known at compile-time, making it ideal for representing a fixed set of types.

A lambda expression is an anonymous function that can be treated as a value. It can be passed as an argument, returned from a function, or assigned to a variable.

Kotlin supports functional programming through higher-order functions, lambdas, and inline functions. It allows functions to be passed as arguments, returned as values, and stored in variables.

A companion object allows you to define methods and properties that belong to a class but do not require an instance of the class to be accessed. It is similar to static members in Java.

Kotlin encourages immutability by using val for read-only variables and providing immutable collections like List, Set, and Map. The language promotes functional programming practices that avoid mutable state.

Array is a fixed-size, mutable collection of elements, while List is an immutable collection (by default) with no fixed size. List has both mutable (MutableList) and immutable versions.

Delegation in Kotlin allows you to delegate the implementation of a class or interface to another class or object. This is commonly used with properties, where the getter and setter methods are delegated to another object.

Kotlin uses try, catch, and finally blocks to handle exceptions. It also provides the throw keyword to manually throw an exception. Unlike Java, Kotlin does not require exceptions to be declared or caught explicitly (no checked exceptions).

fun factorial(n: Int): Int {
return if (n == 1) n else n * factorial(n - 1)
}

fun main() {
println(factorial(5)) // Output: 120
}
fun isPrime(n: Int): Boolean {
if (n <= 1) return false
for (i in 2..n / 2) {
if (n % i == 0) return false
}
return true
}

fun main() {
println(isPrime(11)) // Output: true
}
fun reverseString(s: String): String {
return s.reversed()
}

fun main() {
println(reverseString("hello")) // Output: "olleh"
}
fun isPalindrome(s: String): Boolean {
return s == s.reversed()
}

fun main() {
println(isPalindrome("racecar")) // Output: true
}
fun findMax(arr: Array<Int>): Int {
return arr.maxOrNull() ?: throw IllegalArgumentException("Array is empty")
}

fun main() {
println(findMax(arrayOf(1, 2, 3, 4, 5))) // Output: 5
}
fun sumArray(arr: Array<Int>): Int {
return arr.sum()
}

fun main() {
println(sumArray(arrayOf(1, 2, 3, 4, 5))) // Output: 15
}
fun gcd(a: Int, b: Int): Int {
return if (b == 0) a else gcd(b, a % b)
}

fun main() {
println(gcd(56, 98)) // Output: 14
}
fun power(base: Int, exp: Int): Int {
return if (exp == 0) 1 else base * power(base, exp - 1)
}

fun main() {
println(power(2, 3)) // Output: 8
}
fun findMin(arr: Array<Int>): Int {
return arr.minOrNull() ?: throw IllegalArgumentException("Array is empty")
}

fun main() {
println(findMin(arrayOf(3, 5, 7, 2, 8))) // Output: 2
}
fun mergeArrays(arr1: Array<Int>, arr2: Array<Int>): Array<Int> {
return (arr1 + arr2).sortedArray()
}

fun main() {
val arr1 = arrayOf(1, 3, 5, 7)
val arr2 = arrayOf(2, 4, 6, 8)
println(mergeArrays(arr1, arr2).joinToString(", ")) // Output: 1, 2, 3, 4, 5, 6, 7, 8
}
fun removeDuplicates(arr: Array<Int>): Array<Int> {
return arr.distinct().toTypedArray()
}

fun main() {
println(removeDuplicates(arrayOf(1, 2, 2, 3, 4, 4, 5)).joinToString(", ")) // Output: 1, 2, 3, 4, 5
}
fun fibonacci(n: Int): List<Int> {
val sequence = mutableListOf(0, 1)
for (i in 2 until n) {
sequence.add(sequence[i - 1] + sequence[i - 2])
}
return sequence
}

fun main() {
println(fibonacci(10).joinToString(", ")) // Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
}
fun isPerfectSquare(n: Int): Boolean {
val sqrt = Math.sqrt(n.toDouble()).toInt()
return sqrt * sqrt == n
}

fun main() {
println(isPerfectSquare(16)) // Output: true
}
fun transpose(matrix: Array<Array<Int>>): Array<Array<Int>> {
val rows = matrix.size
val cols = matrix[0].size
val transposed = Array(cols) { Array(rows) { 0 } }

for (i in matrix.indices) {
for (j in matrix[i].indices) {
transposed[j][i] = matrix[i][j]
}
}
return transposed
}

fun main() {
val matrix = arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6))
val result = transpose(matrix)
result.forEach { println(it.joinToString(", ")) } // Output: 1, 4 | 2, 5 | 3, 6
}
fun sortArray(arr: Array<Int>): Array<Int> {
return arr.sortedArray()
}

fun main() {
println(sortArray(arrayOf(5, 3, 8, 6, 2)).joinToString(", ")) // Output: 2, 3, 5, 6, 8
}
fun longestWordLength(sentence: String): Int {
return sentence.split(" ").maxOfOrNull { it.length } ?: 0
}

fun main() {
println(longestWordLength("Kotlin is a powerful language")) // Output: 9
}
fun swap(a: Int, b: Int): Pair<Int, Int> {
var x = a
var y = b
x = x + y
y = x - y
x = x - y
return Pair(x, y)
}

fun main() {
val (a, b) = swap(3, 5)
println("After swap: a = $a, b = $b") // Output: a = 5, b = 3
}
fun decimalToBinary(n: Int): String {
return Integer.toBinaryString(n)
}

fun main() {
println(decimalToBinary(10)) // Output: 1010
}
fun gcd(a: Int, b: Int): Int {
return if (b == 0) a else gcd(b, a % b)
}

fun lcm(a: Int, b: Int): Int {
return (a * b) / gcd(a, b)
}

fun main() {
println(lcm(12, 18)) // Output: 36
}
fun secondLargest(arr: Array<Int>): Int? {
val sortedArr = arr.sortedDescending()
return sortedArr.getOrNull(1)
}

fun main() {
println(secondLargest(arrayOf(3, 1, 4, 1, 5))) // Output: 4
}

fun reverseWords(sentence: String): String {
return sentence.split(" ").reversed().joinToString(" ")
}

fun main() {
println(reverseWords("Kotlin is fun")) // Output: "fun is Kotlin"
}

fun areAnagrams(str1: String, str2: String): Boolean {
return str1.toCharArray().sorted() == str2.toCharArray().sorted()
}

fun main() {
println(areAnagrams("listen", "silent")) // Output: true
}
fun removeWhitespace(s: String): String {
return s.replace("\\s".toRegex(), "")
}

fun main() {
println(removeWhitespace("Kotlin is fun")) // Output: "Kotlinisfun"
}
fun countOccurrences(s: String, ch: Char): Int {
return s.count { it == ch }
}

fun main() {
println(countOccurrences("Kotlin is fun", 'i')) // Output: 2
}
fun calculator(a: Int, b: Int, op: Char): Int {
return when (op) {
'+' -> a + b
'-' -> a - b
'*' -> a * b
'/' -> a / b
else -> throw IllegalArgumentException("Invalid operator")
}
}

fun main() {
println(calculator(10, 5, '+')) // Output: 15
}
fun toUpperCase(s: String): String {
return s.uppercase()
}

fun main() {
println(toUpperCase("kotlin")) // Output: "KOTLIN"
}
fun isDigitsOnly(s: String): Boolean {
return s.all { it.isDigit() }
}

fun main() {
println(isDigitsOnly("12345")) // Output: true
}
fun isDigitsOnly(s: String): Boolean {
return s.all { it.isDigit() }
}

fun main() {
println(isDigitsOnly("12345")) // Output: true
}
fun flattenList(nestedList: List<List<Int>>): List<Int> {
return nestedList.flatten()
}

fun main() {
println(flattenList(listOf(listOf(1, 2), listOf(3, 4), listOf(5, 6)))) // Output: [1, 2, 3, 4, 5, 6]
}
fun generateFibonacci(n: Int): List<Int> {
val fibonacciList = mutableListOf(0, 1)
for (i in 2 until n) {
fibonacciList.add(fibonacciList[i - 1] + fibonacciList[i - 2])
}
return fibonacciList
}

fun main() {
println(generateFibonacci(10).joinToString(", ")) // Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
}
Get in touch

We are here to help you & your business

We provide expert guidance, personalized support, and resources to help you excel in your digital marketing career.

Timing
9:00 am - 5:00 pm

    Book Your FREE  Digital Marketing Consultation

    +91 8005836769

    info@webounstraininghub.in