Kotlin Interview Questions & Answers
Welcome to SpiritSofts, your premier destination for mastering Kotlin programming and excelling in the world of Android app development. We take pride in offering a comprehensive training package that includes the finest collection of Kotlin Interview Questions and Answers, meticulously crafted Course Material, and hands-on Android Project experiences.
At SpiritSofts, we understand the ever-evolving landscape of technology, and our training program is designed to equip you with the skills and knowledge you need to stay ahead. Kotlin has emerged as a powerful and flexible programming language, particularly for Android development, and our training is tailored to ensure you not only grasp its concepts but also harness its full potential.
Key Highlights of Our Offering:
1. Best Kotlin Interview Questions and Answers: Elevate your interview preparation with our carefully curated selection of the best Kotlin interview questions. Our comprehensive answers provide insights into effective problem-solving strategies and demonstrate your command over Kotlin’s nuances.
2. Comprehensive Course Material: Our course material, crafted by industry experts, offers a deep dive into Kotlin’s syntax, features, and application. You’ll gain a robust foundation in Kotlin programming, with real-world examples and case studies to guide you every step of the way.
3. Hands-on Android Project: Experience the thrill of practical learning as you tackle a real-world Android project. Apply your skills to develop an Android app from concept to execution, honing your coding abilities and gaining valuable project experience that will set you apart in the job market.
Whether you’re a novice embarking on your coding journey or a seasoned developer aiming to expand your skill set, our training caters to all skill levels. Our instructors are industry professionals who bring a wealth of practical knowledge to the classroom, providing you with insights beyond textbook concepts.
At SpiritSofts, we are committed to your success. Our training environment fosters interactive learning, encourages questions, and promotes collaboration. Our goal is not just to impart information but to empower you with the tools and expertise needed to thrive in the dynamic world of technology.
Embark on a transformative learning journey with us. Enhance your career prospects, craft innovative Android applications, and gain the confidence to tackle any Kotlin-related challenge that comes your way.
Visit our website to explore program details, course content, and enrollment options. Let SpiritSofts be your guiding force as you embark on a path of Kotlin mastery and Android excellence. Your journey to success begins here.
Kotlin Interview Questions and Answers Top 100 Interview Questions for Kotlin Android Kotlin Interview Questions 3 years Experience Medium Freshers Kotlin Interview Questions and Answers.
1. Explain Higher-Order Functions?
Ans:Higher-Order Functions: A higher-order function is a function that takes functions as parameters, or returns a function.
2. Explain Functions In Kotlin?
Ans:Kotlin functions are first-class functions that are easily stored in variables and data structures and can be pass as arguments and returned from other higher-order functions.
Sample function declaration and usage in Kotlin
fun double(x: Int): Int {
return 2 * x
}
val result = double(2)
3. How to convert a String to an Int in Kotlin?
Ans: toInt() method is used to convert a string value to integer or INT in Kotlin. Below is example uses
fun main(args: Array) {
val s: String = “Kotlin”
var x = 10
x = “8”.toInt()
}
4. What is the difference between declaration variable using val or var in Kotlin?
Ans:
In Kotlin a variable declared using val keyword is cannot be changed. It is similar to the final modifiers in Java whereas the variables declared using var keywords can be reassigned.
5. How to Declare a Variable in Kotlin?
Ans:
In Kotlin, you can declare a variable using var or val which followed by an optional datatype.
Variable declaration in Kotlin looks like:
val s: String = “Hi”
var x = 5
6. List the Basic data types of Kotlin?
Ans:
Data types of a constant or variable decide what type of variable it is and how much space is required to store it.
The basic data types in Kotlin are:
Numbers
Characters
Strings
Arrays
Booleans
7. Why is Kotlin preferred over Java?
Ans:
Kotlin eases the 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 Kotlin, we code approximately 40% less number of code lines as compared with Java.
8. Where does the Kotlin run and what is the entry point of Kotlin?
Ans:
The Kotlin program once compiled, can run on standard JVM like other programming codes.And, like many other programming languages main() function is the entry point of the Kotlin.
9. What are the different types of constructors in Kotlin?
Ans:
There are two types of constructors in Kotlin:
Primary constructor: It is a section of the Class header and is declared after the class name.
Secondary constructor: This constructor is declared inside the body.
Note: There can be more secondary constructors for a class.
10. Can you execute Kotlin code without JVM?
Ans: JVM, which stands for Java Virtual Machine is a feature of Kotlin. This feature compiles a Kotlin code into a native code, which can be done without JVM too.
11. Mention the structural expressions in Kotlin?
Ans:
There are three Structural expressions in Kotlin.They are:
Return: It returns from the nearest enclosing function or anonymous function by default.
Break: This expression terminates the closest enclosing loop.
Continue: This expression proceeds you to the next closest enclosing loop.
12. Explain the data classes in Kotlin?
Ans:
In programming, we use classes to hold data and these classes are called as data classes.
An object can be initialized in the data class and to access the individual parameters of these data classes, we use component functions.
13. What are the modifiers that are available in Kotlin?
Ans:
The modifier in Kotlin provides the developer to customize the declarations as per the requirements. Kotlin provides four modifiers. They are:
Private: This makes the declaration visible only inside the file containing declaration.
Public: It is by default, which means that the declarations will be visible everywhere.
Internal: This makes the declaration visible everywhere in the same modules.
Protected: This keeps the declaration protected and is not available for top-level declarations.
14. Can you migrate the code from Java to Kotlin? If yes how do you do it?
Ans:
Yes, we can migrate the code from Java to Kotlin.This can be done using JetBrains IDEA, which facilitates the conversion of Java code to Kotlin code.
15. State the differences between Val and Var?
Ans:
Val: Val, which is the short form of value, is a constant and it cannot be changed once assigned.
Var: Var, which is the short form of variable, is a storage location that accepts the reassignment of values that have the same data types.
16. Explain Kotlin’s Null safety?
Ans:
In Kotlin, the Null safety is used to eliminate the risk of countering the NullPointer exception in real time.
17. What are the types of strings available in Kotlin? And, what do you mean by Kotlin String Interpolation?
Ans:
Strings are a collection of characters together.Kotlin features two types of strings, and they are:
Raw string
Escaped string
In Kotlin String, templates can be evaluated.This evaluation of string templates is called as the string template interpolation.
18. State the advantages and disadvantages of Kotlin?
Ans:
Advantages:
Kotlin is simple and easy 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. Upon all this, 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.
Disadvantages:
Kotlin does not provide the static modifier, which causes problems for conventional java developer.
In Kotlin, the function declaration can be done in many places in the application, which creates the trouble for the developer to understand which function is being called.
19. What is Kotlin?
Ans:
It is an open source programming language that combines object-oriented programming features.
The features like Range Expression, Extension Function, Companion Object, Smart casts, Data classes are considered to be surplus of the Kotlin Language.
20. Which type of Programming does Kotlin support?
Ans:
Kotlin supports only two types of programming, and they are:
Procedural programming
Object-oriented programming
21. Why did you switch to Kotlin from Java ?
Ans:
Kotlin seems to be simpler and cleaner than Java. It removes a lot of redundancies in code from Java. Kotlin also adds some needed features that Java doesn’t yet support, and is making code more idiomatic. Also Kotlin has been added to Android Studio’s list of supported languages recently. So, there is much to expect from Kotlin in easing out the development efforts and good support in future.
22. What are the features you think are there in Kotlin but not in Java ?
Ans:
Kotlin has quite a number of features that Java doesn’t. To name some of them, they are
Extension Functions
Null Safety
Smart casts
Range expressions
Operator Overloading
Data classes
Companion Objects
Coroutines
etc.
23. What kinds of programming does Kotlin support ?
Ans:
Kotlin supports two types of programming. They are
Procedural Programming
Object Oriented Programming
Q4 – What is the entry point to a Kotlin program ? Provide an example.
Like most of the other procedural languages, main() function is the entry point to a Kotlin program.
An Example for main() function is :
24. How do you think extension functions are useful ?
Ans:
Extension functions helps to extend a class with new functionality without having to inherit from the class. Also you may use them like an inbuilt function for the class throughout the application.
25. What are Data classes ? Aren’t they available in Java ?
Ans:
Sometimes we use a class just to hold the data and nothing else. These classes are called Data classes. Of course these kind of classes could be built using Java, but with explicit implementation of getter and setter for each of the properties of class. Also you may need to implement functions like equals, toString and copy separately. What Kotlin does is implementing all these automatically along with special functions called component functions. How cool is that, removing the redundant code bloat.
26. Does Kotlin provide any additional functionalities for standard Java packages or standard Java classes?
Ans:
Ofcourse, Yes. Kotlin uses the concept of extension functions, that we already talked about, to build some useful and more widely used functions among developers directly into the Kotlin library.
27. Where does this Kotlin run ? Does it have some kind of different runtime environment ?
Ans:
Once compiled, Kotlin programs can run on standard JVM like some other compiled Java code. This means that Kotlin Compiler compiles Kotlin programs to byte-code, which is understood by JVM. So, Kotlin is like a flavor of Java, that goes alongside Java. Interesting fact is that, Kotlin applications can be built with parts of Java code.
28. So, how do you migrate the code from Java to Kotlin ?
Ans:
JetBrains IDEA provides inbuilt tools to convert Java code to Kotlin code. Then you may do the magic offered by Kotlin at some of the parts in code, to make it clean.
29. OK. Is there something called init block in Kotlin ?
Ans:
Yes.
30. What does init block do and Where does it appear in a class ?
Ans:
Instructions in the init block are executed right after Primary Constructor’s execution. init block goes in a class along with secondary constructors as a method.
Reference – Kotlin Init
31. How many types of constructors are there ? What are they ?
Ans:
There are two types of constructors. They are Primary Constructors and Secondary Constructors.
32. How are Primary Constructors different from Secondary Constructors ?
Ans:
Primary Constructors are declared intrinsically with class definition. Secondary Constructors are declared exclusively inside the class body.
In the following example, in the first line, the constructor keyword along with the variables declared right after it is the Primary Constructor. Inside the class body, we have another constructor, and this is Secondary Constructor.
Example of class with Primary and Secondary Constructors
class Person constructor(var name: String, var age: Int){
var profession: String = “Not Mentioned”
constructor (name: String, age: Int, profession: String): this(name,age){
this.profession = profession
}
}
33. Is there any dependency of Secondary Constructors on Primary Constructors ?
Ans:
Yes. Secondary Constructor has to make an exclusive call to Primary Constructor or other Secondary Constructor, which of course calls the Primary Constructor. Following is an example, and here the Secondary Constructor makes call to Primary Constructor using this(name, age).
Example of class with Primary and Secondary Constructors
class Person constructor(var name: String, var age: Int){
var profession: String = “Not Mentioned”
constructor (name: String, age: Int, profession: String): this(name,age){
this.profession = profession
}
fun printPersonDetails(){
println(“$name whose profession is $profession, is $age years old.”)
}
}
34. What is the difference between val and var ?
Ans:
Val (Value) is like a constant. Once assigned a value, you cannot change it. On the other hand Var (Variable) is designed to be a storage location that can accept reassignment of values of same data type or what ever feasible by the data type casting.
35. – What is Kotlin’s Null Safety ?
Ans:
Null Safety in Kotlin is to eliminate the risk of occurrence of NullPointerException in real time. Kotlin can differentiate between nullable references and non-nullable references. If a variable has to be allowed to store a null value, that has to be declared with a null (?) operator.
36. If you have worked with files, name some of the extension methods Kotlin provides to java.io.File
Ans:
Kotlin provides very useful extension functions to java.io.File. Some of them are :
File.bufferedReader() : to read contents of a file into BufferedReader
File.forEachLine() : to read a file line by line in Kotlin
File.inputStream() : to read contents of file to InputStream
File.readBytes() : to read contents of file to ByteArray
File.readLines() : to read lines in file to List
File.readText() : to read contents of file to a single String
For examples to these methods refer – Kotlin Read File Content
37. Is there Ternary Conditional Operator in Kotlin like in Java ?
Ans:
No.
38. How do you realize Ternary Conditional Operator in Kotlin ?
Ans:
A simple if else should do the job.
if (condition) a else b
39. How do you declare a variable as volatile in Kotlin ?
Ans:
By providing volatile annotation before the declaration of variable.
@Volatile var a: Long? = null
40. How do you check if two Strings are equal valued ?
Ans:
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.”)
}
}
For more Click Here
Android with Kotlin Class Notes
Welcome to Kotlin
Recap: Let’s recap what we have learned so far..
Today Topics:
- Key features
- “HelloWorld” program in Kotlin
- Kotlin variables
- Kotlin Data types
Key features:
- Statically typed
- Concise
- Safe
- Interoperable with Java
- Functional and Object Oriented ● High performance than JAVA
Statically typed Vs Dynamically typed:
- In statically typed programming languages, type checking occurs at compile time. At compile time, source code in a specific programming language is converted to a machine-readable format. This means that before source code is compiled, the type associated with each and every single variable must be known.
- Some common examples of programming languages that belong to this category are Java, Haskell, C, C++, C#, Scala, Kotlin, Fortran, Go, Pascal, and Swift.
- In dynamically typed languages, type checking takes place at runtime or execution time. This means that variables are checked against types only when the program is executing.
- Some examples of programming languages that belong to ○ this category are Python, JavaScript, Lisp, PHP, Ruby, Perl, Lua, and Tcl.
Concise:
It drastically reduces the extra code written in other object-oriented programming languages.
Functional Programming Paradigm:
Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style.
Safe:
Kotlin null safety is a procedure to eliminate the risk of null reference from the code. Kotlin compiler throws NullPointerException immediately if it found any null argument is passed without executing any other statements.
Object-oriented programming:
- The object-oriented programming model revolves around the concept of Objects.
- What is an Object? An object is an instance of a Class. It contains properties and functions.
- They are like real-world objects. For example, your car, house, laptop, etc. are all objects.
- They have some specific properties and methods to perform some action.
- What is a Class? The Class defines the blueprint of Objects. They define the properties and functionalities of the objects. For example, Laptop is a class and your laptop is an instance of it.
Kotlin build process:
Hello World program in Kotlin:
fun main(args: Array<String>){
println(“Hello World”)
}
fun ——> keyword reserved for declaring function main ——> name of the function
args ——> input arguments for the function
println ——> pre-defined func.. which is ready to use
Basics of Kotlin-1
Topics:
Basics of Kotlin
- Kotlin variables
- Kotlin Data types
- Kotlin Operators
Kotlin Variables :
- Every variable should be declared before it’s used. ● Declaration of the variable type also decides the kind of data you are allowed to store in the memory location. ● Type of variable can be inferred from the initialized value.
Ex:
var number
var name = “kotlin”
In Kotlin, variables are declared using two types –
- Immutable using val keyword
- Mutable using var keyword
Immutable Variables :
- Immutable is also called read-only variables. Hence, we cannot change the value of the variable declared using val keyword.
Ex:
val myName: String = “”
myName = “Praveen” // compile time error
// It gives error Kotlin Val cannot be reassigned
Mutable Variables :
- In Mutable variable we can change the value of the variable.
Ex:
var myAge = 20
myAge = 22 // compiles successfully
println(“My new Age is ${myAge}”)
Kotlin Data Types :
There are fundamental data types in Kotlin:
- Integer Data type
- Floating-point Data Type
- Boolean Data Type
- Character Data Type
Integer Data Type :
- These data types contain the integer values.
Data type |
Bits |
Min Value |
Max Value |
Byte |
8 bits |
-128 |
127 |
Short |
16 bits |
-32768 |
-32767 |
Int |
32 bits |
-2147483648 |
2147483647 |
Long |
64 bits |
–-9223372 03685477 5808 |
92233720 36854775 807 |
Ex:
var a: Int = 0
var b: Short = 10
var c: Byte = 20
Var d: Long = 56789
Floating-Point Data Type :
- These data type used to store decimal value or fractional part.
Data type |
Bits |
Min Value |
Max value |
Float |
32 bits |
1.40129e-45 |
3.404e+38 |
Double |
64 bits |
4.95e-324 |
1.79e+308 |
Ex:
fun main(args : Array<String>) {
// add suffix F for float
var myfloat = 54F
println(“My float value ${myfloat}”)
var F1: Float = Float.MIN_VALUE
var F2: Float = Float.MAX_VALUE
println(“Smallest Float value: ” +F1)
println(“Largest Float value: ” + F2)
var D1: Double = Double.MIN_VALUE
var D2: Double = Double.MAX_VALUE
println(“Smallest Double value: ” + D1)
println(“Largest Double value: ” + D2)
}
Boolean Data Type :
- Boolean data type represents only one bit of information either true or false.
Data type |
Bits |
Min Value |
Max value |
Boolean |
1 bits |
true |
false |
Character Data Type :
- Character data type represents the small letters(a-z), Capital letters(A-Z), digits(0-9) and other symbols.
Data type |
Bits |
Min Value |
Max value |
Char |
8 bits |
-128 |
127 |
Kotlin Operators :
- Operators are the special symbols that perform different operation on operands.
- Kotlin contains different kinds of operators as below:
❖ Arithmetic operator
❖ Relation operator
❖ Assignment operator
❖ Unary operator
❖ Logical operator
❖ Bitwise operator
Airthmetic Operators :
Operators |
Meaning |
Expression |
Translate to |
+ |
Additon |
a+b |
a.plus(b) |
– |
Subtraction |
a-b |
a.minus(b) |
* |
Multiplication |
a*b |
a.times(b) |
/ |
Division |
a/b |
a.div(b) |
% |
Modulus |
a%b |
a.rem(b) |
Ex:
fun main(args: Array<String>)
{
var a = 20
var b = 4
println(“a + b = ” + (a + b))
println(“a – b = ” + (a – b))
println(“a * b = ” + (a.times(b)))
println(“a / b = ” + (a / b))
println(“a % b = ” + (a.rem(b)))
}
Relational Operators :
Operators |
Meaning |
Expression |
Translate to |
> |
greater than |
a>b |
a.compareTo(b) > 0 |
< |
less than |
a<b |
a.compareTo(b) < 0 |
>= |
greater than or equal to |
a>=b |
a.compareTo(b) >= 0 |
<= |
less than or equal to |
a<=b |
a.compareTo(b) <= 0 |
== |
is equal to |
a==b |
a?.equals(b) ?: (b === null) |
!= |
not equal to |
a!=b |
!(a?.equals(b) ?: (b === null)) > 0 |
Ex: fun main(args: Array<String>){
var c = 30
var d = 40
println(“c > d = “+(c>d))
println(“c < d = “+(c.compareTo(d) < 0))
println(“c >= d = “+(c>=d))
println(“c <= d = “+(c.compareTo(d) <= 0)) println(“c == d = “+(c==d))
println(“c != d = “+(!(c?.equals(d) ?: (d === null))))
}
Assignment Operators :
Operators |
Meaning |
+= |
a = a+b |
–= |
a = a-b |
*= |
a = a*b |
/= |
a = a/b |
%= |
a = a%b |
Ex:
fun main(args : Array<String>){
var a = 10
var b = 5
a+=b
println(a)
a-=b
println(a)
a*=b
println(a)
a/=b
println(a)
a%=b
println(a)
}
Unary Operators :
Operators |
Expression |
Translate to |
++ |
++a or a++ |
a.inc() |
– – |
– –a or a– – |
a.dec() |
Ex:
fun main(args : Array<String>){
var e=10
var flag = true
println(“First print then increment: “+ e++) println(“First increment then print: “+ ++e) println(“First print then decrement: “+ e–)
println(“First decrement then print: “+ –e) }
Logical Operators :
Operators |
Meaning |
Expression |
&& |
return true if all expressions are true |
(a>b) && (a>c) |
| | |
return true if any of expression is true |
(a>b) | | (a>c) |
! |
return complement of the expression |
a.not() |
Ex:
fun main(args : Array<String>){
var x = 100
var y = 25
var z = 10
var result = false
if(x > y && x > z)
println(x)
if(x < y || x > z)
println(y)
if( result.not())
println(“Logical operators”)
}
Bitwise Operators :
Operators |
Meaning |
Expression |
shl |
signed shift left |
a.shl(b) |
shr |
signed shift right |
a.shr(b) |
ushr |
unsigned shift right |
a.ushr() |
and |
bitwise and |
a.and(b) |
or |
bitwise or |
a.or() |
xor |
bitwise xor |
a.xor(b) |
inv |
bitwise inverse |
a.inv() |
Ex:
fun main(args: Array<String>) {
println(“5 signed shift left by 1 bit: ” +
5.shl(1))
println(“10 signed shift right by 2 bits: : “
+ 10.shr(2)) println(“12 unsigned shift right
by 2 bits: ” + 12.ushr(2)) println(“36
bitwise and 22: ” + 36.and(22))
println(“36 bitwise or 22: ” + 36.or(22))
println(“36 bitwise xor 22: ” + 36.xor(22))
println(“14 bitwise inverse is: ” + 14.inv())
Basics of Kotlin-2
Recap:
● So far we learned how to define function, variables
● Basic data types
● Perform operations on variables
Today Topics:
● Self-evaluation
● Important points on data types
● String & String pool
● Heap memory & Stack memory
● Important pre-define functions on strings
Self-Evaluation:
Exercise 1: Find errors in below code
fun main()
{ var a
var x: Int = 0
val y: Int = 1
x = “kotlin”
y = 0
val b: Int
b = 1
b = 2
val z: Double = 1
}
Exercise 2: Find errors in below code
fun main()
{
var a
var x= 1
val y: Double
if(x>0)
{
y = 1.5
}
else{
y = 2.5
}
}
Exercise 3: Guess the output
fun main() {
var a: Int = 0
var c = a++
println(a)
a.inc()
println(a)
c = –a
print(c)
}
Exercise 4: Guess the output:
var characterA = ‘C’
var characterB = ‘E’
var characterC = ‘A’
if(characterA>characterB || characterA>characterC)
{
println(“CharacterA isn’t the smallest”)
}
if(characterA>characterB && characterA>characterC)
{
println(“characterA isn’t the smallest”)
}
else{
println(“characterA is definitely smaller than
characterB”)
}
Exercise 5: Guess the output:
var a: Int = 0
var c = a++
println(a)
a.inc()
println(a)
c = –a
print(c)
Exercise 6: Guess the output:
fun main(args : Array<String>){
var e=10
var flag = true
println(“First print then increment: “+ e++)
println(“First increment then print: “+ ++e)
println(“First print then decrement: “+ e–)
println(“First decrement then print: “+ –e)
}
Important Points on Data types
Numbers:
● The Kotlin compiler can’t infer the types Short and Byte. We
need to define them as shown below
var a: Int = 0
var b: Short = 10
var c: Byte = 20
● Similar to Java, for a Long and Float type you can append the
letter L and F(or f) respectively to the variable value.
val l = 23L
var f = 1.56F
var d = 1.55
var e = 1.55e10 //Alternative form to define a double value.
● Smaller types cannot be implicitly converted to larger ones in
Kotlin. The following would throw an error.
var b: Short = 10
val i: Int = b //Error
● Kotlin provides us with methods to explicitly convert a smaller
type to a larger one.
var b: Short = 10
val i: Int = b.toInt() //Works
Kotlin provides helper functions for conversion between each
type : toByte(), toInt(), toLong(), toFloat(), toDouble(), toChar(),
toShort(), toString() (To convert the string to a number if valid!).
Characters:
● Character types are denoted by Char and the value is specified
in single quotes.
var c: Char = ‘A’
//or using the shorthand form
var c = ‘A’
var d: Char = ‘AB’ //this won’t work. Only one character
allowed.
● Unlike Java, Characters in Kotlin can’t be set using ASCI
values. The following won’t compile
var c:Char = 65 //won’t work
The reason for the above anomaly is put on type inference.
However, we can add an int to a char or convert it to an int to get the
ASCII.
var c:Char = ‘A’
var newChar = c + 1 // B
● Range instantiation and range checks:
a..b ex: 2..8
x in a..b(checks if x is in the range of a to b)
x !in a..b(checks if x is not in the range of a to b)
String:
● String is an array of characters.
var str: String = “Hello”
//or
var str = “Hello”
var newString: String = ‘A’ //ERROR
var newString: String = 2 //ERROR
● String in Kotlin is implemented using the String class. Kotlin
Strings are immutable.
var str = “Hello”
str += “Kotlin Strings”
The above declaration changes the reference of the
variable str in the second line to the newly created string(“Hello
Kotlin Strings”) in the String Pool.
StringPool:
● String Pool in is a pool of Strings stored in Heap Memory.
● String pool helps in saving a lot of space for Java
Runtime although it takes more time to create the String.
● When we use double quotes to create a String, it first
looks for String with the same value in the String pool, if
found it just returns the reference else it creates a new
String in the pool and then returns the reference.
Heap Memory:
● Heap space is used by java runtime to allocate memory
to Objects.
● Whenever we create an object, it’s always created in the Heap
space.
Stack Memory:
● Stack memory is used for the execution of a thread.
They contain method-specific values that are
short-lived and references to other objects in the heap
that is getting referred from the method.
● Stack memory is always referenced in LIFO
(Last-In-First-Out) order.
● Whenever a method is invoked, a new block is created
in the stack memory for the method to hold local
primitive values and reference to other objects in the
method.
● As soon as the method ends, the block becomes
unused and becomes available for the next method.
Stack memory size is very less compared to Heap
memory.
Important Properties and Functions of Kotlin String:
● length : This is a property that can be accessed using the dot
operator on the String. Returns the number of characters
present in a string.
val str = “Hello Kotlin”
println(str.length) // prints: 12
● get(index) : Returns the character specified at the particular
index.
val str = “Hello Kotlin Strings”
println(str.get(4)) //prints o
● subSequence(startIndex, endIndex) : Returns the substring
between the startIndex and the endIndex but excluding the
endIndex character.
val str = “Hello Kotlin Strings”
println(str.subSequence(0,5)) //prints Hello
● a.compareTo(b) : If a is equal to b, it returns 0, if a<b it
returns positive number. compareTo accepts another argument
too, namely ignoreCase.
var str = “Hello Kotlin Strings”
var s = String()
s = “Hello KOTLIN Strings”
println(s.compareTo(str)) //prints -32
println(s.compareTo(str,true)) //prints 0
● Using Index Operator: To access individual characters of a String,
Kotlin supports the index access operator
var str = “Hello, Kotlin”
print(str[0]) //prints H
● Iterating through a String: We can loop through a string to
access each character using a for-in loop as shown below.
for(element in str){
println(element)
}
Escape characters in Kotlin Strings: Following are the escape
characters that when used with a backslash behave differently.
\n : newline.
\t : tab.
\” : double quote
\’ : single quote
\\ : backslash
\$ : dollar – Dollar symbol is used in String templates
that we’ll be seeing next
String Templates:
● Instead of concatenating an expression in a string, Strings can
contain expressions/statements following a dollar symbol as
shown below.
var len = str.length
var newStr = “Length of str is ${str.length}”
//or
var newStr = “Length of str is $len”
println(Length of str is ${str.length})
● Using string templates, we can insert variables and
expressions in a string. String Templates are commonly used
in print statements.
● To use the $ symbol in a string we need to escape the
character.
var escapedDollar = “Amount is \$5.50”
print(escapedDollar) //prints Amount is $5.50
String Equality:
There are two types of equality checkers.
● Referential Equality: Checks if the pointers for two
objects are the same. === operator is used.
● Structural Equality : Checks if the contents of both the
objects are equal. == is used.
Following code snippet demonstrates the above checkers:
var a = “Hello”
var b = “Hello again”
var c = “Hello”
println(a===c) // true since a and c objects point to
the same String in the StringPool
println(a==c) //true since contents are equal
println(a===b) //false
println(a==b) //false
Note: The negation of === and == are !=== and !==
respectively.
Basics of Kotlin-3
Recap:
● Important points on data types
● String & String pool
● Heap memory & Stack memory
● Important pre-define functions on strings
Today Topics:
● Kotlin Expression, Statement, Block
● Kotlin Control Flows
● Kotlin Loops
Kotlin Expression :
An expression consists of variables, operators, method calls etc
that produce a single value.
● A variable declaration can not be an expression (var a =
100)
● Assigning a value is not an expression (b = 15)
● A class declaration is not an expression (class XYZ {….})
Note: In Kotlin every function returns a value atleast Unit, so
every function is an expression.
Ex:
fun sumOf(a:Int,b:Int): Int{
return a+b
}
fun main(args: Array<String>){
val a = 10
val b = 5
var sum = sumOf(a,b)
var mul = a * b
println(sum)
println(mul)
}
Kotlin Statement :
● A statement is the syntactic unit of any programming
language that expresses some action to be carried out.
● A program is formed by the sequence of one or more
statements.
● Declaration of a variable is a statement.
val marks = 90
var grade = ‘A’
● Assigning a value to a variable is also a statement.
var sum = 10 + 20 // it is a statement
Here, 10 + 20 is an expression but var sum =
10 + 20 is a statement.
Multiple Statements:
Multiple statements are the statements when you write
more than one statement in a single line.
Ex:
fun main(args: Array<String>){
val sum: Int
sum = 100
println(sum) // single statement
println(“Hello”);println(“Geeks!”) // Mutilple
statements
}
Kotlin Block :
● A block is a section of software code enclosed with
curly braces ({…}).
● A block can consist of one or more statements,
preceded by the declarations of variables.
● A block contains one or more blocks nested within
it.
● Every function has its own block and the main
function also contains a block.
Ex:
fun main( args: Array<String>) {
//start of main block or outer block
val array = intArrayOf(2, 4, 6, 8)
for (element in array) { // start of inner block
println(element)
} // end of inner block
} // end of main block
Scope of variable in nested blocks:
● The variables declared at the head of the block are
visible throughout the block and any nested blocks,
unless a variable with the same name is declared at the
head in the inner block.
● When a new declaration is effective throughout the inner
block, the outer declaration becomes effective again at
the end of the inner block. So, we can say that variables
have nested scopes.
Ex:
fun main(args: Array<String>) { //start of main block
or outer block
val array = intArrayOf(2, 4, 6, 8)
val i = 0
for (element in array) { // start of inner block
val i = 2
println(i)
}
println(“out”+i) // end of inner block
} // end of outer block
Kotlin Control Flow Statements:
● if, else, range, for, while, when, repeat, continue,
break – are keywords reserved to control the flow of
execution.
Kotlin if else:
● if executes a certain section of code if the condition is
true. It can have an optional else clause.
Ex:
fun main(args: Array<String>) {
var a = 4
var b = 5
var max = a
if (a < b)
max = b
if (a > b) {
max = a
} else {
max = b
}
println(“a is $a b is $b max is $max”)
}
● In Kotlin, if else can be used as expressions too in
order to return a value.
Ex:
a = 5
b = 4
//if else returns a value in Kotlin
max = if (a > b) a else b
print(“a is $a b is $b max is $max”)
Kotlin for loop:
● For loop is used to iterate over a list of items based
on certain conditions.
Ex:
for (i in 0..5) {
print(i)
}
Note: in keyword is used to iterate over the range.
Ex:
val items = listOf(10, 20, 30, 40)
for (i in items)
println(“value is $i”)
Kotlin forEach loop:
● ForEach loop repeats a set of statements for each
iterable as shown below.
(2..5).forEach{ age ->
println(age)
}
//or
(2..5).forEach{
it -> println(it)
}
//Following is printed on the console:
2
3
4
5
Note: it is the default iterable variable that holds
the value of the current iterator.
● To check whether an element exists or doesn’t exist
in a range we use the in and !in keywords as
shown below.
var x = 5
if(x in 1..10)
{
print(“x exists in range”) //this gets
printed
}
else{
print(“x does not exist in range”)
}
x = 15
if(x !in 1..10)
{
print(“x does not exist in range”) //this
gets printed
}
else{
print(“x does exist in range”)
}
● And the following should work the same way. Right?
var x = 5
if(x in 10..1)
{
print(“x exists in range”)
}
else {
print(“x does not exist in range”)
//Ironically, this gets printed.
}
for (i in 5..0)
print(i) //prints nothing
● The Range .. can’t be used in the reverse order.
● This is where we use the downTo keyword.
● The below code would work:
var x = 5
if(x in 10 downTo 1)
{
print(“x exists in range”) //this gets printed
}
else{
print(“x does not exist in range”)
}
for (i in 5 downTo 0)
print(i) //543210
● To exclude the last element from the range we
use the keyword until.
for (i in 1 until 4) {
print(i)
}
//prints 123
● To traverse the range in steps we use the
keyword step.
for (i in 1..5 step 3) print(i) // prints 14
for (i in 4 downTo 1 step 2) print(i)
// prints 42
Kotlin while loop:
● while and do-while loops in Kotlin behave the
same way as they do in Java.
var i = 0
do {
i+=5
println(“Value of i is $i”) //prints 5
} while(i<1)
i=0
while(i<=5) {
print(i)
i++
}
//prints 012345
Kotlin break and continue:
● break is used to exit the loop there and then.
● continue is used to go to the next iteration of the
loop.
● Kotlin gives us the luxury to attach a label to the
break and continue statements to indicate the
loop on which their actions are triggered as
shown below:
customLabel@ for(y in 10 downTo 5) { // applying the
custom label
if(y == 6) {
print(“x is $y breaking here”)
break@customLabel //specifing the label
} else {
print(“continue to next iteration”)
continue@customLabel
}
}
Kotlin repeat and when:
● repeat allows us to execute the statements in
the loop N number of times(where N is the
number specified as the argument).
● The following code snippet would print the
group of statements 3 times.
repeat(3) {
println(“Hello World!”)
println(“Kotlin Control Flow”)
}
● when in Kotlin is equivalent to switch in
other languages, though with a different
syntax and more power!
A basic example of when operator is given
below.
var num = 10
when (num) {
0 -> print(“value is 0”)
5 -> print(“value is 5”)
else -> {
print(“value is neither 0 nor 5”) //this
gets printed.
}
}
● The when operator matches the argument with
all the branches. If it matches with none, the else
statement is printed. The else statement is
similar to default in switch.
● when operator can be used to return values too,
similar to if else.
var valueLessThan100 = when(101){
in 1 until 101 -> true
else -> {
false
}
}
print(valueLessThan100) //false
● Going further, we can use Any type to check
the branch as shown below.
fun month(month: Any) {
when(month) {
1 -> print(“January”)
2 -> print(“February”)
“MAR” -> print(“March”)
else -> {
print(“Any other month or it is invalid.
when operator takes generic type Any”) }
}
}
month(1) //”January”
month(“MAR”) //”March”
}
For Course Material Click Here
For Course Content Click Here