Kotlin

Kotlin Code Examples (70+)37 min read

Example 1: Kotlin Program to Add Two Dates

Kotlin Program to Add Two Dates .we’ll learn about working with dates in KotlinWe’ll be looking into Date-related operations such as creating, formatting and manipulating dates.




Example 2: Kotlin Program to Calculate the Power of a Number

Kotlin Program to Calculate the Power of a Number: In this program, base and exponent are assigned values 3 and 4 respectively. Using the while loop, we keep on multiplying the result by base until exponent becomes zero.In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 * 3 * 3 = 81.

Example 3: Kotlin Program to Display Armstrong Numbers Between Intervals Using Function

Kotlin Program to Display Armstrong Numbers Between Intervals Using Function: To find all Armstrong numbers between two integers, check Armstrong() function is created. This function checks whether a number is Armstrong or not.

In the below program, we’ve created a function named checkArmstrong() which takes a parameter num and returns a boolean value. If the number is Armstrong, it returns true. If not, it returns false.

Example 4: Kotlin Program to Find Factorial of a Number Using Recursion

Kotlin Program to Find Factorial of a Number Using Recursion: Write a program to find factorial of a given number is a common kotlin program asked in an interview with freshers.The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.

Example 5: Kotlin Program to Check Leap Year

Kotlin Program to Check Leap Year : In this program, you’ll learn to check if the given year is a leap year or not in Kotlin. This is checked using an if-else statement and a when statement.

Example 6: Kotlin Program to Display Prime Numbers Between Intervals Using Function

Kotlin Program to Display Prime Numbers Between Intervals Using Function: Below the program, we’ve created a function named check prime number() which takes a parameter num and returns a boolean value. If the number is prime, it returns true. If not, it returns false. Based on the return value, the number is printed on the screen inside the main() function.

Example 7: Kotlin Program to Reverse a Number

Kotlin Program to Reverse a Number: In this, you will see how to reverse a number in Kotlin. We will learn two different ways to do that. The first method will use one loop and the second method will use a different approach to solve it.

Example 8: Kotlin Program to Find ASCII value of a character

Kotlin Program to Find ASCII value of a character : To find the ASCII value of ch, we use a Kotlin’s built-in function called toInt(). This converts a Char value into an Int value. This converted value is then stored in a variable ASCII. Finally, we print the ASCII value using the println() function.

Example 9: Kotlin Program to Find all Roots of a Quadratic Equation

Kotlin Program to Find Roots of a Quadratic Equation: The roots of any quadratic equation is given by: x = [-b +/- sqrt(-b^2 – 4ac)]/2a.

Write down the quadratic in the form of ax^2 + bx + c = 0. If the equation is in the form y = ax^2 + bx +c, simply replace the y with 0. This is done because the roots of the equation are the values where the y-axis is equal to 0

Example 10: Kotlin Program to Display Armstrong Number Between Two Intervals

Kotlin Program to Display Armstrong Number Between Two Intervals: In this program, you’ll learn to display all Armstrong numbers between two given intervals, low and high, in Kotlin.

Example 11: Kotlin Program to Round a Number to n Decimal Places

Kotlin Program to Round a Number to n Decimal Places. In the below program, we’ve used format() method to print the given floating-point number num to 4 decimal places.

Example 12: Kotlin Program to Check if a String is Numeric

Kotlin Program to Check if a String is Numeric. To check if the string contains numbers only, in the try block, we use Double ‘s parseDouble() method to convert the string to a Double.

Example 13: Kotlin Program to Count Number of Digits in an Integer

Kotlin Program to Count Number of Digits in an Integer: In this program, while loop is iterated until the test expression num != 0 is evaluated to 0 (false). After the first iteration, num will be divided by 10 and its value will be 345. Then, the count is incremented to 1.

Example 14: Kotlin Program to Convert Array to Set HashSet and Vice-Versa

Kotlin Program to Convert Array to Set (HashSet) and Vice-Versa. The collection object has a constructor that accepts a Collection object to initial the value. Since both Set and List are extended the Collection, the conversion is quite straightforward.

