You are on page 1of 38

CHAPTER 1

INTRODUCTION

1.1 INTRODUCTION TO ANDROID

Android is an open source operating system based on Linux with a Java programming
interface for mobile devices such as Smartphone (Touch Screen Devices who supports
Android OS) as well for Tablets too. 

Android was developed by the Open Handset Alliance (OHA), which is led by Google.


The Open Handset Alliance(OHA) is consortium of multiple companies like Samsung,
Sony, Intel and many more to provide a services and deploy handsets using android platform.
All the source code for Android is available free on Git-Hub, Stack overflow and many more
websites. Google publishes most of the code under the Apache License version 2.0.

1.2 FEATURES OF ANDROID

Android is a powerful open source operating system which provides a lot of great features,
those are

 It’s an open source and we can customize the OS based on our requirements.
 It support connectivity for GSM, CDMA, WIFI, NFC, Bluetooth, etc. for telephony or
data transfer. It will allow us to make or receive a calls / SMS messages and we can
send or retrieve a data across mobile networks.
 Android have a multiple APIs to support a location-based services such as GPS
 We can perform all data storage related activities by using light weight
database SQLite.
 It have a wide range of media supports like AVI, MKV, FLV, MPEG4 etc. to play or
record variety of audio / video and having a different image formats like JPEG, PNG,
GIF, BMP, MP3, etc. 
1.3 ANDROID VERSIONS

Release Date Version API Level Version Name

September 23, 2008 Android 1.0 1 Apple Pie

February 9, 2009 Android 1.1 2 Banana Bread

April 30, 2009 Android 1.5 3 Cupcake

September 15, 2009 Android 1.5 4 Donut

October 25, 2009 Android 2.0 5 Éclair

May 20, 2010 Android 2.2 8 Froyo

December 5, 2010 Android 2.3 9 Gingerbread

February 22, 2011 Android 3.0.x 11 Honeycomb


Release Date Version API Level Version Name

October 18,2011 Android 4.0 14 Ice Cream Sandwich

July 9, 2012 Android 4.1 15 Jelly Bean

October 31, 2013 Android 4.4 19 Kitkat

October 17, 2014 Android 5.0 21 Lollipop

October 5, 2015 Android 5.0 23 Marshmallow

August 22, 2015 Android 7.0 24 Nougat

1.4 ANDROID APPLICATIONS

An android app is a software application running on the android platform.They are generally
developed in the java language using the Android SDK Android applications can be
packaged easily and sold out either through a store such as Google play,etc. There are many
android applications that we already know and uses them few are music ,news ,weathe
r,etc. Many android application are also available for free most of them are already
available in play store.This apps are compatible with almost every platform but few are also
available for the specific platform. Few apps are :

a) Weather
b) Google Drive
c) Waze and Google Maps
d) Google Search / Assistant / Feed
e) You Tube
1.5ANDROID APP DEVELOPMENT

Android App Development is a cycle through which new applications are created for Android
OS. Programming Languages used in Developing Android Applications
1. Java
2. Kotlin
Developing the Android Application using Kotlin is preferred by Google, as Kotlin is made
an official language for Android Development, which is developed and maintained by
JetBrains. Previously before Java is considered the official language for Android
Development. Kotlin is made official for Android Development in Google I/O 2017.

Advantages of Android Development


 The Android is an open-source Operating system and hence possesses a vast
community for support.
 The design of the Android Application has guidelines from Google, which
becomes easier for developers to produce more intuitive user applications.
Disadvantages of Android Development
 Fragmentation provides a very intuitive approach to user experience but it has
some drawbacks, where the development team needs time to adjust to the
various screen sizes of mobile smartphones that are now available in the market
and invoke the particular features in the application.
 The Android devices might vary broadly. So the testing of the application
becomes more difficult.

1.6 Android App Components

Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact.

There are following four main components that can be used within an Android application −

1. Activities

An activity represents a single screen with a user interface,in-short Activity performs actions
on the screen. For example, an email application might have one activity that shows a list of
new emails, another activity to compose an email, and another activity for reading emails. If
an application has more than one activity, then one of them should be marked as the activity
that is presented when the application is launched.

An activity is implemented as a subclass of Activity class as follows −

