What does a null means?
A null is a representation that implies 'no value exist'
What is exception?
Exception is an event that occurs during the the execution of a program that disrupts the normal flow of instruction. In other word, an error.
What are Collections used for?
Collections are used to contain values or elements.
How to allow variable to contain null value?
Adding a question mark (?) after the declaration of data type.
What are the 3 keywords used in handling exceptions and the keyword used in creating exceptions?
Handle exception: try, catch, finally
Create exception: throw
What is the main difference between Array and ArrayList?
Array is fixed in size whereas ArrayList does not have a fixed size (means elements can be added into an removed from ArrayList).
fun getStringLength (name: String?): Int { if (name.isEmpty()) { return 0 } return name.length } fun main() { println(getStringLength(name: null)) }
What is the output of the code above?
Error, because the value null is being passed into the getStringLength function. Naturally the value in variable 'name' inside the function would be a null, this produces an error when calling a length property from variable 'name' (null in this case) because it does not have any value.
What is the usage of finally keyword?
The finally keyword is used to execute codes either an error occurred or does not occur at all.
fun main() { val numbers: ArrayList<Int> = arrayListOf(1, 2, 3, 4, 5) numbers[0] = 1000 for (number in numbers) { println(number) } }
What is the output of the code above?
OUTPUT:
1000
2
3
4
5
When does NullPointerException occurs in Kotlin?
When accessing a null value.
fun divide (dividend: Int, divisor: Int): Int { try { return dividend / divisor } catch (e: Exception) { println("Division By Zero") return 0 } } fun main() { println(divide(dividend: 1, divisor: 0)) }
What are the outputs of the code above?
OUTPUT:
Division By Zero
0
What is the advantage of using iterator?
It can iterates forward and backward through a list.
Name at least 2 ways used in order to successfully accessing a variable which can contain null value.
Safe Calls (?.)
Elvis Operator (?:)
Not-null Assertion Operator (!!)
Why do we need exception handling?
Because not all errors result in the termination of the program. Exception handling helps in specifying errors in details, so that we can know the location where it occurred and its cause.
fun main() { val numbers = hashMapOf<String, Int>("one" to 1, "two" to 2, "three" to 3) val numbers["four"] = 4 val numbers["one"] = 5 }
How many key-value pairs would there be after the code above is excecuted?
4,
"one" to 5
"two" to 2
"three" to 3
"four" to 4