Example 15: Kotlin Program to Add Two Integers Number

In this program, You will learn how to add two numbers using class and object in Kotlin.
you’ll learn to store and add two integer numbers in Kotlin. After addition, the final sum is displayed on the screen.

Example 16: Kotlin Program to Convert String to Date

Kotlin Program to Convert String to Date.we will learn how to convert a string to a date in Kotlin. We will use the java.util.LocalDate class to convert a string to a Date.LocalDate comes with one static method parse that takes one date string as input and formats it as LocalDate object.

Example 17: Kotlin Program to Sort ArrayList of Custom Objects By Property

Kotlin Program to Sort ArrayList of Custom Objects By Property. For sorting the list with the property, we use the list ‘s sorted with the () method. The sorted with() method takes a comparator to compare that compares the custom property of each object and sorts it.

Example 18: Kotlin Program to Convert Map HashMap to List

Kotlin Program to Convert Map (HashMap) to List. We can convert key-value pairs into ArrayList or HashMap keys into ArrayList or HashMap values into ArrayList.

Example 19: Kotlin Program to Print an Array

Kotlin Program to Print an Array. In this tutorial, we’ll look into Kotlin array. If you’re new to Kotlin, it’s recommended to go through the Introduction to Kotlin tutorial to ensure that you’re up to speed with this tutorial.

Example 20: Kotlin Program to Calculate Average Using Arrays

Kotlin Program to Calculate Average Using Arrays. In the below program, the numeracy stores the floating-point values whose average is to be found. Then, to calculate the average, we need to first calculate the sum of all elements in the array.

Example 21: Kotlin Program to Find the Largest Among Three Numbers

Kotlin Program to Find the Largest Among Three Numbers: In this Kotlin programming, we will learn how to find out the largest number among the three. The user will enter the number values, our program will find and print out the result. To compare three numbers and finding out the largest one, we can either implement our own algorithm or we can use Kotlin’s built-in method maxOf.

Example 22: Kotlin Program to Display Characters from A to Z using a loop

Kotlin Program to Display Characters from A to Z using a loop: In this program, you’ll learn to print English alphabets using while loop in Kotlin. You’ll also learn to print only uppercased and lowercased alphabets.

Example 23: Kotlin Program to Check Armstrong Number

Kotlin Program to Check Armstrong Number: In this program, you’ll learn to check whether a given number is Armstrong number or not. You’ll learn to do this by using a while loop in Kotlin.

Example 24: Kotlin Program to Print an Integer Entered by the User

Kotlin Program to Print an Integer Entered by the User: In this program, you’ll learn to print an integer entered by the user. The integer is stored in a variable and printed to the screen using nextInt() and println() functions respectively.

Example 25: Kotlin Program to Remove All Whitespaces from a String

Kotlin Program to Remove All Whitespaces from a String. In the below program, we use String’s replaceAll() method to remove and replace all whitespaces in the string sentence.

Example 26: Kotlin Program to Compare Strings

Kotlin Program to Compare Strings. Compares this object with the specified object for order. Returns zero if this object is equal to the specified another object, a negative number if it’s less than other, or a positive number if it’s greater than other.

Example 27: Kotlin Program to Compute Quotient and Remainder

Kotlin Program to Compute Quotient and Remainder: In the above program Kotlin Program to Compute Quotient and Remainder, two numbers 25 (dividend) and 4 (divisor) are stored in the dividend and division numbers respectively. Unlike Java, they are automatically assigned type Int in Kotlin.

Example 28: Kotlin Program to Multiply to Matrix Using Multi-dimensional Arrays

Kotlin Program to Multiply to Matrix Using Multi-dimensional Arrays: In this program, you’ll learn to multiply two matrices using multi-dimensional arrays in Kotlin.

Example 29: Kotlin Program to Convert Character to String and Vice-Versa

Kotlin Program to Convert Character to String and Vice-Versa. If you want to convert the String to a char array, try calling. toCharArray() on the String. If the string is 1 character long, just take that character.