public class MainActivity extends Activity {


}
2. Services

A service is a component that runs in the background to perform long-running operations. For
example, a service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user interaction with an
activity.

A service is implemented as a subclass of Service class as follows −

public class MyService extends Service {


}
3. Broadcast Receivers

Broadcast Receivers simply respond to broadcast messages from other applications or from
the system. For example, applications can also initiate broadcasts to let other applications
know that some data has been downloaded to the device and is available for them to use, so
this is broadcast receiver who will intercept this communication and will initiate appropriate
action.

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each


message is broadcaster as an Intent object.

public class MyReceiver extends BroadcastReceiver {


public void onReceive(context,intent){}
}
Content Providers

A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. The data may be stored in
the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform transactions.

public class MyContentProvider extends ContentProvider {


public void onCreate(){}
}
Additional Components

There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are –

S.No Components & Description

Fragments
1
Represents a portion of user interface in an Activity.

Views
2
UI elements that are drawn on-screen including buttons, lists forms etc.

Layouts
3
View hierarchies that control screen format and appearance of the views.

Intents
4
Messages wiring components together.

Resources
5
External elements, such as strings, constants and drawable pictures.

6 Manifest
Configuration file for the application.

1.7 TOOLS USED TO DEVELOP ANDROID APP

The tools used are :

1. ANDROID STUDIO

Android Studio is the official Integrated Development Environment (IDE) for Android app
development, based on IntelliJ IDEA . On top of IntelliJ's powerful code editor and developer
tools, Android Studio offers even more features that enhance your productivity when building
Android apps, such as:

 A flexible Gradle-based build system

 A fast and feature-rich emulator

 A unified environment where you can develop for all Android devices

 Apply Changes to push code and resource changes to your running app without restarting
your app

 Code templates and GitHub integration to help you build common app features and import
sample code

 Extensive testing tools and frameworks

 Lint tools to catch performance, usability, version compatibility, and other problems

 C++ and NDK support

 Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud
Messaging and App Engine
Each project in Android Studio contains one or more modules with source code files and
resource files. Types of modules include:

 Android app modules

All the build files are visible at the top level under Gradle Scripts and each app module
contains the following folders:

 manifests: Contains the AndroidManifest.xml file.

 java: Contains the Java source code files, including JUnit test code.

 res: Contains all non-code resources, such as XML layouts, UI strings, and bitmap images.

2. SDK

A software development toolkit (SDK) is a set of software tools and programs provided by
hardware and software vendors that developers can use to build applications for specific
platforms. These providers make their SDKs available to help developers easily integrate
their apps with their services.

In order to use a SDK, a developer needs an iOS SDK to build iOS apps, an Android toolkit
for building Android apps, Nordic SDK to build Bluetooth or wireless apps and
a VMware SDK to enable integration with the VMware platform.

Although SDKs are largely associated with native mobile apps, developers can use them in
connection with websites, set-top boxes and other digital platforms.

SDKs include documentation, application programming interfaces (APIs), code samples,


libraries and processes, as well as guides that developers can use and integrate into their apps.
Developers can use SDKs to build and maintain applications without having to write
everything from scratch.

More specifically, SDKs include:


 Libraries or APIs - pre-defined pieces of code that let developers perform common
programming tasks on the platform.

 Integrated development environment (IDE) – a visual editor that helps developers


design and layout graphical elements, such as text boxes and buttons. These are
common in mobile software development toolkits. For instance, Apple’s IDE, Xcode,
contains a suite of software development tools to help developers build software for
macOS, iOS, iPadOS, watchOS and tvOS. There are numerous IDE options for
Android.

 Tools to help developers do such tasks as debugging, building, running and testing
their applications.

For example, if a developer wanted to share images or text from his or her app directly into
Facebook, he or she could look for Facebook’s Android SDK to find the necessary code that
would work for an Android device. This speeds deployment because the developer doesn’t
have to write the code from scratch.
CHAPTER 2
KOTLIN WORLD

2.1 INTRODUCTION TO KOTLIN

Kotlin is a general purpose, free, open source, statically typed “pragmatic” programming
language initially designed for the JVM (Java Virtual Machine) and Android that combines
object-oriented and functional programming features. It is focused on interoperability, safety,
clarity, and tooling support. Versions of Kotlin targeting JavaScript ES5.1 and native code
(using LLVM) for a number of processors are in production as well.

