This document provides an introduction to the Kotlin programming language. It discusses Kotlin's history and key features such as being free, open-source, and running on the JVM. It then covers basic Kotlin concepts like data types, variables, operators, control flow statements, and functions. The document gives examples to illustrate Kotlin keywords, variables, data types like numbers, characters and strings, and operators like arithmetic, relational, and logical operators. It also demonstrates the use of control structures like if/else, when, for loops, while loops, and break/continue statements.
3. INTRODUCTION TO KOTLIN
Kotlin is a programming language introduced by JetBrains in 2011, the official designer of the most
intelligent java ide, named Intellij Idea. Kotlin is free, has been free and will remain free. It is
developed under the apache 2.0 license. This is a strongly statically typed general-purpose
programming language that runs on jvm. Following are the great companies who are using Kotlin:
•Google
•Amazon
•Netflix
•Pinterest
•Many more…..
4. Kotlin Program Entry Point :-
Anentrypoint of a Kotlinapplication is themain()function.
fun main()
{
var string: String = "Hello, World!"
println("$string")
}
(or)
fun main(args: Array<String>)
{
println("Hello, world!")
}
6. Kotlin - Keywords
Kotlin Soft Keywords
by catch constructor delegate
dynamic field file finally
get import init param
property receiver set setparam
value where
Kotlin Modifier Keywords
actual abstract annotation companion
const crossinline data enum
expect external final infix
inline inner internal lateinit
noinline open operator out
override private protected public
reified sealed suspend tailrec
vararg
7. Kotlin - Variables
Variables are an important part of any programming. They are the names you givetocomputer memory locations which are usedto store values in a computer program and later you use those names to
retrievethestoredvaluesandusetheminyourprogram.Kotlinvariablesarecreatedusingeithervar orval keywordsand thenanequalsign= isusedtoassignavaluetothosecreatedvariables.
Kotlin Mutable Variables
Mutablemeansthatthevariablecan bereassignedtoadifferentvalueafterinitialassignment.To declareamutablevariable,weusethevarkeyword
fun main()
{
var name = "Zara Ali"
println("Name = $name")
name = "Nuha Ali"
println("Name = $name")
}
8. Kotlin - Variables
Kotlin Read-only Variables
Aread-only variable can be declared using val (instead ofvar)andonce a valueis assigned, it can not bere-assigned.
Kotlin Variable Naming Rules
Therearecertainrulestobe followedwhile namingthe Kotlinvariables:
•Kotlinvariablenamescancontainletters,digits,underscores,anddollarsigns.
•Kotlinvariablenamesshouldstartwitha letter,$ orunderscores
•KotlinvariablesarecasesensitivewhichmeansZaraandZARA aretwo differentvariables.
•Kotlinvariablecannothaveany whitespaceorothercontrolcharacters.
•Kotlinvariablecannothavenameslike var,val,String,Intbecausethey arereservedkeywordsinKotlin.
9. Kotlin - Data Types
Kotlin built indatatype canbe categorizedasfollows:
Number
Character
String
Boolean
Array
10. (a) Kotlin Number Data Types :-
Data Type Size (bits) Data Range
Byte 8 bit -128 to 127
Short 16 bit -32768 to 32767
Int 32 bit -2,147,483,648 to 2,147,483,647
Long 64 bit -9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
Float 32 bit 1.40129846432481707e-45 to
3.40282346638528860e+38
Double 64 bit 4.94065645841246544e-324 to
1.79769313486231570e+308
11. Example :-
fun main(args: Array<String>)
{
val a: Int = 10000
val d: Double = 100.00 val
f: Float = 100.00f
val l: Long = 1000000004
val s: Short = 10
val b: Byte = 1
println("Int Value is " + a)
println("Double Value is " + d)
println("Float Value is " + f)
println("Long Value is " + l )
println("Short Value is " + s)
println("Byte Value is " + b) }
12. (b) Kotlin Character Data Type :-
fun main(args: Array<String>)
{
val letter: Char // defining a Char variable
letter = 'A' // Assigning a value to it
println("$letter")
}
13. Kotlin String Data Type :-
The Stringdata type is used tostore a sequence ofcharacters. String values must be surrounded by double quotes ("") ortriplequote (""" """).
We have twokinds ofstring available in Kotlin- one iscalled EscapedString andanother iscalled Raw String.
•Escapedstring isdeclared within double quote (" ")andmay contain escape characters like 'n', 't','b' etc.
•Raw string is declared within triplequote (""" """) andmay contain multiple lines oftext without any escape characters.
14. Example:-
fun main(args: Array<String>)
{
val escapedString : String = "I am escaped String!n"
var rawString :String = """This is going to be a multi-line string and will not have any escape
sequence""";
print(escapedString)
println(rawString)
}
15. Kotlin Boolean Data Type :-
Boolean is very simple like other programminglanguages. We have only twovalues forBoolean data type - either true orfalse.
fun main(args: Array<String>)
{
val A: Boolean = true // defining a variable with true value
val B: Boolean = false // defining a variable with false value
println("Value of variable A "+ A )
println("Value of variable B "+ B )
}
16. Kotlin Array Data Type :-
Kotlin arraysareacollection ofhomogeneous data.Arrays areused tostore multiple values in a single variable,instead of declaring separate variablesforeach
value.
fun main(args: Array<String>)
{
val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
println("Value at 3rd position : " + numbers[2])
}
17. Kotlin Data Type Conversion :-
Typeconversionisa processinwhichthevalue ofone datatype isconvertedintoanothertype. Kotlindoesnotsupportdirectconversionofonenumericdatatype toanother,
For example,itisnotpossibletoconvertanInttype to aLongtype:
To convert a numeric data type to another type, Kotlin provides a set of functions:
toByte()
toShort()
toInt()
toLong()
toFloat()
toDouble()
toChar()
18. Kotlin Operators
Operators are the special symbols that perform different operation on operands. For example
+ and – are operators that perform addition and subtraction respectively. Like Java, Kotlin
contains different kinds of operators.
• Arithmetic operator
• Relation operator
• Assignment operator
• Unary operator
• Logical operator
• Bitwise operator
19. Arithmetic Operators
Operators Meaning Expression Translate to
+ Addition 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)
20. Relation 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
21. Assignment Operators
Operators Expression Translate to
+= a = a + b a.plusAssign(b) > 0
-= a = a – b a.minusAssign(b) < 0
*= a = a * b a.timesAssign(b)>= 0
/= a = a / b a.divAssign(b) <= 0
%= a = a % b a.remAssign(b)
23. 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()
24. 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()
inv bitwise inverse a.inv()
25. Kotlin Control Flow Statements :-
Kotlin flow control statements determine the next statement tobe executed. For example,
if
if – else
when
while
for
do
26. Kotlin if...else Expression
Kotlin if...else canalso be used asanexpression whichreturnsa valueand thisvaluecanbe assigned to avariable.Below is a simple
syntaxof Kotlinif...else expression:
val result = if (condition) {
// code block A to be executed if condition is true
} else {
// code block B to be executed if condition is false
}
28. Kotlin when expression
when expression is far easy and more clean in comparison to writing many if...else if expressions. Kotlin when expression evaluates a
sectionof code among manyalternativesasexplained in below example.
Kotlin when matchesits argumentagainstall branchessequentiallyuntilsome branchcondition is satisfied.
Kotlin when expression is similar to the switch statementin C, C++ and Java.
29. Example 1
fun main(args: Array<String>) {
val day = 2
val result = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result)
}
30. Example 2
We cancombine multiple when conditions into asingle condition.
fun main(args: Array<String>) {
val day = 2 when (day) {
1, 2, 3, 4, 5 -> println("Weekday")
else -> println("Weekend")
}
}
31. Example 3
Kotlin rangesarecreatedusing double dots .. andwe canusethem while checking when condition withthehelpof inoperator.
fun main(args: Array<String>) {
val day = 2
when (day) {
in 1..5 -> println("Weekday")
else -> println("Weekend")
}
}
32. Kotlin For loop
Kotlin forloop iteratesthroughanythingthatprovides aniterator ie. thatcontainsa countablenumber of values,for example arrays,
ranges,maps or anyother collection availablein Kotlin.
Kotlin does notprovide a conventionalforloop whichis available inC, C++ andJavaetc. Syntax
Thesyntaxof theKotlin forloop is asfollows:
for (item in collection) {
// body of loop
}
33. Example 1
Following is anexample wheretheloop iteratesthroughthe rangeandprintsindividual item. To iterateover a rangeof numbers, we
willuse arangeexpression:
fun main(args: Array<String>) {
for (item in 1..5) {
println(item)
}
}
34. Example 2
Let's seeone more example wheretheloop williteratethroughanotherrange,but thistime it willstep down insteadof stepping up asin
theabove example:
fun main(args: Array<String>) {
for (item in 5 downTo 1 step 2) {
println(item)
}
}
35. Example 3
Following is anexample wherewe used forloop to iteratethroughanarrayof strings:
fun main(args: Array<String>) {
var fruits = arrayOf("Orange", "Apple", "Mango", "Banana")
for (item in fruits) {
println(item)
}
}
36. Kotlin – while loop
Kotlin whileloop executes itsbody continuouslyaslong asthespecified condition is true.
Kotlin whileloop is similar to Java while loop.
Syntax :
Thesyntaxof theKotlin whileloop is asfollows:
while (condition) {
// body of the loop
}
37. Example
Following is anexample wherethewhile loop continueexecuting thebody of theloop aslong asthecountervariable i is greaterthan0:
fun main(args: Array<String>) {
var i = 5;
while (i > 0) {
println(i) i–
}
}
38. Kotlin – do … while loop
Thedo..while is similar to the while loop with a difference that the this loop will execute the code block once,before checkingif the condition
is true,then it will repeat the loop as long as the condition is true.
Theloop will always be executed at least once, even if the condition is false, because the code block is executedbefore the condition is tested.
Syntax:
Thesyntax of theKotlin do...while loop is as follows:
do{
// body of the loop
}while( condition )
39. Example
Following is anexample wherethedo...while loop continueexecutingthe body of the loop as long asthecountervariable i is greater
than0:
fun main(args: Array<String>) {
var i = 5;
do{
println(i)
i–
}while(i > 0)
}
40. Kotlin – Break Statement
Kotlin breakstatement is usedto come out of a loop once a certain condition is met. This loop could bea for, while ordo...while loop.
// Using break in for loop
for (...) {
if(test){
break
}
}
41. Kotlin – Break Statement
// Using break in while loop
while (condition) {
if(test){
break
}
}
// Using break in do...while loop
do {
if(test){
break
}
} while(condition)
42. Kotlin – Labeled Break Statement
Kotlin label is theform of identifier followed by the @ sign,for example test@or outer@. To makeanyKotlin Expression aslabeled
one, we justneed to putalabel infront of theexpression.
Kotlin labeled break statementis used to terminatethespecific loop. Thisis done byusing break expression with@ signfollowed by
labelname(break@LabelName).
Syntax:
outerLoop@ for (i in 1..100) {
// ...
}
43. Example
fun main(args: Array<String>) {
outerLoop@ for (i in 1..3) {
innerLoop@ for (j in 1..3) {
println("i = $i and j = $j")
if (i == 2){
break@outerLoop
}
}
}
}
44. Kotlin Continue Statement
TheKotlincontinue statementbreaks theloop iterationin between(skips thepart nextto thecontinuestatementtillend of theloop)
andcontinueswiththenext iterationin theloop.
// Using continue in for loop
for (...) {
if(test){
continue
}
}
45. Kotlin – Continue Statement
// Using continue in while loop
while (condition) {
if(test){
continue
}
}
// Using continue in do...while loop
do {
if(test){
continue
}
}while(condition)
46. Kotlin – labelled Continue
Statement
Kotlin labeled continue statement is used to skip the part of a specific loop. This is done by using continue expression with @ sign followed by label name (continue@LabelName).
fun main(args: Array<String>) {
outerLoop@ for (i in 1..3) {
innerLoop@ for (j in 1..3) {
if (i == 2){
continue@outerLoop
}
println("i = $i and j = $j")
}
}
}