0%
Loading ...

Kotlin Tutorials

This category contains all the tutorials related tutorials.

Loops in Kotlin

In this tutorial, we will learn about Loops in Kotlin. Loops are used to run a piece of code several times. For example, you want to show 1 to 100 numbers on screen it means you have to write println statement 100 times. But with the help of loop, you can do this by just writing println statement once. Types of Loops in Kotlin: for (as foreach loop) for (as ordinary for loop) while loop For loop(as foreach loop): The for loop is quite a famous loop and in Kotlin for loop can be used as foreach loop to fetch values from a range, collection etc. Please check out the following flow chart diagram. Example Program(with an array): fun main(args : Array<String>) { val numbers = arrayOf(10,20,25,30,40) for(num in numbers){ println(num) } } .Example Program(with a List): fun main(args : Array<String>) { val names = listOf(“Raj”, “Sonu”, “Om”) for (name in names) { println(name) } } for (as ordinary for loop) In this kind of loop, we can control the step size(increment or decrement). In this kind of loop we mention three things first one is the initial value, the second one is until or downTo, the third one is a step size. Please check out following flow chart. Example Program: fun main(args : Array<String>) { for (x in 1 until 10 step 1) println(x) println(“\nDownTo Example”) for (x in 10 downTo 0 step 1) println(x) } While loop: While loop in Kotlin is similar to while loop of Java. It takes a condition in it and iterates the body of loop until it found false condition. Example Program: fun main(args : Array<String>) { var num = 0 while (num < 10) { println(num) num++ } }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Loops in Kotlin Read More »

When operator in Kotlin