Kotlin originated at JetBrains, the company behind IntelliJ IDEA, in 2010, and has been open
source since 2012. The Kotlin team currently has more than 90 full-time members from
JetBrains, and the Kotlin project on GitHub has more than 300 contributors. JetBrains uses
Kotlin in many of its products including its flagship IntelliJ IDEA.

2.2 HISTORY OF KOTLIN

 In July 2011, JetBrains unveiled Project Kotlin, a new language for the JVM, which
had been under development for a year. JetBrains lead Dmitry Jemerov said that most
languages did not have the features they were looking for, with the exception of Scala.
However, he cited the slow compilation time of Scala as a deficiency. One of the
stated goals of Kotlin is to compile as quickly as Java. In February 2012, JetBrains
open sourced the project under the Apache 2 license.
 The name comes from Kotlin Island, near St. Petersburg. Andrey Breslav mentioned
that the team decided to name it after an island, just like Java was named after the
Indonesian island of Java (though the programming language Java was perhaps
named after the coffee rather than the island).
 JetBrains hopes that the new language will drive IntelliJ IDEA sales. Kotlin 1.0 was
released on February 15, 2016. This is considered to be the first officially stable
release and JetBrains has committed to long-term backwards compatibility starting
with this version.
 At Google I/O 2017, Google announced first-class support for Kotlin on Android.
Kotlin 1.2 was released on November 28, 2017. Sharing code between JVM and
JavaScript platforms feature was newly added to this release (as of version 1.4
multiplatform programming is an alpha feature upgraded from "experimental").
A full-stack demo has been made with the new Kotlin/JS Gradle Plugin.
 Kotlin 1.3 was released on 29 October 2018, bringing coroutines for asynchronous
programming.
 On 7 May 2019, Google announced that the Kotlin programming language is now its
preferred language for Android app developers.
 Kotlin 1.4 was released in August 2020, with e.g. some slight changes to the support
for Apple's platforms, i.e. to the Objective-C/Swift interop.
 Kotlin 1.5 was released in May 2021.
 Kotlin 1.6 was released in November 2021.
 Kotlin 1.7 was released in June 2022, including the alpha version of the new Kotlin
K2 compiler.

2.3 FEATURES OF KOTLIN

Following are the features of Kotlin :

1. Kotlin is Open-Source

The very first thing you should know about Kotlin is that it is an open-source programming
language. But, apart from being open-source, Kotlin also provides a single-click tool using
which, developers can convert existing Java code.

And if you’re an Android app developer who is new to Kotlin and interested in learning it
from scratch, we recommend starting with the beginner course available on Udemy and
Udacity. These courses will help you to sharpen your skills

2. Kotlin Supports Full Java Interoperability

One of the major as well as the best features of Android Kotlin is its deep interoperability
with Java. This, in fact, has attracted many Java developers as well as Android app
developers to learn Kotlin.
It basically runs on JVM and also supports Java libraries as well as tools, providing full Java
interoperability.

Both the languages co-exist, and this makes it easier for developers to be productive.
Developers can easily compile one Android project in both languages with the help of this
feature – interoperability function.

This will allow the developer to switch the programming language instead of changing the
codes. It will also save time for them to develop more Android apps.

It can show 100% interoperable. So, if you need access to a Kotlin method from a Java class
or vice versa, you can do it without any extra parameters.
3. Kotlin Comes With Lazy-Loading Feature

The lazy-loading feature basically increases the startup time, which is very useful when using
it for Android development.

In simple words, it’s the best solution for all developers who want to reduce their Android
app startup time so that their apps’ content can be shown faster.

With the lazy-loading feature, Android developers can load the only resources into main
memory which are necessary. If you are looking for this feature, then Kotlin is the best
choice.

For example, if you have a shopping app, the majority of users will only browse your
selection, that means you could have the payment API be lazy loaded.
4. Data Classes in Kotlin

The necessity of a class is always argued by programming language designers/makers.


