0%
Loading ...

Kotlin Tutorials

This category contains all the tutorials related tutorials.

Class and objects in Kotlin

In this tutorial, we will learn about class and objects in Kotlin. As we know Kotlin is a JVM based programming language and same as Java, Kotlin is an Object-Oriented Programming language. In simple words, Class is a blueprint for an object. For example, you have object student we can create a class for the student object which can have variables like stu_name, stu_class and some methods etc. We can create any number of objects of a class. The way to create a class in Kotlin is same as Java. Please check out the following Syntax to create a class in Kotlin. class CLASS_NAME { // class Body } Creating a Class: Same as Java there is a class keyword in Kotlin. Which we used to create a class in Kotlin. This class keyword followed by Class_Name. we can write any number of variables and methods in class according to requirements.  We can also control the visibility of the class members variables and methods using access specifiers. To understand this wisely please check out the following example program in which we will create a Student class. Example Program: class Student { // property (data member) private var name: String = “Ram” // member function fun showInfo(){ print(“Name: “+name) } } Creating an Object: We can write any number of objects of the class. It is simple to create an object of the class in Kotlin. Please check out the following example program. class Student { // property (data member) private var name: String = “Ram” // member function fun showInfo(){ print(“Name: “+name) } } fun main(args: Array<String>) { val obj = Student() // creating obj object of Student class obj.showInfo() } Output: Name: Ram   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

Class and objects in Kotlin Read More »

Try expression in Kotlin

The Try can be also used as Try expression in Kotlin. The Try expression returns the last expression of try block or last expression of catch. The finally block working doesn’t get affected in Try expression. To understand Try expression is Kotlin please check out the following example program. Example Program without Exception: fun main(args: Array<String>){ val str = div(10,2) println(“Ans “+str) } fun div(num1: Int, num2: Int): Int{ return try { num1/num2 } catch (e: ArithmeticException) { 0 } } Output: Ans 5 Example Program with Exception: fun main(args: Array<String>){ val str = div(10,0) println(“Ans “+str) } fun div(num1: Int, num2: Int): Int{ return try { num1/num2 } catch (e: ArithmeticException) { 0 } } Output: Ans 0   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

Try expression in Kotlin Read More »

Try Catch block in Kotlin

In the last tutorial, we have learned about Exception and this tutorial we will learn how we can prevent our code from throwing exceptions. One of the powerful a method to handle exceptions in Kotlin is Try-Catch block in Kotlin. The try block is followed by the catch and finally blocks. In this catch and finally blocks, we write code to handle the exception. Please check out the basic syntax of the Try-Catch block. try{ //Here is code that may throw an exception }catch(ref: Exception_Class){ } Before going further, here we write a code(with exception) without Try Catch block: Example Program(without Try Catch Block) fun main(args : Array<String>){ println(“Ans of 10/2 =”+(10/2)) println(“Ans of 12/3 =”+(12/3)) println(“Ans of 5/0 =”+(5/0)) // this will throws ArithmeticException println(“Ans of 24/6 =”+(24/6)) println(“Ans of 8/2 =”+(8/2)) } Output: Ans of 10/2 =5 Ans of 12/3 =4 Exception in thread “main” java.lang.ArithmeticException: / by zero at Example.main(Example.java:4)} As you can see in the above example program we got an ArithmeticException(Because we can’t divide a number by zero in Kotlin) on the fourth line. Now in the next example, we will write the same program but with the Try-Catch block to handle the Arithmetic Exception we got in our last example. fun main(args : Array<String>){ println(“Ans of 10/2 =”+(10/2)) println(“Ans of 12/3 =”+(12/3)) try{ println(“Ans of 5/0 =”+(5/0)) // this will throws ArithmeticException }catch(e: ArithmeticException){ println(e) } println(“Ans of 24/6 =”+(24/6)) println(“Ans of 8/2 =”+(8/2)) } Output: Ans of 10/2 =5 Ans of 12/3 =4 java.lang.ArithmeticException: / by zero Ans of 24/6 =4 Ans of 8/2 =4 Here you can see how we handled ArithmeticException in our last example using try catch block. In the try block, we placed all the code which might throw an exception and we catch this exception using catch block. Instead of adding particular exception class such as ArithmeticException or ArrayIndexOutOfBoundsException you can directly add parent Exception class. Example Program: fun main(args : Array<String>){ println(“Ans of 10/2 =”+(10/2)) println(“Ans of 12/3 =”+(12/3)) try{ println(“Ans of 5/0 =”+(5/0)) // this will throws ArithmeticException }catch(e: Exception){ println(e) } println(“Ans of 24/6 =”+(24/6)) println(“Ans of 8/2 =”+(8/2)) } Output: Ans of 10/2 =5 Ans of 12/3 =4 java.lang.ArithmeticException: / by zero Ans of 24/6 =4 Ans of 8/2 =4 Multiple catch blocks: In many situations, your code might throw multiple types of exception so to solve different kind of exception we can add multiple catch block with a try block. Check out the following example. fun main(args : Array<String>){ try{ val num = arrayOf(5,6,9,8) num[4]=10/0 println(“Done”) } catch(e: ArithmeticException){ println(“Can not divide by Zero”) } catch(e: ArrayIndexOutOfBoundsException){ println(“Out of Array Index”) } println(“Outside try-catch block”) println(“Outside try-catch block”) } Output: Can not divide by Zero Outside try-catch block Outside try-catch block As in the above example, you can see we have added multiple catch blocks(ArithmeticException and ArrayIndexOutOfBoundsException) and in the above example, we are got handled ArithmeticException. Here is the same example again with little change to show you the concept of multiple catch blocks. fun main(args : Array<String>){ try{ val num = arrayOf(5,6,9,8) num[6]=10/2 println(“Done”) } catch(e: ArithmeticException){ println(“Can not divide by Zero”) } catch(e: ArrayIndexOutOfBoundsException){ println(“Out of Array Index”) } println(“Outside try-catch block”) println(“Outside try-catch block”) } Output: Out of Array Index Outside try-catch block Outside try-catch block 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

Try Catch block in Kotlin Read More »

Exception Handling in Kotlin

In this tutorial, we will learn about Exception Handling in Kotlin. According to the dictionary, the word exception means abnormal and Here Exception handling means to solve abnormal situations which occur while the execution of code. During the execution of the program due to several reasons such as wrong input, or some programming mistakes, the program stops working and throw an error on screen which is known exception. Kotlin has a concept called Exception Handling to handle these exceptions. Example Program: fun main(args : Array<String>){ println(“Ans of 10/2 =”+(10/2)) println(“Ans of 12/3 =”+(12/3)) println(“Ans of 5/0 =”+(5/0)) // this will throws ArithmeticException println(“Ans of 24/6 =”+(24/6)) println(“Ans of 8/2 =”+(8/2)) } Output: Ans of 10/2 =5 Ans of 12/3 =4 Exception in thread “main” java.lang.ArithmeticException: / by zero As in the above example, you can see our code was working perfectly till the 4th line. But when it reached to 5th line and we tried to divide 5 by 0. We got an exception(In Kotlin / by Zero is an Exception) and our program stropped to working immediately as two can see there were two more lines(line number 6th and 7th) which were not executed because of Exception. Types of Exception: Kotlin has two kinds of exception which can occur in Kotlin programs. Types of Exception are as follow: Checked Exception Unchecked Exception Checked Exception: The checked exceptions are those exceptions which can be caught on compilation time by the compiler. These kinds of exceptions can not be ignored by the compiler. The programmer has to solve these exceptions first to run the program(without solving these checked exceptions program would not compile). List of Checked Exceptions in Kotlin: ClassNotFoundException NoSuchFieldException NoSuchMethodException InterruptedException IOException InvalidClassException SQLException any many more… Unchecked Exception: Unchecked Exceptions are those exceptions which can not be caught at the time of compilation of code. These exceptions only occur while the execution of code and stops the code from working. List of Unhecked Exceptions in Kotlin: ArithmeticException ArrayIndexOutOfBoundsException EnumConstantNotPresentException NegativeArraySizeException NumberFormatException NullPointerException IllegalStateException UnsupportedOperationException and many more.. 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

Exception Handling in Kotlin Read More »

String in Kotlin

In this tutorial, we will learn about String in Kotlin. A string is an array of characters(char type values) and String class is used to represent strings in Kotlin. It is important to note just like Java, String is an immutable class in Kotlin it means we can not change of object once after creation. Creating a String in Kotlin: In Kotlin we can use double quotes (“”) to create escaped string or triple quote(“”” “””) to create raw string literals. Check out the following example program to understand different ways to create a string in Kotlin. Example Program: fun main(args : Array<String>){ var str1 = “Owlbuddy” var str2 = “””Owlbuddy Programming Tutorials””” var str3 : String = “Owlbuddy Programming Tutorials” var charArray= charArrayOf(‘O’, ‘w’, ‘l’, ‘b’, ‘u’, ‘d’, ‘d’, ‘y’) var str4 = String(charArray) println(str1) println(str2) println(str3) println(str4) } Output: Owlbuddy Owlbuddy Programming Tutorials Owlbuddy Programming Tutorials Owlbuddy Ways to create String in Kotlin: using double quotes (“”) and using triple quote(“”” “””) Using double quotes (“”): Most of the time we use double quotes to declare String literals in Kotlin. When we create double quotes to create Strings this kind of stings are known as escaped strings because we can use escape characters like ‘\n’, ‘\t’, ‘\b’, etc’ in these(double-quoted) strings. Please check out the example Program to understand it. Example Program: fun main(args: Array<String>) { var name = “Rahul” var age = 20 println(“Hello $name \nYour age is $age”) } Output: Hello Rahul Your age is 20 Available Escape characters in Kotlin: \”: to add a double quote in the string \r: to carriage return \n: to add a new line \’: to add a single quote in the string \\: to add a backslash in the string \t: to add space in string \b: to add backspace Using the triple quote(“”” “””): Another way to declare strings in Kotlin is by using triple quotes. Triple quotes are used to create raw strings. These are mainly used to create multi-line strings and raw strings can not contain escaped characters. Please check out the following example program to understand it. Example Program: fun main(args: Array<String>) { var text=”””Hello Friends |Welcome to Owlbuddy, You can Learn Here |Python |Java |Kotlin etc”””.trimMargin() println(text) } In above example we have used trimMargin() function. This function is used to fix the margins in strings and it use | as margin prefix Output: Hello Friends Welcome to Owlbuddy, You can Learn Here Python Java Kotlin etc Empty String in Kotlin: It is really easy to create an empty string in Kotlin. We just have to create an object of string class with default constructor to create an empty string. Please check out the following example program to understand it. fun main(args : Array<String>){ var str1 = String() } String Functions: Functions Description compareTo(other: String): Int This function is used to compare the current string object with the specified string object. It returns zero if the current string object equals to a specified string object. get(index: Int): Char This function returns the character at the specified index in the string. plus(other: Any?): String This function returns string after concatenating a string with the specified string. subSequence(startIndex: Int,endIndex: Int): CharSequence This function returns the new string from the current string, starting from startIndex to endIndex. CharSequence.contains(other: CharSequence, ignoreCase: Boolean = false):Boolean This function returns true or false based on if the string contains the other specified character sequence. CharSequence.count(): Int This function returns the length of the string. String.drop(n: Int): String This function returns a string after removing the first n character from the string. String.dropLast(n: Int): String This function returns a string after removing the last n character from the string. String.dropWhile (predicate: (Char) -> Boolean ): String This function returns a character sequence which contains all the characters, except first characters which satisfy the given predicate. CharSequence.elementAt(index: Int): Char This function returns the character at the given index or IndexOutOfBoundsException in case the index number is bigger than the size of the char sequence. CharSequence.indexOf(char: Char, startIndex: Int = 0, ignoreCase: Boolean = false ): Int This function returns the index of the given character’s first occurrence. CharSequence.indexOfFirst( predicate: (Char) -> Boolean ): Int This function returns the index of the given character’s first occurrence. CharSequence.indexOfLast( predicate: (Char) -> Boolean ): Int This function returns the index of the given character’s last occurrence. CharSequence.getOrElse(index: Int, defaultValue: (Int) ->Char): Char This function returns the character at the given index in the char sequence or the default value if the index is bigger than the size of the char sequence. CharSequence.getOrNull(index: Int): Char? This function returns the character at the given index in the char sequence or a null value if the index is bigger than the size of the char sequence. 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

String in Kotlin Read More »

Ranges in Kotlin

In this tutorial, we will learn about Ranges in Kotlin. This is a very amazing feature provided by Kotlin with the help of ranges we can create a collection of values by just defining starting and ending value. For example, you want to create a series of 1 to 10 this can be easily done with the help of ranges. There are a total of three ways to create a range in kotlin: Using (..) operator Using rangeTo() function Using downTo() function Create Ranges in Kotlin Using (..) operator: It is really easy to create range using (..) operator in Kotlin. You just have to mention the starting and ending point(value) around the (..) operator. Check out the following example program to understand the use of (..) operator to create ranges in kotlin. Example Program: fun main(args : Array<String>){ println(“1 to 5:”) // creating range in kotlin using (..) operator for(num in 1..5){ println(num) } } Output: 1 to 5: 1 2 3 4 5 Create Range in Kotlin rangeTo() function: Here we will check out another way to create a range in Kotlin. The rangeTo() function is also used for creating ranges in Kotlin. This rangeTo() function can be used to create both character and integer ranges in kotlin. Please check out the following example program to understand rangeTo() function. Example Program: fun main(args : Array<String>){ println(“A to Z:”) // creating range in kotlin using rangeTo() function for(alpha in ‘A’.rangeTo(‘Z’)){ println(alpha) } } Output: A to Z: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Create Range in Kotlin Using downTo() function: The downTo() function in kotlin used to create ranges in Kotlin in reverse order. For example, you want to create a range from 10 to 1. Please check out the following example program to understand it. Example Program: fun main(args : Array<String>){ println(“Descending order range:”) // creating range in kotlin using downTo() function for(num in 10.downTo(1)){ println(num) } } Output: Descending order range: 10 9 8 7 6 5 4 3 2 1 Kotlin Range Step() function: Till now we have learned about three different methods to create ranges in Kotlin and if you learned carefully you can clearly notice that all the functions created ranges with a step size of one. For example in the case of 1 to 10 range was like this 1 2 3 4 5 6 7 8 9 10. But there are many situations when we need to create a range with different step size for example 5 10 15 20 25 30. In this kind of situation, we can use step() function with the range to mention the size of the interval between to values of the range. To understand it please check out the following example program. Example Program: fun main(args : Array<String>){ val myRange = 5..50 println(“5 to 50 with step size 5”) for(num in myRange.step(5)){ println(num) } } Output: 5 to 50 with step size 5 5 10 15 20 25 30 35 40 45 50 Kotlin range reversed() function: The reversed() function used to create reverse order of the range. Check out the following example program to understand it. fun main(args : Array<String>){ val myRange = 1..5 println(“5 to 1”) for(num in myRange.reversed()){ println(num) } } Output: 5 to 1 5 4 3 2 1   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

Ranges in Kotlin Read More »

Array in Kotlin

In this tutorial, we will learn about Array in Kotlin. The array is also known as a collection of homogeneous data elements. In arrays, we can store multiple values in contiguous memory locations. Furthermore, we store and fetch data with the help of index numbers. It is important to note, In kotlin array is not a data type. It is just treated as a collection of the same kind of data elements and There is a dedicated Array class in kotlin which is used to represent these data collections. Creating an Array in Kotlin: There are two ways to create an array in Kotlin which are: using arrayOf function using Array() constructor Example Program(Using arrayOf() function): fun main(args: Array<String>) { // creating array val students = arrayOf(“ABC”,”XYZ”,”MNO”,”JKL”) for (name in students) { println(name) } } Output: ABC XYZ MNO JKL Example Program(Using Array() Constructor): The Array constructor takes two parameters which we have to pass while creating an array which is the size of the array and a function that can return the initial value of each array element given its index. fun main(args: Array<String>) { // creating array using Array Constructor val asc = Array(5) { i -> (i + 1)} asc.forEach { println(it) } } Output: 1 2 3 4 5 Modifying and Accessing Array Elements: In Kotlin we have two functions get() and set() which helps us to modify or to access elements of an array. The set() function: The set function is used to set a particular element in the array. In the set() function we pass two parameters first one is index number which we want to change and the second one is the value which we want to set at that particular index. Check out the following example program. Example Program: fun main(args: Array<String>) { // creating array val students = arrayOf(“ABC”,”XYZ”,”MNO”,”JKL”) students.set(1,”JJJ”) //setting element value at particular indexusing set function students[3]=”KKK” //another way to setting element value at particulat index for (name in students) { println(name) } } Output: ABC JJJ MNO KKK In the above example program, you can see on the time of initialization(on 3rd line in code) of students array we had value “XYZ” on 1st index but later we modified the value of this index number using the set() method(on 4th line) to “JJJ”. The get() function: The get function is used to get value from a particular index from the array. The get function only takes a single parameter which is the index number from which you want to fetch the value. Example Program: fun main(args: Array<String>) { // creating array val students = arrayOf(“ABC”,”XYZ”,”MNO”,”JKL”) println(students.get(1)) //getting value using get function println(students[3]) //another way to fetch value from array } Output: XYZ JKL   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

Array in Kotlin Read More »

Function Overloading in Kotlin

In this tutorial, we will learn about the Function overloading in Kotlin. Same as Java Methods we can overload function in Kotlin. To overload a function in Kotlin, the function must have the same name and parameter lists should be different(in data type or in numbers). Check out the following example program. Example Program: //overloaded function fun addition(num1: Int, num2: Int): Int{ return num1+num2 } //overloaded function fun addition(num1: Double, num2: Double): Double{ return num1+num2 } fun main (args: Array<String>){ var ans=addition(10,20) //calling the addtion function with int values println(“Ans = “+ans) var ans2=addition(21.5,11.2) //calling the addtion function with double values println(“Ans = “+ans2) } Output: Ans = 30 Ans = 32.7 As in above example, you can see particular function is invoking on function call according to the parameter we are passing while calling the function, 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

Function Overloading in Kotlin Read More »

Function in Kotlin

In this tutorial, we will learn about Function in Kotlin.  A function is a small piece(block) of code which can perform some special task and it only executes when we call this function. The function allows us to reuse code. In Kotlin we use the fun keyword to declare a function. fun functionName(parameterName: parameterType, parameterName: parameterType): returnType { //body of function } It is important to note, you must have to mention data type of each parameter at the time of defining a function. Please check out the following example program to understand how to define and call a function in Kotlin. Example Program: //defining function fun addition(num1: Int, num2: Int): Int{ return num1+num2 } fun main (args: Array<String>){ var ans=addition(10,20) //calling the function println(“Ans = “+ans) } Output: Ans = 30 In case you have a very small piece of code in function body then you can also mention return type of function using assignment operator(=). please check out the following example. Example program: //defining function in single line fun addition(num1: Int, num2: Int = 0) = num1+num2 //return value using = fun main (args: Array<String>){ var ans=addition(10,20) //calling the function println(“Ans = “+ans) } Output: Ans = 30 Function Default Arguments In Kotlin, while defining a function we can specify the default value of parameters. The default value will be used when the corresponding argument is omitted from the function call. Check out the following example. Example Program: //defining function with default value parameter fun addition(num1: Int, num2: Int = 0) = num1+num2 //return value using = fun main (args: Array<String>){ var ans=addition(10,20) //calling the function println(“Ans = “+ans) ans = addition(20) //Second paramter will use defualt value println(“Ans = “+ans) } Output: Ans = 30 Ans = 20 The function named arguments: In Kotlin we can specify the name of arguments while passing it to function. This makes function class so clean and readable. Check out this example program. //defining function with default value parameter fun sum(num1: Int, num2: Int = 0, num3:Int=0) = num1*num2+num3 //return value using = fun main (args: Array<String>){ var ans=sum(10,5,2) //simply calling the function println(“Ans = “+ans) ans = sum(num1=20,num3=3) //calling the function with named arguments println(“Ans = “+ans) } Output: Ans = 52 Ans = 3 It is important to note, Mixing named and positioned arguments are not allowed in Kotlin. Varargs(Variable number of arguments): In Kotlin, you can pass a variable number of arguments while defining a function. You just have to add a vararg parameter in the function definition. At the call of this type of function, you can pass any number of parameters. Check out the following example. //defining function with vararg parameter fun sum(vararg numbers: Int): Int { var sum: Int = 0 for(number in numbers) { sum += number } return sum } fun main (args: Array<String>){ var ans=sum(10,5,2,25,10,15) //sending any number of variable println(“Ans = “+ans) ans=sum(16,15,9,10,16,25,21,33) //sending any number of variable println(“Ans = “+ans) } Output: Ans = 67 Ans = 145 Spread operator: In case you have an array and you want to send an array to a function which has vararg parameter defined in it. You can do this with the help of the spread operator(*). Check out the following example. //defining function with vararg parameter fun sum(vararg numbers: Int): Int { var sum: Int = 0 for(number in numbers) { sum += number } return sum } fun main (args: Array<String>){ val arr = intArrayOf(10,5,2,25,10,15) var ans=sum(*arr) //sending array using spread operator println(“Ans = “+ans) } Output: Ans = 67   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

Function in Kotlin Read More »

Jump expressions in Kotlin

In this tutorial, we will learn about Jump expressions in Kotlin. The main use of all these three jump expressions is to move the cursor on the different statement in code. There are a total of three jump expressions available in Kotlin. break continue return Break expression: The break expression is used to terminates the nearest enclosing loop. Here is an example o break expression. Break expression in Kotlin can be used with or without a label. Example Program(without a Label): fun main(args: Array<String>) { for (num in 1..10) { if (num == 5) { break } println(num) } } Example Program(with a label): fun main(args: Array<String>) { loop@ for (i in 1..5) { for (j in 1..5) { if (i==2) break@loop println(“$i $j”) } } } Continue expression: Continue expression is mainly used to skip an iteration of the loop. Continue expression can be used with or without a label. Example Program(without a label): fun main(args: Array<String>) { for (num in 1..5) { if (num == 3) { continue } println(num) } } Example Program(with a label): fun main(args: Array<String>) { loop@ for (i in 1..3) { for (j in 1..3) { if (i==2) continue@loop println(“$i $j”) } } } Return expression: The return statement is used to return some value from a function. We normally write it as the last statement in the function. Here is an example program of return expression check it out. Example Program: //defining function fun addition(num1: Int, num2: Int): Int{ return num1+num2 } fun main (args: Array<String>){ var ans=addition(10,20) //calling the function println(“Ans = “+ans) }   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

Jump expressions in Kotlin Read More »

Scroll to Top
×