What Is Kotlin
What Is Kotlin
What Is Kotlin
Kotlin Tutorial
Environment Setup
Hello World Program
First Program Concept
Environment Setup (IDE)
First Program (IDE)
Kotlin Variable
Kotlin Data Type
Kotlin Type Conversion
Kotlin Operator
Kotlin Input/Output
Kotlin Comment
What is Kotlin
History of Kotlin
Features of Kotlin
Concise: Kotlin reduces writing the extra codes. This makes Kotlin more
concise.
Null safety: Kotlin is null safety language. Kotlin aimed to eliminate the
NullPointerException (null reference) from the code.Interoperable.
Interoperable: Kotlin easily calls the Java code in a natural way as well as
Kotlin code can be used by Java.
1|Page
Smart cast: It explicitly typecasts the immutable values and inserts the
value in its safe cast automatically.
Compilation Time: It has better performance and fast compilation time.
Tool-friendly: Kotlin programs are build using the command line as well as
any of Java IDE.
Extension function: Kotlin supports extension functions and extension
properties which means it helps to extend the functionality of classes
without touching their code.
println("Hello World!")
Save the file with name hello.kt, .kt extension is used for Kotlin file.
kotlinc hello.kt -include-runtime -d hello.jar
To run the Kotlin .jar (hello.jar) file run the following command.
java -jar hello.jar
fun main(args: Array<String>) {
println("Hello World!")
2|Page
}
fun main(args: Array<String>): Unit {
//
}
The main() function is the entry point of the program, it is called first when Kotlin
program starts execution.
The second line used to print a String "Hello World!". To print standard output we
use wrapper println() over standard Java library functions (System.out.println()).
println("Hello World!")
Kotlin Variable
Variable refers to a memory location. It is used to store data. The data of variable
can be changed and reused depending on condition or on information passed to the
program.
Variable Declaration
var language ="Java"
3|Page
val salary = 30000
The difference between var and val is specified later on this page.
Here, variable language is String type and variable salary is Int type. We don't
require specifying the type of variable explicitly. Kotlin complier knows this by
initilizer expression ("Java" is a String and 30000 is an Int value). This is called
type inference in programming.
We can also explicitly specify the type of variable while declaring it.
var language: String ="Java"
val salary: Int = 30000
It is not necessary to initialize variable at the time of its declaration. Variable can
be initialized later on when the program is executed.
var language: String
... ... ...
language = "Java"
val salary: Int
... ... ...
salary = 30000
Example
var salary = 30000
salary = 40000 //execute
4|Page
Here, the value of variable salary can be changed (from 30000 to 40000) because
variable salary is declared using var keyword.
val language = "Java"
language = "Kotlin" //Error
Here, we cannot re-assign the variable language from "Java" to "Kotlin" because
the variable is declared using val keyword.
In Kotlin, everything is an object, which means we can call member function and
properties on any variable.
Number
Character
Boolean
Array
String
Number Types
Number types of data are those which hold only number type data variables. It is
further categorized into different Integer and Floating point.
5|Page
Int 32 bit -2,147,483,648 to 2,147,483,647
Characters are represented using the keyword Char. Char types are declared using
single quotes ('').
Example
val value1 = 'A'
//or
val value2: Char
value2= 'A'
Boolean data is represented using the type Boolean. It contains values either true or
false.
6|Page
Boolean 1 bit true or false
Example
val flag = true
AD
Array
Arrays in Kotlin are represented by the Array class. Arrays are created using
library function arrayOf() and Array() constructor. Array has get (), set()
function, size property as well as some other useful member functions.
The elements of array are accessed through their index values (array[index]). Array
index are start from zero.
val id = arrayOf(1,2,3,4,5)
val firstId = id[0]
val lasted = id[id.size-1]
val asc = Array(5, { i -> i * 2 }) //asc[0,2,4,6,8]
7|Page
String
String declaration:
val text ="Hello, JavaTpoint"
Types of String
String are categorize into two types. These are:
1. Escaped String: Escape String is declared within double quote (" ") and may
contain escape characters like '\n', '\t', '\b' etc.
val text1 ="Hello, JavaTpoint"
//or
val text2 ="Hello, JavaTpoint\n"
//or
val text3 ="Hello, \nJavaTpoint"
2. Raw String: Row String is declared within triple quote (""" """). It provides
facility to declare String in new lines and contain multiple lines. Row String cannot
contain any escape character.
AD
val text1 ="""
Welcome
To
JavaTpoint
"""
8|Page
Kotlin Type Conversion
Type conversion is a process in which one data type variable is converted into
another data type. In Kotlin, implicit conversion of smaller data type into larger
data type is not supported (as it supports in java). For example Int cannot be
assigned into Long or Double.
In Java
int value1 = 10;
long value2 = value1; //Valid code
In Kotlin
var value1 = 10
val value2: Long = value1 //Compile error, type mismatch
var value1 = 10
val value2: Long = value1.toLong()
The list of helper functions used for numeric conversion in Kotlin is given below:
toByte()
toShort()
toInt()
toLong()
toFloat()
toDouble()
toChar()
fun main(args : Array<String>) {
9|Page
var value1 = 100
val value2: Long =value1.toLong()
println(value2)
}
We can also converse from larger data type to smaller data type.
fun main(args : Array<String>) {
var value1: Long = 200
val value2: Int =value1.toInt()
println(value2)
}
Kotlin Operator
Operators are special characters which perform operation on operands (values or
variable).There are various kind of operators available in Kotlin.
Arithmetic operator
Relation operator
Assignment operator
Unary operator
Bitwise operation
Logical operator
Arithmetic Operator
10 | P a g e
- Subtraction a-b a.minus(b)
var a=10;
var b=5;
println(a+b);
println(a-b);
println(a*b);
println(a/b);
println(a%b);
}
Output:
15
5
50
2
0
Relation Operator
Relation operator shows the relation and compares between operands. Following
are the different relational operators:
11 | P a g e
> greater than a>b a.compateTo(b)>0
fun main(args : Array<String>) {
val a = 5
val b = 10
val max = if (a > b) {
println("a is greater than b.")
a
} else{
println("b is greater than a.")
b
}
println("max = $max")
}
12 | P a g e
Output:
b is greater than a.
max = 10
Assignment operator
fun main(args : Array<String>) {
var a =20;var b=5
a+=b
println("a+=b :"+ a)
a-=b
println("a-=b :"+ a)
a*=b
println("a*=b :"+ a)
13 | P a g e
a/=b
println("a/=b :"+ a)
a%=b
println("a%=b :"+ a)
}
Output:
a+=b :25
a-=b :20
a*=b :100
a/=b :20
a%=b :0
AD
Unary Operator
Unary operator is used with only single operand. Following are some unary
operator given below.
! not !a a.not()
fun main(args: Array<String>){
14 | P a g e
var a=10
var b=5
var flag = true
println("+a :"+ +a)
println("-b :"+ -b)
println("++a :"+ ++a)
println("--b :"+ --b)
println("!flag :"+ !flag)
}
Output:
+a :10
-b :-5
++a :11
--b :4
!flag :false
Logical Operator
Logical operators are used to check conditions between operands. List of logical
operators are given below.
&& 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)
fun main(args: Array<String>){
15 | P a g e
var a=10
var b=5
var c=15
var flag = false
var result: Boolean
result = (a>b) && (a>c)
println("(a>b) && (a>c) :"+ result)
result = (a>b) || (a>c)
println("(a>b) || (a>c) :"+ result)
result = !flag
println("!flag :"+ result)
}
Output:
(a>b) && (a>c) :false
(a>b) || (a>c) :true
!flag :true
Bitwise Operation
In Kotlin, there is not any special bitwise operator. Bitwise operation is done using
named function.
AD
fun main(args: Array<String>){
var a=10
var b=2
println("a.shl(b): "+a.shl(b))
println("a.shr(b): "+a.shr(b))
println("a.ushr(b:) "+a.ushr(b))
println("a.and(b): "+a.and(b))
println("a.or(b): "+a.or(b))
println("a.xor(b): "+a.xor(b))
println("a.inv(): "+a.inv())
}
Output:
a.shl(b): 40
a.shr(b): 2
a.ushr(b:) 2
a.and(b): 2
17 | P a g e
a.or(b): 10
a.xor(b): 8
a.inv(): -11
Kotlin Output
fun main(args: Array<String>) {
println("Hello World!")
print("Welcome to JavaTpoint")
}
Output
Hello World!
Welcome to JavaTpoint
The methods print() and println() are internally call System.out.print() and
System.out.println() respectively.
fun main(args: Array<String>){
println(10)
println("Welcome to JavaTpoint")
18 | P a g e
print(20)
print("Hello")
}
Output:
10
Welcome to JavaTpoint
20Hello
Kotlin Input
fun main(args: Array<String>) {
println("Enter your name")
val name = readLine()
println("Enter your age")
var age: Int =Integer.valueOf(readLine())
println("Your name is $name and your age is $age")
}
Output:
To input other data type rather than String, we need to use Scanner object of
java.util.Scanner class from Java standard library.
19 | P a g e
Example Getting Integer Input
import java.util.Scanner
fun main(args: Array<String>) {
val read = Scanner(System.`in`)
println("Enter your age")
var age = read.nextInt()
println("Your input age is "+age)
}
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.
fun main(args: Array<String>) {
// this statement used for print
println("Hello World!")
20 | P a g e
}
Output
Hello World!
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:
fun main(args: Array<String>) {
/* this statement
is used
for print */
println("Hello World!")
}
Output:
Hello World!
21 | P a g e