Typically, a data class in Java contains lots of boilerplate code which developers have to
skip in order to find out the real use of that class.
But now in Kotlin, Android developers can write the equivalent of the same Java code in a
simple manner, and with lesser code. Therefore, the data classes in Kotlin are also known to
be one of the useful features.

5. Collection Filtering
We all know that when working with an API, we developers need to deal with collections
quite often. But by using Kotlin’s collection filtering feature, it’s easier to tell what your
resulting list should contain.

In fact, filtering a collection using the built-in Kotlin is very comparable to other
programming languages such as Swift collection types or Java 8 streams.
6. Reduces Crashes at Runtime

This is the most advanced feature, where it is easy to identify the Null Pointer
Exception while compiling your Android app development project.

This will ensure that every variable works as a non-null, and it helps in reducing the number
of crashes at runtime.

Moreover, if you decided to hold on to a null value, then reduce the number of crashes by
appending a question mark at the end of the variable type. This way, you can easily reduce
crashes at runtime.
2.4 VARIABLES AND OPERATORS IN KOTLIN
Variables And Operators used in Kotlin are discussed in below sections.
2.4.1 VARIABLES
 A variable is a location in memory (storage area) to hold data.To indicate the storage area,
each variable should be given a unique name (identifier).

How to declare a variable in Kotlin?

To declare a variable in Kotlin, either var or val keyword is used. Here is an example:

var language = "French"

val score = 95

The difference in using var and val is discussed later in the article. For now, let's focus on
variable declaration.
Here, language is a variable of type String, and score is a variable of type Int. You don't
have to specify the type of variables; Kotlin implicitly does that for you. The compiler knows
this by initializer expression ("French" is a String, and 95 is an integer value in the above
program). This is called type inference in programming.
However, you can explicitly specify the type if you want to:

var language: String = "French"

val score: Int = 95

We have initialized variable during declaration in above examples. However, it's not
necessary. You can declare variable and specify its type in one statement, and initialize the
variable in another statement later in the program.

var language: String // variable declaration of type String

... .. ...

language = "French" // variable initialization

val score: Int // variable declaration of type Int

... .. ...

score = 95 // variable initialization

Difference Between var and val


 val (Immutable reference) - The variable declared using val keyword cannot be
changed once the value is assigned. It is similar to final variable in Java.
 var (Mutable reference) - The variable declared using var keyword can be changed
later in the program. It corresponds to regular Java variable.
2.4.2 OPERATORS
Kotlin has a set of operators to perform arithmetic, assignment, comparison operators and
more. You will learn to use these operators in this article.
Operators are special symbols (characters) that carry out operations on operands (variables
and values). For example, + is an operator that performs addition.
 Arithmetic Operators

Here's a list of arithmetic operators in Kotlin:

Kotlin Arithmetic Operators

Operator Meaning

+ Addition (also used for string concatenation)

- Subtraction Operator

* Multiplication Operator

/ Division Operator

% Modulus Operator

 Assignment Operators

Assignment operators are used to assign value to a variable. We have already used simple
assignment operator = before.

val age = 5

Here, 5 is assigned to variable age using = operator.


Here's a list of all assignment operators and their corresponding functions:

Expression Equivalent to Translates to

a +=b a=a+b a.plusAssign(b)

a -= b a=a-b a.minusAssign(b)

a *= b a=a*b a.timesAssign(b)

a /= b a=a/b a.divAssign(b)
a %= b a=a%b a.modAssign(b)

 Unary prefix and Increment / Decrement Operators

Here's a table of unary operators, their meaning, and corresponding functions:

Operator Meaning Expression Translates to

+ Unary plus +a a.unaryPlus()

- Unary minus (inverts sign) -a a.unaryMinus()

! not (inverts value) !a a.not()

++ Increment: increases value by1 ++a a.inc()

-- Decrement: decreases value by 1 --a a.dec()

 Comparison and Equality Operators

Here's a table of equality and comparison operators, their meaning, and corresponding
functions:

Operator Meaning Expression Translates to

> greater than a>b a.compareTo(b) > 0

< less than a<b a.compareTo(b) < 0

>= greater than or equals to a >= b a.compareTo(b) >= 0

<= less than or equals 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))

 Logical Operators

There are two logical operators in Kotlin: || and &&.


Here's a table of logical operators, their meaning, and corresponding functions.