Example 30: Kotlin Program to Find Largest Element in an Array

Kotlin Program to Find Largest Element in an Array. Note that it is the kth largest element in the sorted order, not the kth distinct element. In the below program, we store the first element of the array in the variable largest.Then, the largest is used to compare other elements in the array. If any number is greater than the largest, the largest is assigned the number.

Example 31: Kotlin Program to Convert List ArrayList to Array and Vice-Versa

Kotlin Program to Convert List (ArrayList) to Array and Vice-Versa. In the below program, we have an array list of strings list.

Example 32: Kotlin Code To Create a Pyramid and Pattern

Kotlin Code To Create a Pyramid and Pattern. In this program, you will learn to create a pyramid, half pyramid, inverted pyramid, Pascal’s triangle, and Floyd’s triangle sing control statements in Kotlin.

Example 33: Kotlin Program to Lookup Enum by String value

Kotlin Program to Lookup enum by the String value. we ‘ll deep dive into Kotlin enums.
With the evolution of programming languages, the usage and application of enums have also advanced.

Example 34: Kotlin Program to Sort a Map By Values

Kotlin Program to Sort a Map By Values. In order to sort HashMap by values, you can first create a Comparator, which can compare two entries based on values.

Example 35: Kotlin Program to Get Current Working Directory

Kotlin Program to Get Current Working Directory .the program begins by testing for command-line arguments. If a command-line argument is available, the command-line argument is used for the Path.

Example 36: Kotlin Program to Find the Sum of Natural Numbers using Recursion

Kotlin Program to Find the Sum of Natural Numbers using Recursion: Find the last digit of a number using modular division by 10. Add the last digit found above to the sum variable.

Example 37: Kotlin Program to Generate Multiplication Table

Kotlin Program to Generate Multiplication Table: In this program, you’ll learn about how to generate the multiplication table of a given number. This is done by using a for and a while loop in Kotlin.

Example 38: Kotlin Program to calculate the power using recursion

Kotlin Program to calculate the power using recursion?Recursion is a powerful technique, it allows us to define a complex problem in terms of solving a simpler version.

Example 39: Kotlin Program to Find Factorial of a Number

Kotlin Program to find Factorial of a Given Number : In this program, you’ll learn to find the factorial of a number using for and while loop in Kotlin. You’ll also learn to use ranges to solve this problem.

Example 40: Kotlin Program to Multiply two Matrices by Passing Matrix to a Function

Kotlin Program to Multiply two Matrices by Passing Matrix to a Function: In this program, you’ll learn to multiply two matrices using a function in Kotlin. For matrix multiplication to take place, the number of columns of the first matrix must be equal to the number of rows of the second matrix.

Example 41: Kotlin Program to Display Prime Numbers Between Two Intervals

Kotlin Program to Display Prime Numbers Between Two Intervals : In this program, you’ll learn to display prime numbers between two given intervals, low and high. You’ll learn to do this using a while and a for loop in Kotlin.

Example 42: Kotlin Program to Multiply two Floating-Point Numbers

Kotlin Program to Multiply two Floating-Point Numbers: In the above program Kotlin Program to Multiply two Floating-Point Numbers, we have two floating-point numbers 1.5f and 2.0f stored in variables first and second respectively.

Example 43: Kotlin Program to Calculate Difference Between Two Time Periods

Kotlin Program to Calculate Difference Between Two Time Periods. The Time class has a constructor that initializes the value of hours, minutes and seconds.

Example 44: Kotlin Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers

Kotlin Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers: In this program, you’ll learn to check whether a given number can be expressed as a sum of two prime numbers or not.

Example 45: Kotlin Program to Convert OutputStream to String

Kotlin Program to Convert OutputStream to String. This is done using the stream’s write() method. Then, we simply convert the OutputStream to a final string using String ‘s constructor which takes a byte array.

Example 46: Kotlin Program to Find Transpose of a Matrix

