Kotlin Operator

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

Kotlin Operator

Operators are special characters which perform operation on operands (values or


variable).There are various kind of operators available in Kotlin.

o Arithmetic operator
o Relation operator
o Assignment operator
o Unary operator
o Bitwise operation
o Logical operator

Arithmetic Operator
Arithmetic operators are used to perform basic mathematical operations such as addition
(+), subtraction (-), multiplication (*), division (/) etc.

Operator Description Expression Translate to

+ Addition a+b a.plus(b)

- Subtraction a-b a.minus(b)

* Multiply a*b a.times(b)

/ Division a/b a.div(b)

% Modulus a%b a.rem(b)

Example of Arithmetic Operator


1. fun main(args : Array<String>) {
2. var a=10;
3. var b=5;
4. println(a+b);
5. println(a-b);
6. println(a*b);
7. println(a/b);
8. println(a%b);
9. }

Relation Operator
Relation operator shows the relation and compares between operands. Following are the
different relational operators:

Operator Description Expression Translate to

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

< Less than a<b a.compateTo(b)<0

>= greater than or equal to a>=b a.compateTo(b)>=0

<= less than or equal to a<=b a?.equals(b)?:(b===null)

== is equal to a==b a?.equals(b)?:(b===null)

!= not equal to a!=b !(a?.equals(b)?:(b===null))

Example of Relation Operator

1. fun main(args : Array<String>) {


2. val a = 5
3. val b = 10
4. val max = if (a > b) {
5. println("a is greater than b.")
6. a
7. } else{
8. println("b is greater than a.")
9. b
10. }
11. println("max = $max")
12. }
String literals may contain template expressions – pieces of code that are evaluated and whose
results are concatenated into the string. A template expression starts with a dollar sign ( $) and
consists of either a name:

Assignment operator
Assignment operator "=" is used to assign a value to another variable. The assignment of
value takes from right to left.

Operator Description Expression Convert to

+= add and assign a+=b a.plusAssign(b)

-= subtract and assign a-=b a.minusAssign(b)

*= multiply and assign a*=b a.timesAssign(b)

/= divide and assign a/=b a.divAssign(b)

%= mod and assign a%=b a.remAssign(b)

Example of Assignment operator

1. fun main(args : Array<String>) {


2.
3. var a =20;var b=5
4. a+=b
5. println("a+=b :"+ a)
6. a-=b
7. println("a-=b :"+ a)
8. a*=b
9. println("a*=b :"+ a)
10. a/=b
11. println("a/=b :"+ a)
12. a%=b
13. println("a%=b :"+ a)
14.
15. }
Unary Operator
Unary operator is used with only single operand. Following are some unary operator given
below.

Operator Description Expression Convert to

+ unary plus +a a.unaryPlus()

- unary minus -a a.unaryMinus()

++ increment by 1 ++a a.inc()

-- decrement by 1 --a a.dec()

! not !a a.not()

Example of Unary Operator

1. fun main(args: Array<String>){


2. var a=10
3. var b=5
4. var flag = true
5. println("+a :"+ +a)
6. println("-b :"+ -b)
7. println("++a :"+ ++a)
8. println("--b :"+ --b)
9. println("!flag :"+ !flag)
10. }

Logical Operator
Logical operators are used to check conditions between operands. List of logical operators
are given below.

Operator Description Expression Convert to

&& return true if all expression are true (a>b) && (a>c) (a>b) and (a>c)
|| return true if any expression are true (a>b) || (a>c) (a>b) or(a>c)

! return complement of expression !a a.not()

Example of Logical Operator

1. fun main(args: Array<String>){


2. var a=10
3. var b=5
4. var c=15
5. var flag = false
6. var result: Boolean
7. result = (a>b) && (a>c)
8. println("(a>b) && (a>c) :"+ result)
9. result = (a>b) || (a>c)
10. println("(a>b) || (a>c) :"+ result)
11. result = !flag
12. println("!flag :"+ result)
13.
14. }

Bitwise Operation
In Kotlin, there is not any special bitwise operator. Bitwise operation is done using named
function.

Named Function Description Expression

shl (bits) signed shift left a.shl(b)

shr (bits) signed shift right a.shr(b)

ushr (bits) unsigned shift right a.ushr(b)

and (bits) bitwise and a.and(b)

or (bits) bitwise or a.or(b)

xor (bits) bitwise xor a.xor(b)


inv() bitwise inverse a.inv()