Operato Description Expression Corresponding


r Function

|| true if either of the Boolean (a>b)||(a<c) (a>b)or(a<c)


expression is true

&& true if all Boolean (a>b)&&(a< (a>b)and(a<c)


expressions are true c)

Note that, or and and are functions that support infix notation.


Logical operators are used in control flow such as if expression, when expression, and loops.
 in Operator

The in operator is used to check whether an object belongs to a collection.


Operator Expression Translates to

in a in b b.contains(a)

!in a !in b !b.contains(a)

 Index access Operator

Here are some expressions using index access operator with corresponding functions in
Kotlin.

Expression Translated to

a[i] a.get(i)

a[i, n] a.get(i, n)
a[i1, i2, ..., in] a.get(i1, i2, ..., in)

a[i] = b a.set(i, b)

a[i, n] = b a.set(i, n, b)

a[i1, i2, ..., in] = b a.set(i1, i2, ..., in, b)

2.5 STRINGS, FUNCTIONS AND ARRAYS IN KOTLIN

2.5.1 STRINGS

Strings are a sequence of characters. For example, "Hello there!" is a string literal.


In Kotlin, all strings are objects of String class. Meaning, string literals such as "Hello
there!" are implemented as instances of this class. 
How to create a String variable?
Here is how you can define a String variable in Kotlin. For example,

val myString = "Hey there!"

Here, myString is a variable of type String.


You can declare variable of type String and specify its type in one statement, and initialize
the variable in another statement later in the program.

val myString: String

... .. ...

myString = "Howdy"

2.5.1.1 STRING FUNCTIONS

Functions Description
compareTo(other: String): Int It compares the current object with
specified object for order. It returns zero if
current is equals to specified other object.

get(index: Int): Char It returns the character at given index from


the current character sequence.

plus(other: Any?): String It returns the concatenate string with the


string representation of the given other
string.

subSequence(startIndex: Int,endIndex: Int): It returns the new character sequence from


CharSequence current character sequence, starting from
startIndex to endIndex.

CharSequence.contains(other: CharSequence, It returns true if the character sequence


ignoreCase: Boolean = false):Boolean contains the other specified character
sequence.

CharSequence.count(): Int It returns the length of char sequence.

String.drop(n: Int): String It returns a string after removing the first n


character.

String.dropLast(n: Int): String It returns a string after removing the last n


character.

String.dropWhile It returns a character sequence which


(predicate: (Char) -> Boolean contains all the characters, except first
): String characters which satisfy the given
predicate.
CharSequence.elementAt(index: Int): Char It returns a character at the given index or
throws an IndexOutOfBoundsException if
the index does not exist in character
sequence.

CharSequence.indexOf(char: Char, startIndex: Int It returns the index of first occurrence of


= 0, the given character, starting from the given
ignoreCase: Boolean = false index value.
): Int

CharSequence.indexOfFirst( It returns the index of first character which


predicate: (Char) -> Boolean match the given predicate, or -1 if the
): Int character sequence not contains any such
character.

CharSequence.indexOfLast( It returns the index of last character which


predicate: (Char) -> Boolean match the given predicate, or -1 if the
): Int character sequence not contains any such
character.

CharSequence.getOrElse(index: Int, defaultValue: It returns the character at specified index or


(Int) ->Char): Char the result of calling the defaultValue
function if the index is out of bound of
current character sequence.

CharSequence.getOrNull(index: Int): Char? It returns a character at the given index or


returns null if the index is out of bound
from character sequence.

2.5.1.2 String elements and templates


 String elements

The characters which are present in string are known as elements of string. Element of string
are accessed by indexing operation string[index]. String's index value starts from 0 and ends
at one less than the size of string string[string.length-1]. Index 0 represent first element, index
1 represent second element and so on.

1. val str ="Hello, javatpoint"  
2. println(str[0]) //prints H  
 String templates

String template expression is a piece of code which is evaluated and its result is returned into
string. Both string types (escaped and raw string) contain template expressions. String
templates starts with a dollar sign $ which consists either a variable name or an arbitrary
expression in curly braces.

String template as variable name:

val i =10  
print("i = $i") //i=10  
  
