Part 2: Hello World Program in Kotlin

 

Hello World Program in Kotlin

Welcome to the second part of our Learn Kotlin: The Ultimate Tutorial Series! In this tutorial, we’ll write the classic "Hello, World!" program—the first step in learning any programming language. Let’s dive into Kotlin and create your first program.

Writing Your First Kotlin Program: Hello, World!

The "Hello, World!" program is a simple way to get started with Kotlin. Follow these steps to create and run your first Kotlin program:

  1. Open your favorite text editor (like Notepad or Notepad++) or an IDE like IntelliJ IDEA.
  2. Create a file named firstapp.kt.
  3. Add the following code:
    
// Kotlin Hello World Program
fun main(args: Array) {
    println("Hello, World!")
}
    
  

Note: If you’re using IntelliJ IDEA, you can run this program directly. Check out our previous post on setting up your Kotlin environment for detailed steps.

Breaking Down the Hello, World! Program

Let’s dissect the code to understand each part of this simple program:

Line 1: Comments

The first line is a comment, which the compiler ignores. Comments make your code easier to read and understand.

    
// Kotlin Hello World Program
    
  

Kotlin supports two types of comments:

  • Single-line comment: Starts with //.
  •       
    // single line comment
          
        
  • Multi-line comment: Enclosed between /* and */.
  •       
    /* This is
    multi line
    comment */
          
        

Line 2: The main Function

The second line defines the main function, which is the entry point of every Kotlin program:

    
fun main(args: Array) {
    // ...
}
    
  

Here’s what each part means:

  • fun: Keyword to declare a function in Kotlin.
  • main: The name of the function, which serves as the program’s entry point.
  • args: Array: A parameter that accepts an array of strings (command-line arguments).
  • Unit: The return type (implicit here), equivalent to void in Java, meaning the function doesn’t return a value.
  • { ... }: The body of the function, containing the code to execute.

Line 3: Printing Output

The third line prints "Hello, World!" to the console:

    
println("Hello, World!")
    
  

The println() function outputs text to the console, followed by a new line. Unlike some languages, Kotlin doesn’t require semicolons at the end of statements—they’re optional!

Running the Program

If you run this program in IntelliJ IDEA or compile it using the Kotlin compiler, you’ll see the following output:

    
Hello, World!
    
  

What’s Next?

Congratulations on writing your first Kotlin program! In the next part of this series, we’ll explore variables and data types in Kotlin to help you build more complex programs. Stay tuned!

Did you successfully run your Hello, World! program? Let me know in the comments, and share any questions you have!

Comments

Popular posts from this blog

Introduction to Kotlin: A Modern Programming Language