Example of Bitwise Operation

1. fun main(args: Array<String>){


2. var a=10
3. var b=2
4. println("a.shl(b): "+a.shl(b))
5. println("a.shr(b): "+a.shr(b))
6. println("a.ushr(b:) "+a.ushr(b))
7. println("a.and(b): "+a.and(b))
8. println("a.or(b): "+a.or(b))
9. println("a.xor(b): "+a.xor(b))
10. println("a.inv(): "+a.inv())
11.
12. }

Kotlin Standard Input/Output


Kotlin standard input output operations are performed to flow byte stream from input
device (keyboard) to main memory and from main memory to output device (screen).

Kotlin Output
Kotlin output operation is performed using the standard methods print() and println().
Let's see an example:

1. fun main(args: Array<String>) {


2. println("Hello World!")
3. print("Welcome to JavaTpoint")
4. }

Output

Hello World!
Welcome to JavaTpoint

The methods print() and println() are internally call System.out.print() and
System.out.println() respectively.

Play Video

Difference between print() and println() methods:


o print(): print() method is used to print values provided inside the method "()".
o println(): println() method is used to print values provided inside the method "()" and moves
cursor to the beginning of next line.

Example

1. fun main(args: Array<String>){


2. println(10)
3. println("Welcome to JavaTpoint")
4. print(20)
5. print("Hello")
6. }

Output:

10
Welcome to JavaTpoint
20Hello

Kotlin Input
Kotlin has standard library function readLine() which is used for reads line of string input
from standard input stream. It returns the line read or null. Let's see an example:

1. fun main(args: Array<String>) {


2. println("Enter your name")
3. val name = readLine()
4. println("Enter your age")
5. var age: Int =Integer.valueOf(readLine())
6. println("Your name is $name and your age is $age")
7. }

Output:
Enter your name
Ashutosh
Enter your age
25
Your name is Ashutosh and your age is 25

While using the readLine() function, input lines other than String are explicitly converted
into their corresponding types.

To input other data type rather than String, we need to use Scanner object of
java.util.Scanner class from Java standard library.

Example Getting Integer Input

1. import java.util.Scanner
2. fun main(args: Array<String>) {
3. val read = Scanner(System.`in`)
4. println("Enter your age")
5. var age = read.nextInt()
6. println("Your input age is "+age)
7. }

Output:

Enter your age


25
Your input age is 25

Here nextInt() is a method which takes integer input and stores in integer variable. The
other data types Boolean, Float, Long and Double uses nextBoolean(), nextFloat(),
nextLong() and nextDouble() to get input from user.

Kotlin Comment
Comments are the statements that are used for documentation purpose. Comments are
ignored by compiler so that don't execute. We can also used it for providing information
about the line of code. There are two types of comments in Kotlin.

1. Single line comment.


2. Multi line comment.

Single line comment


Single line comment is used for commenting single line of statement. It is done by using '//'
(double slash). For example:

Multi line comment


Multi line comment is used for commenting multiple line of statement. It is done by using /*
*/ (start with slash strict and end with star slash). For example:

Kotlin if Expression
In Kotlin, if is an expression is which returns a value. It is used for control the flow of
program structure. There is various type of if expression in Kotlin.

o if-else expression
o if-else if-else ladder expression
o nested if expression

Kotlin if-else Expression


As if is an expression it is not used as standalone, it is used with if-else expression and the
result of an if-else expression is assign into a variable.

Syntax of if-else expression

1. val returnValue = if (condation) {


2. //code statement
3. } else {
4. // code statement
5. }
6. println(returnValue)

Kotlin if-else Expression Example

Let's see an example of if-else expression.

1. fun main(args: Array<String>) {


2. val num1 = 10
3. val num2 =20
4. val result = if (num1 > num2) {
5. "$num1 is greater than $num2"
6. } else {
7. "$num1 is smaller than $num2"
8. }
9. println(result)
10. }

We can remove the curly braces of if-else body by writing if expression in only one
statement.

For example:

1. fun main(args: Array<String>) {


2. val num1 = 10
3. val num2 =20
4. val result = if (num1 > num2) "$num1 is greater than $num2" else "$num1 is smaller t
han $num2"
5. println(result)
6. }

Kotlin if-else if-else Ladder Expression


Let's see an example of if-else if-else ladder expression.

1. fun main(args: Array<String>) {


2. val num = 10
3. val result = if (num > 0){
4. "$num is positive"
5. }else if(num < 0){
6. "$num is negative"
7. }else{
8. "$num is zero"
9. }
10. println(result)
11. }

