Q1. You would like to print each score on its own line with its cardinal position. Without using var or val, which method allows iteration with both the value and its position?
Q6. What is the entry point for a Kotlin application?
fun static main(){}
fun main(){}
fun Main(){}
public static void main(){}
Q7. You are writing a console app in Kotlin that processes tests entered by the user. If the user enters an empty string, the program exits. Which kind of loop would work best for this app? Keep in mind that the loop is entered at least once
Q8. You pass an integer to a function expecting type Any. It works without issue. Why is a primitive integer able to work with a function that expects an object?
Q9. You have started a long-running coroutine whose job you have assigned to a variable named task. If the need arose, how could you abort the coroutine?
Q11. You have written a snippet of code to display the results of the roll of a six-sided die. When the die displays from 3 to 6 inclusive, you want to display a special message. Using a Kotlin range, what code should you add?
when (die) {
1 -> println("die is 1")
2 -> println("die is 2")
___ -> println("die is between 3 and 6")
else -> println("die is unknown")
}
Q12. The function typeChecker receives a parameter obj of type Any. Based upon the type of obj, it prints different messages for Int, String, Double, and Float types; if not any of the mentioned types, it prints "unknown type". What operator allows you to determine the type of an object?
Q14. You have a function simple() that is called frequently in your code. You place the inline prefix on the function. What effect does it have on the code?
inlinefunsimple(x: Int): Int{
return x * x
}
funmain() {
for(count in1..1000) {
simple(count)
}
}
The code will give a stack overflow error
The compiler warns of insignificant performance impact
Q17. Which line of code shows how to display a nullable string's length and shows 0 instead of null?
println(b!!.length ?: 0)
println(b?.length ?: 0)
println(b?.length ?? 0)
println(b == null? 0: b.length)
Q18. In the file main.kt, you are filtering a list of integers and want to use an already existing function, removeBadValues. What is the proper way to invoke the function from filter in the line below?
Q21. Your code need to try casting an object. If the cast is not possible, you do not want an exception generated, instead you want null to be assigned. Which operator can safely cast a value?
Q30. The code snippet below translates a database user to a model user. Because their names are both User, you must use their fully qualified names, which is cumbersome. You do not have access to either of the imported classes' source code. How can you shorten the type names?
Q31. Your function is passed by a parameter obj of type Any. Which code snippet shows a way to retrieve the original type of obj, including package information?
Q36. You have an enum class Signal that represents the state of a network connection. You want to print the position number of the SENDING enum. Which line of code does that?
Q38. You have a when expression for all of the subclasses of the class Attribute. To satisfy the when, you must include an else clause. Unfortunately, whenever a new subclass is added, it returns unknown. You would prefer to remove the else clause so the compiler generates an error for unknown subtypes. What is one simple thing you can do to achieve this?
Because name is a class parameter, not a property-it is unresolved main().
In order to create an instance of a class, you need the keyword new
The reference to name needs to be scoped to the class, so it should be this.name
Classes cannot be immutable. You need to change var to val
Note: By default, constructor parameters can only be used in the initializer blocks or property initializers declared in the class body. Therefore, to let the greet function have access to the name parameter, it should be declared as a property: class Cat (val name: String) { ... }
Q46. The code below shows a typical way to show both index and value in many languages, including Kotlin. Which line of code shows a way to get both index and value more idiomatically?
var ndx = 0;
for (value in1..5){
println("$ndx - $value")
ndx++
}
Q50. In this code snippet, why does the compiler not allow the value of y to change?
for(y in1..100) y+=2
y must be declared with var to be mutable
y is an implicitly immutable value
y can change only in a while loop
In order to change y, it must be declared outside of the loop
Q51. You have created a data class, Point, that holds two properties, x and y, representing a point on a grid. You want to use the hash symbol for subtraction on the Point class, but the code as shown will not compile. How can you fix it?
dataclassPoint(val x: Int, val y: Int)
operatorfun Point.plus(other: Point) = Point(x + other.x, y + other.y)
operatorfun Point.hash(other: Point) = Point(x - other.x, y - other.y)
funmain() {
val point1 = Point(10, 20)
val point2 = Point(20, 30)
println(point1 + point2)
println(point1 # point2)
}
You cannot; the hash symbol is not a valid operator.
You should replace the word hash with octothorpe, the actual name for the symbol.
You should use minus instead of hash, then type alias the minus symbol.
You need to replace the operator with the word infix.
Q52. This code snippet compiles without error, but never prints the results when executed. What could be wrong?
val result = generateSequence(1) { it + 1 }.toList()
println(result)
The sequence lacks a terminal operation.
The sequence is infinite and lacks an intermediate operation to make it finite.
The expression should begin with generateSequence(0).
Q54. Both y and z are immutable references pointing to fixed-size collections of the same four integers. Are there any differences?
val y = arrayOf(10, 20, 30, 40)
val z = listOf(10, 20, 30, 40)
You can modify the contents of the elements in y but not z.
There are not any differences. y and z are a type alias of the same type.
You add more elements to z since it is a list.
You can modify the contents of the elements in z but not y.
Q55. The code snippet compiles and runs without issue, but does not wait for the coroutine to show the "there" message. Which line of code will cause the code to wait for the coroutine to finish before exiting?
Q56. You would like to group a list of students by last name and get the total number of groups. Which line of code accomplishes this, assuming you have a list of the Student data class?
dataclassStudent(val firstName: String, val lastName: String)
Q57. Class BB inherits from class AA. BB uses a different method to calculate the price. As shown, the code does not compile. What changes are needed to resolve the compilation error?
openclassAA() {
var price: Int = 0get() = field + 10}
classBB() : AA() {
var price: Int = 0get() = field + 20}
You need to add a lateinit modifier to AA.price.
You simply need to add an override modifier to BB.price.
You need to add an open modifier to AA.price and an override modifier to BB.price.
You need to add a public modifier to AA.price and a protected modifier to BB.price.
Q61. You want to know each time a class property is updated. If the new value is not within range, you want to stop the update. Which code snippet shows a built-in delegated property that can accomplish this?
Q62. Which line of code shows how to call a Fibonacci function, bypass the first three elements, grab the next six, and sort the elements in descending order?
val sorted = fibonacci().skip(3).take(6).sortedDescending().toList()
val sorted = fibonacci().skip(3).take(6).sortedByDescending().toList()
val sorted = fibonacci().skip(3).limit(6).sortedByDescending().toList()
val sorted = fibonacci().drop(3).take(6).sortedDescending().toList()
Q69. For the Product class you are designing, you would like the price to be readable by anyone, but changeable only from within the class. Which property declaration implements your design?
Q76. You have written a function, sort(), that should accept only collections that implement the Comparable interface. How can you restrict the function?
funsort(list: List<T>): List <T> {
return list.sorted()
}
Add <T -> Comparable<T>> between the fun keyword and the function name
Add Comparable<T> between the fun keyword and the function name
Add <T : Comparable<T>> between the fun keyword and the function name
Add <T where Comparable<T>> between the fun keyword and the function name
Q83. The code below compiles and executes without issue, but is not idiomatic kotlin. What is a better way to implement the printlln()?
funmain() {
val name: String = "Amos"val grade: Float = 95.5f println("My name is " + name + ". I score " + grade + " points on the last coding quiz.")
}
Q84. You have enum class Signal that represents a state of the network connection. You want to iterate over each member of the enum. Which line of code shows how to do that `?
By using the !! operator to force variables to be non-null.
By using safe calls (?.) and the Elvis operator (?:).
By declaring all variables as nullable.
Null safety cannot be ensured in Kotlin.
Q102. What is a data class in Kotlin?
A class used for storing confidential data.
A class designed to hold data with automatically generated methods.
A class used to create instances of other classes.
A class used to define the structure of data in a database.
Q103. What is the default behavior of Kotlin classes?
All classes are open by default.
All classes are final by default.
All classes are abstract by default.
All classes are static by default.
Q104. Does Kotlin provide support for primitive data types?
No, Kotlin does not provide support for primitive data types like in Java.
Yes, Kotlin supports primitive data types in addition to objects.
Only for certain primitive data types, such as int.
Yes, Kotlin provides support for primitive data types like in Java.
Q105. Does Kotlin provide support for macros?
Yes, Kotlin has a rich set of macros for code generation.
No, Kotlin does not support macros.
Yes, Kotlin supports macros for advanced metaprogramming.
Macros are not needed in Kotlin as it use a different approach.
Q106. What is the use of the open keyword in Kotlin?
The open keyword is used to declare a variable as mutable.
The open keyword is used to allow a class or function to be subclassed or overridden.
The open keyword is used to specify a class as abstract.
The open keyword is used to indicate that a variable is always null.
Q107. What do you understand by the Ranges operator in Kotlin?
The Ranges operator is used to iterate within a range of values.
The Ranges operator is used to perform bitwise operations.
The Ranges operator is used to concatenate strings.
The Ranges operator is used for logical comparisons.
Q108. Where should we use var and val in Kotlin?
var and val can be used interchangeably; there is no difference.
Use var for mutable variables and val for immutable variables.
Use var for integers and val for strings.
Use var for class properties and val for local variables.
Q109. What is the difference between a safe call (?.) and a null check (!!) in Kotlin?
The safe call (?.) checks if a variable is null and returns null if it is, while the null check (!!) throws a KotlinNullPointerException if the variable is null.
The safe call (?.) and null check (!!) perform the same operation.
The safe call (?.) and null check (!!) both return the value of the variable if it is null.
The safe call (?.) and null check (!!) are not valid Kotlin operators.
Q110. What is the basic difference between fold and reduce in Kotlin?
fold takes an initial accumulator value and applies a binary operation to the elements and the accumulator, while reduce uses the first element as the initial accumulator value.
fold and reduce are equivalent and can be used interchangeably.
fold can only be used with collections, while reduce can be used with any data type.
fold and reduce are both used for filtering elements in a collection.
Q111. What are the advantages of "when" over "switch" in Kotlin?
"when" in Kotlin is more concise and powerful than "switch" in Java.
"when" in Kotlin is less flexible than "switch" in Java.
"when" in Kotlin can only be used with integers.
"when" in Kotlin is less efficient than "switch" in Java.
Q112. Why does this code snippet not compile?
interfaceVehiclefunmain() {
val myCar = Vehicle()
}
Q113. What is the difference between a primary constructor and a secondary constructor in Kotlin?
A primary constructor is declared in the class header, while a secondary constructor is declared in the class body.
A primary constructor can have only one parameter, while a secondary constructor can have multiple parameters.
A primary constructor must initialize all of the class's properties, while a secondary constructor does not have to initialize all of the class's properties.
A primary constructor can only be called once, while a secondary constructor can be called multiple times.