In this tutorial, we will learn about when operator in Kotlin. When operator is work same as Switch statement of Java. In Kotlin when operator uses to match an argument with all the branches until it finds a satisfying condition in a branch. After finding satisfying condition it runs all statements inside the scope of that branch. Follow the given example to understand when operator. Example Program: fun main(args: Array<String>) { val num:Int = 2 when (num) { 1 -> print(“num is = 1”) 2 -> print(“num is = 2”) else -> { print(“Out of range”) } } } We when operator we can combine multiple branches using comma. check the following example. Example Program: fun main(args: Array<String>) { val num:Int = 8 when (num) { 1,2,3,4,5 -> print(“num is in first range”) 6,7,8,9,10 -> print(“num is in second range”) else -> { print(“Out of range”) } } We can also use in to check the particular value in a range or not. Example Program: fun main(args: Array<String>) { val num:Int = 12 when (num) { in 1..10 -> print(“num is in first range”) in 10..20 -> print(“num is in second range”) else -> { print(“Out of range”) } } }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

When operator in Kotlin Read More »

if expression in Kotlin

In this tutorial, we will learn about if expression in Kotlin. In Kotlin “if” is not a keyword(as it was in Java). In Kotlin “if” is an expression and it returns a value. In mean ordinary “If expression” in Kotlin can work just like a ternary operator(condition ? then: else) of Java. Apart from this, we can also use “if-else” as simple blocks the same as other languages(Java or c). Example Program: In this example, we will use “if-else” as simple blocks. fun main(args: Array<String>) { var num1=20 var num2=10 var max:Int if (num1 > num2) { max = num1 } else { max = num2 } println(“Max is “+max) } Example Program: In this example, we will use “if” as expression. fun main(args: Array<String>) { var num1=20 var num2=10 val max = if (num1 > num2) num1 else num2 print(“Max is =”+max) } Example Program: It is important “if ” expression can still return value while using as blocks the last statement of the block can be used to return value. fun main(args: Array<String>) { var num1=10 var num2=2 val max = if (num1>num2) { println(“num1 is big”) num1 } else { println(“num2 is big”) num2 } println(“Value of max =”+max) }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

if expression in Kotlin Read More »

Comments in Kotlin

In this tutorial, we will learn about Comments in Kotlin. Comments are not used to perform any function in the program but they really useful for developers. Developers can write comments with variables and functions to remember their working (purpose) in the program. One important thing to mention comments doesn’t put any impact on the execution of program because compiler simply ignores them. Types of Comments: Single Line comments Multi-Line comments Single-Line Comments: Single Line comments are used to add single line comment with a variable or any function. Double slash “//’ is used to add Single-Line comments. fun main(args: Array<String>) { // Pi variable with value 3.14 val Pi= 3.14 } Multi-Line Comments: Multi-Line comments are used to add a multi-line comment with a variable or any function. /* */ symbols are used to add Multi-Line comments. fun main(args: Array<String>) { /*Pi variable with value 3.14*/ val Pi= 3.14 }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Comments in Kotlin Read More »

Input and Output in Kotlin

In this tutorial, we will learn about Input and Output in Kotlin. We have written several Kotlin programs in previous tutorials and in many programs we have displayed some output on the screen. We have two functions in Kotlin to show output on the screen. print()  println() The only difference between is when we use print() method it prints output and leaves the cursor on the same line. But on the other side, when we use println() it prints output and leaves the cursor on the next line. fun main(args: Array<String>) { int num1=20; println(“Welcome to Owlbuddy “) println(“Welcome to Owlbuddy “) println(“Number is “+20) print(“Welcome to Owlbuddy “) print(“Welcome to Owlbuddy “) } If you want to concatenate a variable with the output you can use concatenate operator (+) to do this. Please check the above example Now we know how to show some output on the screen. Next, we will learn how to get input from the user. Taking input from user in Kotlin: Kotlin has an inbuilt readLine() to take input from the user. This readLine() function is mainly used to take string inputs. But we can also take other types of input but we have to explicitly change in their corresponding types. Example Program: fun main(args: Array<String>) { println(“Your Fav Programming language”) val lang = readLine() println(“Your age please”) var age: Int =Integer.valueOf(readLine()) println(“Your fav programming language is $lang and Your age is $age”) } In case you don’t want to change the data type of every variable explicitly. You can use standard Scanner class from the Java standard library. Example Program: import java.util.Scanner fun main(args: Array<String>) { val obj = Scanner(System.`in`) println(“Enter your age”) var age = obj.nextInt() println(“Your age is “+age) } Available Functions in Scanner class: Function Description nextBoolean() Read boolean input nextByte() Read byte input nextDouble() Read double input nextFloat() Read float value nextInt() Read int input nextLine() Read string input nextLong() Read long value nextShort() Read short input Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Input and Output in Kotlin Read More »

Operators in Kotlin

In this tutorial, we will learn about Operators in Kotlin. Operators are special symbols in Kotlin and we use operators to perform some special operators on operands. For example, the addition of two variables. In kotlin operators are categorised in various categories. Types of Operators: Arithmetic operators Relational operators Assignment operators Unary operators Bitwise operations Logical operators Arithmetic Operators: Arithmetic Operators are used to performing simple mathematical operations like addition, subtraction, multiplication, division etc. Operator Symbol Operator Name Example + Addition a+b – Subtraction a-b * Multiply a*b / Division a/b % Modulus a%b Example Program: fun main(args : Array<String>) { var num1=20; var num2=10; println(num1+num2); println(num1-num2); println(num1*num2); pr Relational operators: Relational Operators are used to checking the relation between the two operands. For example to check both operands are equal (num1==num2). Operator Symbol Operator Name Example > greater than a>b < Less than a<b >= greater than or equal to a>=b <= less than or equal to a<=b == is equal to a==b != not equal to a!=b Example Program: fun main(args : Array<String>) { val num1 = 20 val num2 = 10 if (num1 > num2) { println(“num1 is greater”) } else{ println(“num2 is greater”) } } Assignment operators: Assignment Operators are used to assigning value to a variable. We mainly use = operator as assignment operator but we have several other assignment operators in Kotlin. Operator Symbol Operator Name Example = equal operator a=b += add and assign a+=b -= subtract and assign a-=b *= multiply and assign a*=b /= divide and assign a/=b %= mod and assign a%=b Example Program: fun main(args : Array<String>) { var num1 =20 var num2=10 num1 +=num2 println(“num1+=num2 :”+ num1) num1 -=num2 println(“num1-=num2 :”+ num1) num1 *=num2 println(“num1*=num2 :”+ num1) num1 /=num2 println(“num1/=num2 :”+ num1) num1 %=num2 println(“num1%=num2 :”+ num1) } Unary operators: Unary Operators works on a single operand and there is total of five Unary operators available in Kotlin. Operator Symbol Operator Name Example + unary plus +a – unary minus -a ++ increment by 1 ++a — decrement by 1 –a ! not !a Example Program: fun main(args: Array<String>){ var num1=20 var num2=10 var light = true println(“+num1 :”+ +a) println(“-num2 :”+ -b) println(“++num1 :”+ ++a) println(“–num2 :”+ –b) println(“!light :”+ !flag) } Bitwise operations: Bitwise operators works at the bit level of operand. But Bitwise operators are not available in Kotlin. There are some predefined functions available in Kotlin which helps us to perform Bitwise operations. Function Name/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 Program: fun main(args: Array<String>){ var num1=20 var num2=2 println(“Signed shift left: “+num1.shl(num2)) println(“Signed shift right: “+num1.shr(num2)) println(“Unsigned shift right: “+num1.ushr(num2)) println(“Bitwise and: “+num1.and(num2)) println(“Bitwise or: “+num1.or(num2)) println(“Bitwise xor: “+num1.xor(num2)) println(“Bitwise inverse: “+num1.inv()) } Logical operators: Logical operators are used to check Logical relation between Operands. The result of these operators comes in Boolean form true/false. There are three Logical Operators in Kotlin. Operator Symbol Operator Name Example && Logical AND (a>b) && (a>c) || Logical OR (a>b) || (a>c) ! Logical NOT !a Example Program: fun main(args: Array<String>){ var num1=20 var num2=15 var num3=10 var light = true var result: Boolean result = (num1>num2) && (num1>num3) println(“Logical AND :”+ result) result = (num1>num2) || (num1>num3) println(“Logical OR :”+ result) result = !light println(“Logical NOT :”+ result) }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Operators in Kotlin Read More »

Type Conversion in Kotlin

In this tutorial, we will learn about Type Conversion in Kotlin. In simple words type conversion means converting variable of one data type into another data type. It is important to note in Kotlin doesn't support implicit conversion of smaller data type into larger data type. Invalid Type Conversion Example: var num1 = 10 val num2: Long = num1 //Compile error, type mismatch Kotlin also supports explicit type conversion. It means a programmer can explicitly convert smaller data type into larger data type and vice-versa. There are helper functions available in Kotlin to do this. List of helper functions: toByte() toShort() toInt() toLong() toFloat() toDouble() toChar() Explicit Type Conversion Example: fun main(args : Array<String>) { var num1 = 10 val num2: Long =num1.toLong() println(num2) }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Type Conversion in Kotlin Read More »

Data Types in Kotlin

In this tutorial, we will learn about available Data Types in Kotlin. Data Types are used to refer to the type and size of the value in a variable. The data types in Kotlin are divided into various categories and these categories are as follow: Number Character Boolean Array String Number: This category contains all those data types which can store both normal and decimal number. There is a total of six data types in this category which are as follow: Data Type Memory Size 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 Program: un main(args: Array<String>) { val b: Byte = 1 val s: Short = 10 val i: Int = 10000 val l: Long = 100000000 val f: Float = 100.00f val d: Double = 100.00 println(“Byte Value is “+b); println(“Short Value is “+s); println(“Int Value is “+i); println(“Long Value is “+l); println(“Float Value is “+f); println(“Double Value is “+d); } Characters: In Kotlin Char data type is used to define character in variable. Char value should be defined inside single quotes ('a'). Data Type Memory Size Range Char 4 bit -128 to 127 fun main(args: Array<String>) { val gender: Char // defining variable gender = ‘M’ // Assigning value println(“Gender = “+gender) } Boolean: In Boolean data type we can store only two value which are true or false. Data Types Memory Size Values Boolean 1 bit true or false Example Program: fun main(args: Array<String>) { val flag: Boolean // defining variable flag = true // Assinging value println(“Value is “+”$flag”) } Array: In very simple language Array is a collection of homogeneous data elements. Kotlin has Array class to define an array in program. We can us arrayOf() function and Array() constructor to create an Array. Creating an array using arrayOf() function: fun main() { // declaring an array using arrayOf() val numbers = arrayOf(1, 2, 3, 4, 5) for (i in 0..numbers.size-1) { println(numbers[i]) } } Creating an array using Array Constructor: The Array constructor takes two parameters: The size of the array. A function which accepts the index of a given element and returns the initial value of that element. fun main() { val numbers = Array(5, { i -> i * 1 }) for (i in 0..numbers.size-1) { println(numbers[i]) } } String: In Kotlin String is represented as collect of characters. String is immutable in Kotlin like Java. We have two kinds of strings available in Kotlin which are raw String and escaped String. Raw String: We describe raw strings using  triple quote (""" """). We can create multi-line strings using raw strings. fun main(args: Array<String>) { var rawString :String = “”” Learn Kotlin On Owlbuddy””” println(rawString) } Escaped String: We describe Escaped strings using double quote (" "). There are various escaped characters available in Kotlin which we can use with Strings like '\n', '\t', '\b' etc. fun main(args: Array<String>) { val escapedString : String = “\nThis is escaped String!\n” println(escapedString) }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Data Types in Kotlin Read More »

Variables in Kotlin

In this tutorial, we will learn about Variables in Kotlin. The main motive of variables is to store data in memory while execution of a Kotlin program. The value of variables can be changed throughout the execution of the program and we change reuse variable any number of times throughout the program n Kotlin we have two keywords to declare variables. var(Mutable variable): We can change the value of the variable which declared using the var keyword. val(Immutable variable): We cannot change the value of the variable which declared using val keyword. Example of Variable using var keyword: lang = “Java”; val age = 22 Here is a really important thing to note about Kotlin variable we don't need to explicitly define the type of variable. Kotlin compiler automatically takes data type according to the value of the variable. This is known as type inference in programming. We also have another option if a programmer wants to write datatype explicitly he/she can write. Check out the example. var lang: String = “Java”; val age: Int = 22 Example of Variable using val keyword: var lang = “Java”; //We cannot change value of this variable lang = “Python”;   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Variables in Kotlin Read More »

Hello World Program in Kotlin

In the last tutorial, we learned about how to set up the environment for Kotlin and how to start new Kotlin project in Eclipse. In this tutorial, we will learn how to write Hello World program in Kotlin. Before going further it is important to mention that we save Kotlin program files with extension .kt. If you want to save you program file with HelloWorld name you have to save it as HelloWorld.kt. Let’s check out code of our first Kotlin program. fun main (args: Array<String>){ println(“Hello World”) } To run this code you can use play button which is available in the toolbar or click on Run in the menu bar then Run As option. You will get the output of this program in the console. Hello World code Explanation: fun: In our code, you can see we started from fun. fun is a keyword in kotlin to define the function after writing fun we write function name. main(): The main function is Kotlin is same as main() in java and c. From where the execution of the program starts. In Kotlin main function take an array of string as a parameter. println(): The println() is a function which is used to print a string on the screen. We write a string in println() function in double-quotes. Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Hello World Program in Kotlin Read More »

Scroll to Top
×