fun main(args: Array<String>) {  
val i =10  
    print("i = $i")//i=10  
}  

Output:

i=10

2.5.2 FUNCTIONS

Function is a group of related statements that perform a specific task.

Functions are used to break a large program into smaller and modular chunks. For example,
you need to create and color a circle based on input from the user. You can create two
functions to solve this problem:
 createCircle() Function
 colorCircle() Function
Dividing a complex program into smaller components makes our program more organized
and manageable.

Furthermore, it avoids repetition and makes code reusable.

Types of Functions

Depending on whether a function is defined by the user, or available in standard library, there
are two types of functions:
 Kotlin Standard Library Function

 User-defined functions

1. Kotlin Standard Library Function

The standard library functions are built-in functions in Kotlin that are readily available for
use. For example,

 print() is a library function that prints message to the standard output stream
(monitor).
 sqrt() returns square root of a number (Double value)

fun main(args: Array<String>) {

var number = 5.5


print("Result = ${Math.sqrt(number)}")
}

 When you run the program, the output will be:

 Result = 2.345207879911715

2. User-defined Functions

As mentioned, you can create functions yourself. Such functions are called user-defined
functions.
How to create a user-defined function in Kotlin?

Before you can use (call) a function, you need to define it.

Here's how you can define a function in Kotlin:

