Kotlin

Kotlin for Beginners – Part 1: Environment Setup, Variables, Data Types, Operators, Input/Output, Comments

Pinterest LinkedIn Tumblr

Kotlin is a beautiful language with concise code and fast compilation.

Let’s start this journey by the famous saying,

 

A journey of a thousand miles must begin with a single step

Step 1: Install JDK and setup path in the local system environment variable.

You can install the latest JDK by visiting the downloads section at this link: Download

Alternatively, you can download Amazon Corretto : Download

Optional Step: You can setup Kotlin for command line also

You can download Kotlin compiler from GitHub by visiting following link: Download

 

You can choose anyone out of this

Now, extract the zip file to C:\Program Files. Add the kotlinc\bin directory to your command line path.

 

Then, for Windows, open Control Panel -> System -> Advanced System Settings -> Environment Variables

 

After opening Environment Variables, click on Edit Path in System Variables

 

 Next, paste the copied path of kotlinc bin directory in New

 

And you’re good to go

Step 2: Install an IDE

You need to install an IDE to run Kotlin programs. Some of the available IDEs are:

 

For IntelliJ IDEA setup, look for IntelliJ IDEA Setup for Java and Kotlin

For Android Studio setup, look for Android Studio Setup

 

Kotlin – First Program

 

fun main(args: Array<String>) {  
    println("Hello! Android Resource!")  
}  

Here, we can see that main is a function in Kotlin. Functions are a combination of statements to perform a particular task. The main () function that takes Array<String> as a parameter and returns unit. It means unit does not return any value. As in Java, C, C++ etc – main function is the entry point for a program. Here, the second line prints output to the console : println ()

Output:

 

Hello! Android Resource

 

Kotlin – Variables

variable refers to a memory location that stores some data in it. It has a name and an associated type. The type of a variable defines the range of values that the variable can hold and the operations that can be done on them.

In Kotlin, a variable is declared using keyword val and var.

 

  • val is an immutable variable: Its value cannot be changed.
  • var is a mutable variable: Its value can be changed.

 

val max = 100 
max = 99 //Error 
var name ="Kotlin" 
name = "Java" //execute perfectly 

So, how does Kotlin compiler check which one is String and which one is Int? Here comes the concept of Type Inference

Surely, If we want, we can also explicitly specify the type of variable during declaration.

 

val max:Int = 100
var name:String ="Kotlin"  

 

Kotlin – Data Types

Data type is a broad term used to define the type of data. Every language has different data types.

Kotlin language has variables as objects so that member functions can be called on any variable.

It has 5 built-in data types:

 

  • Number: It holds only integer and float type variables. e.g. byte, short, int, long, float, double
  • Character: It is represented by char keyword, represented by single quotes( ‘char’ ).
  • Boolean: It is represented by boolean, contains values either true or false.
  • Array: It is represented by Array class, created using arrayOf( ), which is a library function and Array( ) constructor. Array has get( ), set( ) functions, size property and some other useful member functions.
  • String: It is represented by String class, also, the elements in the string cannot be changed.

Code for Data Types:

 

// Integer
val rollno = 101

// Float
val point = 132.56

// Char
val grade = 'A'

// Boolean
val result = true

// Array
// Creating array using library function arrayOf()
val  rollno = arrayOf(101,102,103,104,105)  
val firstRollno = rollno[0]  
val lastRollno = rollno[rollno.size-1]

//Creating array using Array() constructor
val rollno = Array(5, { i -> i * 3 }) //rollno[0,3,6,9,12]  

//String
val blog ="Android Resource"

 

Kotlin – Operators

There are 6 types of operators available in Kotlin:

 

  • Arithmetic operators: + , -, *, /, %
  • Relational operators: <, >, >=, <=, ==, !=
  • Assignment or shorthand operators: -=, +=, *=, /=, %=
  • Unary operators: +, -, ++, –, !
  • Bitwise operators: shr, shl, ushr, and, or, xor, inv( )
  • Logical operators: &&, || , !

Arithmetic operators

 

fun main(args : Array<String>) {  
var a=4;  
var b=2;  
println(a+b);  
println(a-b);  
println(a*b);  
println(a/b);  
println(a%b);  
}  

//Output:
6
2
8
2
0

Relational Operators

 

// Relational Operators
fun main(args : Array<String>) {  
    val a = 4  
    val b = 2  
    val min = if (a < b) {  
        println("a is smaller than b.")          
    } else{  
        println("b is smaller than b.")  
    }  
    println("min = $min")  
}  

Assignment or Shorthand Operators

 

// Assignment Operators
fun main(args : Array<String>) {  
    var a =4
    var b =2   
    println("a+=b :"+ a)  
    println("a-=b :"+ a)   
    println("a*=b :"+ a)  
    println("a/=b :"+ a)  
    println("a%=b :"+ a)  
}  
//Output
a+=b :6
a-=b :2
a*=b :8
a/=b :2
a%=b :0

Unary Operators

 

// Unary Operators
fun main(args: Array<String>){  
    var a=4
    var b=2  
    println("+a :"+ +a)  
    println("-b :"+ -b)  
    println("++a :"+ ++a)  
    println("--b :"+ --b)    
}  
//Output
4
-2
5
1

Bitwise Operators

 

//Bitwise operators
fun main(args: Array<String>){  
    var a=4
    var b=2  
    
    println("a.and(b): "+a.and(b))  
    println("a.or(b): "+a.or(b))  
    println("a.xor(b): "+a.xor(b))  
}  
//Output
a.and(b): 2
a.or(b): 4
a.xor(b): 2

Logical Operators

 

//Logical Operators
fun main(args: Array<String>){  
    var a=4
    var b=2  
    var c= 3  
    var flag = false  
    var result: Boolean  
    result = (a>b) && (a>c)  
    println("(a>b) && (a>c) :"+ result)  
}  
//Output
(a>b) && (a>c) : true

 

Kotlin – Input/Output

In Kotlin, the input is taken as by using readLine( ) or Scanner object:

 

// Using readLine()
fun main(args: Array<String>) {  
    println("Enter your name")  
    val name = readLine()  
    println("Enter your rollno")  
    var rollno: Int =Integer.valueOf(readLine())  
    println("Your name is $name and your rollno is $rollno")  
}  
//Output
Enter your name
Sam
Enter your rollno
9
Your name is Sam and your age is 9

// Using Scanner class
import java.util.Scanner  
fun main(args: Array<String>) {  
    val read = Scanner(System.`in`)  
    println("Enter your rollno")  
    var rollno = read.nextInt()  
    println("Your rollno is "+rollno)  
}  
//Output
Enter your rollno
9
Your rollno is 9

 

Kotlin – Comments

Two types of comments are there in Kotlin:

 

  • Single line comment
  • Multi line comment

 

// Single line comment
fun main(args: Array<String>) {  
// statement for printing information on the console 
   println("Hello Android Resource")  
}

// Multi line comment
fun main(args: Array<String>) {  
/* statement for 
   printing information 
   on the console  */  
   println("Hello Android Resource")  
}   

For further reading, please visit Kotlin for Beginners – Part 2: Flow of Control, Functions, and Arrays

 

Passionate about Mobile App Development. Trained in Java, Android, IOS Development, Databases, MEAN Stack and SAP. Strong communication, interpersonal, logical and team-building skills with proficiency in grasping new concepts quickly and utilizing the same in a productive manner. Apart from technical skills, Motivator, YouTuber, and Yogi.