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.
Single line comment.
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:
fun main(args: Array<String>) {
// this statement used for print
println("Hello World!")
}
Output
Hello World!
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:
fun main(args: Array<String>) {
/* this statement
is used
for print */
println("Hello World!")
}
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:
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.
Difference between print() and println() methods:
print(): print() method is used to print values provided inside the method “()”.
println(): println() method is used to print values provided inside the method “()” and moves cursor to the beginning of next line.
Example
fun main(args: Array<String>){
println(10)
println("Welcome to JavaTpoint")
print(20)
print("Hello")
}
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:
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:
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
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.
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
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
fun main(args : Array<String>) {
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:
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
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")
}
Output:
b is greater than a.
max = 10
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
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)
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
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
fun main(args: Array<String>){
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.
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
fun main(args: Array<String>){
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)
}
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
However in Kotlin, conversion is done by explicit in which smaller data type is converted into larger data type and vice-versa. This is done by using helper function.
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()
Kotlin Type Conversion Example
Let see an example to convert from Int to Long.
fun main(args : Array<String>) {
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)
}
Data type (basic type) refers to type and size of data associated with variables and functions. Data type is used for declaration of memory location of variable which determines the features of data.
In Kotlin, everything is an object, which means we can call member function and properties on any variable.
Kotlin built in data type are categorized as following different categories:
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.
Data Type
Bit Width (Size)
Data 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
Character (Char) Data Type
Characters are represented using the keyword Char. Char types are declared using single quotes (”).
Data Type
Bit Width (Size)
Data Range
Char
4 bit
-128 to 127
Example
val value1 = 'A'
//or
val value2: Char
value2= 'A'
Boolean Data Types
Boolean data is represented using the type Boolean. It contains values either true or false.
Data Type
Bit Width (Size)
Data Value
Boolean
1 bit
true or false
Example
val flag = true
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.
Creating Array using library function arrayOf()
The arrayOf() function creates array of wrapper types. The item value are passed inside arrayOf() function like arrayOf(1,2,3) which creates an array[1,2,3].
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]
Creating Array using Array() constructor
Creating array using Array() constructor takes two arguments in Array() constructor:
First argument as a size of array, and
Second argument as the function, which is used to initialize and return the value of array element given its index.
val asc = Array(5, { i -> i * 2 }) //asc[0,2,4,6,8]
String
String in Kotlin is represented by String class. String is immutable, which means we cannot change the elements in 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.
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
Kotlin variable is declared using keyword var and val.
var language ="Java"
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
Difference between var and val
var (Mutable variable): We can change the value of variable declared using var keyword later in the program.
val (Immutable variable): We cannot change the value of variable which is declared using val keyword.
Example
var salary = 30000
salary = 40000 //execute
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.
Since, Kotlin runs on JVM, it is necessary to install JDK and setup the JDK and JRE path in local system environment variable. Use this link https://www.javatpoint.com/how-to-set-path-in-java to setup JDK path.
Install IDE for Kotlin
There are various Java IDE available which supports Kotlin project development. We can choose these IDE according to our compatibility. The download links of these IDE’s are given below.
Let’s understand the concepts and keywords of Kotlin program ‘Hello World.kt’.
fun main(args: Array<String>) {
println("Hello World!")
}
1. The first line of program defines a function called main(). In Kotlin, function is a group of statements that performs a group of tasks. Functions start with a keyword fun followed by function name (main in this case).
The main () function takes an array of string (Array<String>) as a parameter and returns Unit. Unit is used to indicate the function and does not return any value (void as in Java). Declaring Unit is an optional, we do not declare it explicitly.
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.
2. 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()).