fun callMe() {

// function body

To define a function in Kotlin, fun keyword is used. Then comes the name of the function
(identifier). Here, the name of the function is callMe.
In the above program, the parenthesis ( ) is empty. It means, this function doesn't accept any
argument. You will learn about arguments later in this article.
The codes inside curly braces { } is the body of the function.
2.5.3 ARRAYS
Array is one of the most fundamental data structure in practically all programming
languages. The idea behind an array is to store multiple items of the same data-type,such as
an integer or string under a single variable name.
Arrays are used to organize data in programming so that a related set of values can be
easily sorted or searched.
Here are some basic properties of arrays –
 They are stored in contiguous memory locations.
 They can be accessed programmatically through their indexes (array[1],
array[0], etc.)
 They are mutable.
 Their size is fixed.
Creating an array
In Kotlin, arrays are not a native data type, but a mutable collection of similar items which
are represented by the Array class.There are two ways to define an array in Kotlin.
Using the arrayOf() function –
We can use the library function arrayOf() to create an array by passing the values of the
elements to the function.
Syntax:
val num = arrayOf(1, 2, 3, 4) //implicit type declaration

val num = arrayOf<Int>(1, 2, 3) //explicit type declaration

2.6 CONDITIONALS, LOOPS AND LISTS

2.6.1 CONDITIONALS

1. Kotlin if expression

Unlike Java (and other many programming languages), if can be used an


expression in Kotlin; it returns a value. Recommended Reading: Kotlin expression
Here is an example:
Example: Kotin if expression

fun main(args: Array<String>) {

val number = -10

val result = if (number > 0) {


"Positive number"
} else {
"Negative number"
}

println(result)
}

When you run the program, the output will be:

Negative number

The else branch is mandatory when using if as an expression.


2. Kotlin Nested if Expression
An if expression can be inside the block of another if expression known as nested
if expression.
Example: Nested if Expression
This program computes the largest number among three numbers.

fun main(args: Array<String>) {

val n1 = 3
val n2 = 5
val n3 = -2

val max = if (n1 > n2) {


if (n1 > n3)
n1
else
n3
} else {
if (n2 > n3)
n2
else
n3
}

println("max = $max")
}

When you run the program, the output will be:

max = 5

2.6.2 LOOPS

Loop is used in programming to repeat a specific block of code until certain


condition is met (test expression is false).
Loops are what makes computers interesting machines. Imagine you need to
print a sentence 50 times on your screen. Well, you can do it by using print
statement 50 times (without using loops). How about you need to print a
sentence one million times? You need to use loops.

2.6.2.1 for-LOOP

The for loop in Kotlin iterates through anything that provides an iterator. In this
article, you learn to create for loop (with the help of examples).

There is no traditional for loop in Kotlin unlike Java and other languages.
In Kotlin, for loop is used to iterate through ranges, arrays, maps and so on
(anything that provides an iterator).
The syntax of for loop in Kotlin is:

for (item in collection) {

// body of loop

2.6.3 LISTS

A list is a collection of items with a specific order. There are two types of lists in Kotlin:

 Read-only list: List cannot be modified after you create it.


 Mutable list: MutableList can be modified after you create it, meaning you can add,
remove, or update its elements.

When using List or MutableList, you must specify the type of element that it can contain. For
example, List<Int> holds a list of integers and List<String> holds a list of Strings. If you define
a Car class in your program, you can have a List<Car> that holds a list of Car object instances.

2.7 ERRORS AND EXCEPTIONS

 Errors
The error signifies a situation that mostly happens due to the absence of system resources.
The system crash and memory errors are an example of errors. It majorly occurs at runtime.

 Exceptions

Exceptions are problems that occur during the program execution and disrupt the
conventional flow. This can occur due to various reasons like invalid arithmetic operation, a
reference to a null object. There are two types of exceptions: Checked exceptions and
Unchecked exceptions.

Kotlin Exception

In Kotlin, there are only unchecked exceptions that are thrown during the runtime execution
of the program. All exception classes descend from the class Throwable. Kotlin uses
the throw keyword to throw an exception object.

2.7.1 Using try catch block to handle exceptions in kotlin

Kotlin try-catch block is used for exception handling in the code. The try block encloses the
code which may throw an exception and the catch block is used to handle the exception. This
block must be written within the method. Kotlin try block must be followed by
either catch block or finally block or both.

Syntax of try with catch block

try{    
//code that may throw exception    
}catch(e: SomeException){  
//code that handles exception  
}    
Syntax of try with finally block

try{    
//code that may throw exception    
}finally{  
// code finally block  
}    
Syntax of try catch with finally block

try {  
    // some code  
}  
catch (e: SomeException) {  
    // handler  
}  
finally {  
    // optional finally block  
}  

Problem without Exception Handling

Lets's see an example which causes exception which is not handled.

fun main(args: Array<String>){  
    val data = 20 / 0   //may throw exception  
    println("code below exception ...")  
}  

This above program generates an exception, which causes rest of code below the
exception not executable.

Output:

Excejava.lang.ArithmeticException: / by zero
at ExceptionHandlingKt.main(ExceptionHandling.kt:2)

Kotlin try block as an Expression


We can use try block as an expression which returns a value. The value returned by try
expression is either the last expression of try block or the last expression of catch. Contents of
the finally block do not affect the result of the expression.
Kotlin try as an expression example

Let's see an example of try-catch block as an expression which returns a value. In this
example String value to Int which does not generate any exception and returns last statement
of try block.

fun main(args: Array<String>){  
val str = getNumber("10")  
    println(str)  
}  
fun getNumber(str: String): Int{  
    return try {  
        Integer.parseInt(str)  
    } catch (e: ArithmeticException) {  
        0  
    }  
}  

Output:

10

Let's modify the above code which generate an exception and return the last statement of
catch block.

fun main(args: Array<String>){  
val str = getNumber("10.5")  
    println(str)  
}  
fun getNumber(str: String): Int{  
    return try {  
        Integer.parseInt(str)  
    } catch (e: NumberFormatException) {  
        0  
    }  
}  

Output:

Next Topic
2.7.2 NULL POINT EXCEPTION

Since the NullPointerException is a runtime exception, it doesn't need to be caught and


handled explicitly in application code. The NullPointerException occurs due to a situation in
application code where an uninitialized object is attempted to be accessed or modified.
Essentially, this means the object reference does not point anywhere and has a null value.

Kotlin Null Safety

Basically, Kotlin null safety has been proposed to eliminate NullPointerException form the
code. NullPointerException can just only possible on following situations:

 Throw NullPointerException() as a forceful call


 Using external java code as Kotlin, which means Java interoperability.
 An uninitialized of this operator that is available in a constructor passed and used another
place.
 Use of the !! operator
 A superclass constructor calls an open member.

2.8 CLASSES AND OBJECTS

2.8.1 Kotlin Classes

A class is a blueprint for the objects which defines a template to be used to create the required
objects.
Classes are the main building blocks of any Object Oriented Programming language. A
Kotlin class is defined using the class keyword. Following is the syntax to create a Kotlin
Class:

A Kotlin class declaration is similar to Java Programmig which consists of a class


header and a class body surrounded by curly braces.

class ClassName { // Class Header

//
// Variables or data members
// Member functions or Methods
//
...
...
}

2.8.2 Kotlin Objects

The objects are created from the Kotlin class and they share the common properties and
behaviours defined by a class in form of data members (properties) and member functions
(behaviours) respectively.

The syntax to declare an object of a class is:

var varName = ClassName()

We can access the properties and methods of a class using the . (dot) operator as shown
below:

Var varName =ClassName()

varName.property = <Value>
varName.functionName()

Example

Following is an example where we will create one Kotlin class and its object through which
we will access different data members of that class.
class myClass {
// Property (data member)
private var name: String = "Tutorialspoint.com"

// Member function
fun printMe() {
print("The best Learning website - " + name)
}
}
fun main(args: Array<String>) {
val obj = myClass() // Create object obj of myClass class
obj.printMe() // Call a member function using object
}

2.9 INHERTANCE AND INTERFACE

2.9.1 KOTLIN INHERITANCE

Inheritance is one of the key features of object-oriented programming. It allows user to create
a new class (derived class) from an existing class (base class).

The derived class inherits all the features from the base class and can have additional features
of its own.

Suppose, in your application, you want three characters - a math teacher, a footballer and


a businessman.
Since, all of the characters are persons, they can walk and talk. However, they also have some
special skills. A math teacher can teach math, a footballer can play football and a
businessman can run a business.
You can individually create three classes who can walk, talk and perform their special skill.
In each of the classes, you would be copying the same code to walk and talk for each
character.

If you want to add a new feature - eat, you need to implement the same code for each
character. This can easily become error-prone (when copying) and duplicate codes.

It would be a lot easier if we had a Personclass with basic features like talk, walk, eat,
sleep, and add special skills to those features as per our characters. This is done using
inheritance.
Using inheritance, now you don't implement the same code
for walk(), talk() and eat() for each class. You just need to inherit them.
So, for MathTeacher (derived class), you inherit all features of a Person (base class)
and add a new feature teachMath(). Likewise, for the Footballer class, you inherit
all the features of the Person class and add a new feature playFootball() and so on.
This makes your code cleaner, understandable and extendable.

It is important to remember: When working with inheritance, each derived class should


satisfy the condition whether it "is a" base class or not. In the example
above, MathTeacher is a Person, Footballer is a Person. You cannot have
something like, Businessman is a Business.

Let's try to implement the above discussion in code:

open class Person(age: Int) {

// code for eating, talking, walking

class MathTeacher(age: Int): Person(age) {

// other features of math teacher

class Footballer(age: Int): Person(age) {

// other features of footballer


}

class Businessman(age: Int): Person(age) {

// other features of businessman

2.9.2 INTERFACE

Interfaces are custom types provided by Kotlin that cannot be instantiated directly.


Instead, these define a form of behavior that the implementing types have to follow. With
the interface, you can define a set of properties and methods, that the concrete types must
follow and implement.

Creating Interfaces –

The interface definition in Kotlin begins with the interface keyword followed by the name
of the interface, followed by the curly braces within which the members of the interface
reside. The difference is that the members will have no definition of their own. These
definitions will be provided by the conforming types.
Example:
interface Vehicle()

fun start()

fun stop()
}

Implementing Interfaces –

An interface can be implemented by a class or an object. When implementing an interface,


the conforming type must provide the definition for all of its members. To implement an
interface, the name of the custom type is followed by a colon and the name of the interface
which is to be implemented.

class Car: Vehicle

Example to demonstrate an interface in Kotlin –

interface Vehicle {

    fun start()

    fun stop()

  

class Car : Vehicle {

    override fun start()


    {

        println("Car started")

    }

override fun stop()

    {

        println("Car stopped")

    }

fun main()

    val obj = Car()

    obj.start()
    obj.stop()

Output:
Car started

Car stopped

Explanation:
In this program, the interface Vehicle declares two methods start() and stop(), which need
to be overridden. The class Car implements the interface using the class-literal syntax and
overrides the two methods using the override keyword. Finally, the main function creates
an object of class Car and calls the two methods.

You might also like