Kotlin Nested if Expression


Let's see an example of nested if expression.
1. fun main(args: Array<String>) {
2. val num1 = 25
3. val num2 = 20
4. val num3 = 30
5. val result = if (num1 > num2){
6.
7. val max = if(num1 > num3){
8. num1
9. }else{
10. num3
11. }
12. "body of if "+max
13. }else if(num2 > num3){
14. "body of else if"+num2
15. }else{
16. "body of else "+num3
17. }
18. println("$result")
19. }

Kotlin when Expression


Kotlin, when expression is a conditional expression which returns the value. Kotlin, when
expression is replacement of switch statement. Kotlin, when expression works as a switch
statement of other language (Java, C++, C).

Using when as an Expression


Let's see a simple example of when expression.

1. fun main(args: Array<String>){


2. var number = 4
3. var numberProvided = when(number) {
4. 1 -> "One"
5. 2 -> "Two"
6. 3 -> "Three"
7. 4 -> "Four"
8. 5 -> "Five"
9. else -> "invalid number"
10. }
11. println("You provide $numberProvided")
12. }

Output:

You provide Four

Using when Without Expression


It is not mandatory to use when as an expression, it can be used as normally as it used in
other language.

For Example

1. fun main(args: Array<String>){


2.
3. var number = 4
4. when(number) {
5. 1 -> println("One")
6. 2 -> println("Two")
7. 3 -> println("Three")
8. 4 -> println("Four")
9. 5 -> println("Five")
10. else -> println("invalid number")
11. }
12.
13. }

Output:

Four
Multiple Statement of when Using Braces
We can use multiple statement enclosed within block of condition.

For Example

1. fun main(args: Array<String>){


2. var number = 1
3. when(number) {
4. 1 -> {
5. println("Monday")
6. println("First day of the week")
7. }
8. 7 -> println("Sunday")
9. else -> println("Other days")
10. }
11. }

Output:

Monday
First day of the week

Multiple branches of when


We can use multiple branches of condition separated with a comma. It is used, when we
need to run a same logic for multiple choices.

1. fun main(args: Array<String>){


2. var number = 8
3. when(number) {
4. 3, 4, 5, 6 ->
5. println("It is summer season")
6. 7, 8, 9 ->
7. println("It is rainy season")
8. 10, 11 ->
9. println("It is autumn season")
10. 12, 1, 2 ->
11. println("It is winter season")
12. else -> println("invalid input")
13. }
14. }

Output:

It is rainy season

Using when in the range


The when expression also check the ranges of input provided in when condition. A range is
created using .. (double dot) operator. The in operator is used to check if a value belongs to
a range.

For Example:

1. fun main(args: Array<String>){


2. var number = 7
3. when(number) {
4. in 1..5 -> println("Input is provided in the range 1 to 5")
5. in 6..10 -> println("Input is provided in the range 6 to 10")
6. else -> println("none of the above")
7. }
8. }

Output:

Input is provided in the range 6 to 10

Kotlin for Loop


Kotlin for loop is used to iterate a part of program several times. It iterates through arrays,
ranges, collections, or anything that provides for iterate. Kotlin for loop is equivalent to
the foreach loop in languages like C#.

Syntax of for loop in Kotlin:

1. for (item in collection){


2. //body of loop
3. }
Iterate through array
Let's see a simple example of iterating the elements of array.

1. fun main(args : Array<String>) {


2. val marks = arrayOf(80,85,60,90,70)
3. for(item in marks){
4. println(item)
5. }
6. }

Output:

80
85
60
90
70

If the body of for loop contains only one single line of statement, it is not necessary to
enclose within curly braces {}.

1. fun main(args : Array<String>) {


2. val marks = arrayOf(80,85,60,90,70)
3. for(item in marks)
4. println(item)
5. }

The elements of an array are iterated on the basis of indices (index) of array. For example:

1. fun main(args : Array<String>) {


2.
3. val marks = arrayOf(80,85,60,90,70)
4. for(item in marks.indices)
5. println("marks[$item]: "+ marks[item])
6. }

Output:

marks[0]: 80
marks[1]: 85
marks[2]: 60
marks[3]: 90
marks[4]: 70
Iterate through range
Let's see an example of iterating the elements of range.

