Writing your first Kotlin Program

This first program in every coding language is what we call “Hello World!” Not sure why but I hate saying “Hello World!”. Can say anything. Anyways. Lets get started.

In almost every coding language, the first program we write is about getting the output using code. To get the desired output we need to maintain two critical things:

  1. Command: every language and its compiler has a set of commands to follow and execute them for user once given. High level languages use commands that are readable by humans i.e. you can understand what code is about by reading it just like you read newspaper. Though they are not completely written in human language, but very close to it. Thus making them easy to write and read.
  2. Syntax: in every human language we arrange words in a distinct way to make the sentence or phrase meaningful. Same way, computer languages have rules for arrangements that we call syntax. Just like human languages have punctuation, grammar etc, computer languages make use of brackets, periods and other symbols.

Don’t worry. No one is expecting from you to know all of this completely right in the beginning. We will learn as we progress.

To have an out of “Welcome to Kotlin” we can use either of the two commands:

  1. print
  2. println

The difference between two is that first one prints the outcome in the same line whereas the second one will print the outcome in a new line. 

NOTE: Before we write our first code, just remember for now that whatever code we write, it must go within main function. Why it is important is something to be discussed later, but for now just know that no code will work if not written inside this function’s body/block. You can insert this function simply by typing main and when Kotlin gives suggestion tooltip hit tab once to insert it completely with curly brackets. This will save you from typing all of it manually.

Lets write our first program:

Here is the code itself:

Observed few things? I didn’t press round bracket key twice but still Kotlin helped me with inserting a pair. Same goes for the Quotation marks, I pressed it once and a pair got inserted. These little things help in typing fast and saving your fingers as well.

We can ask for multiple instances of same “Welcome to Kotlin” sentence. Simply duplicate the command of print and hit SHIFT+F10

Though the command itself was in multiple lines, the outcome was one liner. We can solve it:

  1. either by using println command instead of simple print or
  2. use \n after every string to break the line so that next execution takes place in the new line.

So there you go. You wrote your first program and executed it perfectly. Now go and your homework is to get the following output from your code:

“Hey! I learnt my first Kotlin program”



Leave a Reply

Notify of