Kotlin Program to Find Transpose of a Matrix: The transpose of a matrix is simply a flipped version of the original matrix. We can transpose a matrix by switching its rows with its columns.

Example 47: Kotlin Program to Reverse a Sentence Using Recursion

Kotlin Program to Reverse a Sentence Using RecursionRecursive function (reverse) takes string pointer (str) as input and calls itself with the next location to passed pointer (str+1).

Example 48: Kotlin Program to Join Two Lists

Kotlin Program to Join Two Lists. You will see how to merge two or more collections into one. However, before we move ahead, we need to understand the difference between mutable and immutable types.

Example 49: Kotlin Program to Make a Simple Calculator Using switch Case

Kotlin Program to Make a Simple Calculator Using switch Case:In this program, you’ll learn to make a simple calculator using when expression in Kotlin. This calculator would be able to add, subtract, multiply and divide two numbers.

Example 50: Kotlin Program to Convert InputStream to String

Kotlin Program to Convert InputStream to String. In this program, you’ll learn to convert the input stream to a string using InputStreamReader in Kotlin.In the below program, the input stream is created from a String and stored in a variable stream.

Kotlin 51: Kotlin Program to Add Two Matrix Using Multi-dimensional Arrays

Kotlin Program to Add Two Matrix Using Multi-dimensional Arrays: In the below program, the two matrices are stored in 2d array, namely first matrix and second matrix. We’ve also defined the number of rows and columns and stored them in variables rows and columns respectively.

Example 52: Kotlin Program to Convert Binary Number to Octal and vice versa

Kotlin Program to Convert Binary Number to Octal and vice versaConversion binary to decimal and vice versa: We multiply each binary digit by its weighted position, and add each of the weighted value together.

Example 53: Kotlin Program to Append Text to an Existing File

Kotlin Program to Append Text to an Existing File. Learn how to append text to file in Kotlin using Kotlin’s extension function, File.appendText() a single line of code, with an example program.

Example 54: Kotlin Program to Convert File to Byte Array and Vice-Versa

Kotlin Program to Convert File to byte array and Vice-Versa. Before we convert a file to byte array and vice-versa, we assume we have a file named test.txt in our src folder. In the below program, we store the path to the file in the variable path.

Example 55: Kotlin Program to Find G.C.D Using Recursion

Kotlin Program to Find G.C.D Using Recursion: In this program, you’ll learn to find GCD of two numbers in Kotlin. … The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder).

Example 56: Kotlin Program to Create String from Contents of a File

Kotlin Program to Create String from Contents of a File. Kotlin has inherited Java’s fidgety (but very flexible) way of doing I/O, but with some simplifying extra features.

Example 57: Kotlin Program to Convert Milliseconds to Minutes and Seconds

Kotlin Program to Convert Milliseconds to Minutes and Seconds. Basically when you want to check the exact time taken to execute a program then you may need to calculate the time.

Example 58: Kotlin Program to Display Factors of a Number

Kotlin Program to Display Factors of a Number: In the below program, the number whose factors are to be found is stored in the variable number (60). The for loop is iterated from 1 to number.

Example 59: Kotlin Program to Find GCD of two Numbers

Kotlin Program to Find GCD of two Numbers: The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder). This is done by using a while loop with the help of the if-else statement.

Example 60: Kotlin Program to Convert a Stack Trace to a String

Kotlin Program to Convert a Stack Trace to a String. In the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using the printStackTrace() method of the exception and write it in the writer.

Example 61: Kotlin Program to Convert Octal Number to Decimal and vice versa

Kotlin Program to Convert Octal Number to Decimal and vice-versa: We multiply each binary digit by its weighted position, and add each of the weighted value together.

Example 62: Kotlin Program to Concatenate Two Arrays

Kotlin Program to Concatenate Two Arrays. In the above program, we’ve two integer arrays array1 and array2. In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length Alen + ben.

Example 63: Kotlin Program to Calculate Standard Deviation