1. fun main(args : Array<String>) {


2.
3. print("for (i in 1..5) print(i) = ")
4. for (i in 1..5) print(i)
5. println()
6. print("for (i in 5..1) print(i) = ")
7. for (i in 5..1) print(i) // prints nothing
8. println()
9. print("for (i in 5 downTo 1) print(i) = ")
10. for (i in 5 downTo 1) print(i)
11. println()
12. print("for (i in 5 downTo 2) print(i) = ")
13. for (i in 5 downTo 2) print(i)
14. println()
15. print("for (i in 1..5 step 2) print(i) = ")
16. for (i in 1..5 step 2) print(i)
17. println()
18. print("for (i in 5 downTo 1 step 2) print(i) = ")
19. for (i in 5 downTo 1 step 2) print(i)
20. }

Output:

for (i in 1..5) print(i) = 12345


for (i in 5..1) print(i) =
for (i in 5 downTo 1) print(i) = 54321
for (i in 5 downTo 2) print(i) = 5432
for (i in 1..5 step 2) print(i) = 135
for (i in 5 downTo 1 step 2) print(i) = 531

Kotlin while Loop


The while loop is used to iterate a part of program several time. Loop executed the block of
code until the condition has true. Kotlin while loop is similar to Java while loop.
Syntax

1. while(condition){
2. //body of loop
3. }

Example of while Loop


Let's see a simple example of while loop printing value from 1 to 5.

1. fun main(args: Array<String>){


2. var i = 1
3. while (i<=5){
4. println(i)
5. i++
6. }
7. }

Output:

1
2
3
4
5

Kotlin Infinite while Loop


The while loop executes a block of code to infinite times, if while condition remain true.

For example:

1. fun main(args: Array<String>){


2. while (true){
3. println("infinite loop")
4. }
5. }

Output:

infinite loop
infinite loop
infinite loop
.
.
.
.
infinite loop
infinite loop

infinite loop
infinite loop
infinite loop
infinite loop

Kotlin do-while Loop


The do-while loop is similar to while loop except one key difference. A do-while loop first
execute the body of do block after that it check the condition of while.

As a do block of do-while loop executed first before checking the condition, do-while loop
execute at least once even the condition within while is false. The while statement of do-
while loop end with ";" (semicolon).

Syntax

1. do{
2. //body of do block
3. }
4. while(condition);

Example of do -while loop

Let's see a simple example of do-while loop printing value 1 to 5.

1. fun main(args: Array<String>){


2. var i = 1
3. do {
4. println(i)
5. i++
6. }
7. while (i<=5);
8. }

Output:

1
2
3
4
5

Example of do -while loop even condition of while if false

In this example do-while loop execute at once time even the condition of while is false.

1. fun main(args: Array<String>){


2. var i = 6
3. do {
4. println(i)
5. i++
6. }
7. while (i<=5);
8. }

Output:

Kotlin Return and Jump


There are three jump expressions in Kotlin. These jump expressions are used for control the
flow of program execution. These jump structures are:

o break
o continue
o return

Break Expression
A break expression is used for terminate the nearest enclosing loop. It is almost used with
if-else condition.

For example:

1. for(..){
2. //body of for
3. if(checkCondition){
4. break;
5. }
6. }

In the above example, for loop terminates its loop when if condition execute break
expression.

372.9K

WWDC 2022 Is ANNOUNCED! Here's What To Expect & How To Watch!

Kotlin break example:

1. fun main(args: Array<String>) {


2. for (i in 1..5) {
3. if (i == 3) {
4. break
5. }
6. println(i)
7. }
8. }

Output:

1
2

In the above example, when the value of i became equal to 3 and satisfy
the if condition(i==3) than the break expression execute and terminate for loop.

Kotlin Labeled break Expression


Labeled is the form of identifier followed by the @ sign, for example abc@, test@. To make
an expression as label, we just put a label in front of expression.

Kotlin labeled break expression is used to terminate the specific loop. This is done by using
break expression with @ sign followed by label name (break@loop).

Kotlin labeled break example

1. fun main(args: Array<String>) {


2. loop@ for (i in 1..3) {
3. for (j in 1..3) {
4. println("i = $i and j = $j")
5. if (i == 2)
6. break@loop
7. }
8. }
9. }

Output:

i = 1 and j = 1
i = 1 and j = 2
i = 1 and j = 3
i = 2 and j = 1

In the above example, when the value of i became 2 and satisfy the if condition which
execute break expression followed by labeled name. The break expression followed by
labeled name terminates the body of label identifier.

You might also like