SlideShare a Scribd company logo
1 of 50
Compose
Code
Camp
GDSC ANDROID
DEVELOPMENT TEAM,
GPREC.
Topics :-
 Introduction
 KeyWords
 Input Output
 Data Types
 Operators
 Flow Controls
 Functions
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…..
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!")
}
Kotlin - Keywords
Kotlinkeywordshavebeencategorizedintothreebroadcategories:(a)HardKeywords(b) SoftKeywords(c) ModifierKeywords
Kotlin Hard Keywords
as as? break class
continue do else false
for fun if in
!in interface is !is
null object package return
super this throw true
try typealias typeof val
var when while
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
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")
}
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.
Kotlin - Data Types
Kotlin built indatatype canbe categorizedasfollows:
 Number
 Character
 String
 Boolean
 Array
(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
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) }
(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")
}
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.
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)
}
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 )
}
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])
}
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()
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
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)
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
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)
Unary Operators
Operators Expression Translate to
++ ++a or a++ a.inc()
— –a or a– a.dec()
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()
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()
Kotlin Control Flow Statements :-
Kotlin flow control statements determine the next statement tobe executed. For example,
 if
 if – else
 when
 while
 for
 do
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
}
Example
fun main(args: Array<String>) {
val age:Int = 10
val result = if (age > 18) {
"Adult"
} else {
"Minor"
}
println(result)
}
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.
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)
}
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")
}
}
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")
}
}
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
}
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)
}
}
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)
}
}
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)
}
}
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
}
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–
}
}
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 )
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)
}
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
}
}
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)
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) {
// ...
}
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
}
}
}
}
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
}
}
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)
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")
}
}
}
QUIZ TIME!!!
Q&A Session!
Thank you! 

More Related Content

Similar to Compose Code Camp (1).pptx

Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 

Similar to Compose Code Camp (1).pptx (20)

Vizwik Coding Manual
Vizwik Coding ManualVizwik Coding Manual
Vizwik Coding Manual
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Kotlin
KotlinKotlin
Kotlin
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
C++
C++C++
C++
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 

Compose Code Camp (1).pptx

  • 2. Topics :-  Introduction  KeyWords  Input Output  Data Types  Operators  Flow Controls  Functions
  • 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!") }
  • 5. Kotlin - Keywords Kotlinkeywordshavebeencategorizedintothreebroadcategories:(a)HardKeywords(b) SoftKeywords(c) ModifierKeywords Kotlin Hard Keywords as as? break class continue do else false for fun if in !in interface is !is null object package return super this throw true try typealias typeof val var when while
  • 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)
  • 22. Unary Operators Operators Expression Translate to ++ ++a or a++ a.inc() — –a or a– a.dec()
  • 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 }
  • 27. Example fun main(args: Array<String>) { val age:Int = 10 val result = if (age > 18) { "Adult" } else { "Minor" } println(result) }
  • 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") } } }
  • 47.