Kotlin Program to Calculate Standard Deviation: I want to write a method that counts the standard deviation from the provided numbers.this program calculates the standard deviation of an individual series using arrays.

Example 64: Kotlin Program to Convert Byte Array to Hexadecimal

Kotlin Program to Convert Byte Array to Hexadecimal. To convert byte array to a hex value, we loop through each byte in the array and use String ‘s format().

Example 65: Kotlin Program to Get Current Date-TIme

Kotlin Program to Get Current Date/TIme.Kotlin doesn’t have its own date and time implementation. Kotlin and Java are “compatible”, they use the same virtual machine and that’s why they can share their classes.Therefore, Kotlin uses Java classes for date and time. Date – The Date class from the java. util package was the first attempt at storing date and time in Java.

Example 66: Kotlin Program to Add Two Integers

Kotlin Program to Add Two Integers: In this program, You will learn how to add two numbers in Kotlin.you’ll learn to store and add two integer numbers in Kotlin. After addition, the final sum is displayed on the screen.

Example 67: Kotlin Program to Find Factorial of a Number Using Recursion

Kotlin Program to Find Factorial of a Number Using Recursion: The factorial of a negative number doesn’t exist. And the factorial of 0 is 1.You will learn to find the factorial of a number using recursion in this example.

Example 68: Kotlin Program to Convert Binary Number to Decimal and vice-versa

Kotlin Program to Convert Binary Number to Decimal and vice-versa: We multiply each binary digit by its weighted position, and add each of the weighted value together.

Example 69: Kotlin Program to Find the Sum of Natural Numbers using Recursion

Kotlin Program to Find the Sum of Natural Numbers using Recursion: The positive numbers 1, 2, 3… are known as natural numbers. The program below takes a positive integer from the user and calculates the sum up to the given number.

You can find the sum of natural numbers using the loop as well. However, you will learn to solve this problem using recursion here.

Example 70: Kotlin Program to Swap Two Numbers

Kotlin Program to Swap Two Numbers: In this article, we will learn various methods to swap two numbers in Kotlin. We will also study various methods and block like run, also, with and destructing declarations in Kotlin.

Example 71: Kotlin Program to Check Whether a Number is Even or Odd

Kotlin Program to Check Whether a Number is Even or Odd: In this program, you’ll learn to check if a number entered by a user is even or odd. This will be done using two variants of if…else in Kotlin.

Example 72: Kotlin Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers

Kotlin Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers: In this program, you’ll learn to check whether a given number can be expressed as a sum of two prime numbers or not. This is done with the help of loops and break statements in Kotlin.

Example 73: Kotlin Program to Check Whether an Alphabet is Vowel or Consonant

Kotlin Program to Check Whether an Alphabet is Vowel or Consonant: To check whether ch is vowel or not, we check if ch is any of: (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) . Unlike Java, this is done using if..else expression as opposed to the if..else statement. If the alphabet is any of the vowels, “vowel” string is returned. Else, “consonant” string is returned.

Example 74: Kotlin Program to Display Fibonacci Series

Kotlin Program to Display Fibonacci Series: In this program, you’ll learn to display the Fibonacci series in Kotlin using for and while loops. You’ll learn to display the series up to a specific term or a number.

The Fibonacci series is a series where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.

Example 75: Kotlin Program to Make a Simple Calculator Using Switch Case

Kotlin Program to Make a Simple Calculator Using Switch Case: In this program, you’ll learn to make a simple calculator using when expression in Kotlin. This calculator would be able to add, subtract, multiply and divide two numbers.

Example 76: Kotlin Program to Check Whether a Number is Prime or Not

Kotlin Program to Check Whether a Number is Prime or Not: In this program, You will learn how to check number is prime or not in Kotlin.

Example 77: Kotlin Program to Calculate the Sum of Natural Numbers

Kotlin Program to Calculate the Sum of Natural Numbers: In this program, you’ll learn to calculate the sum of natural numbers using for loop and while loop in Kotlin. You’ll also see how ranges can be helpful for solving the problem.

Leave a Comment