Hello World in Scala

The Hello World! the program is the most basic and first program when you dive into a new programming language. This simply prints the Hello World! on the output screen. In Scala, a basic program consists of the following:

  • object
  • Main Method
  • Statements or Expressions

Example:




// Scala program to print Hello World! 
object Beginner 
{
    // Main Method 
    def main(args: Array[String]) 
    {
        // prints Hello World
        println("Hello World!"
    }
}


Output:

Hello World!

Explanation:

  • object Beginner: object is the keyword which is used to create the objects. Objects are the instance of a class. Here “Beginner” is the name of the object.
  • def main(args: Array[String]): def is the keyword in Scala which is used to define the function and “main” is the name of Main Method. args: Array[String] are used for the command line arguments.
  • println(“Hello World!”): println is a method in Scala which is used to display the Output on console.

How to run a Scala Program?

  • To use an online Scala compiler: We can use various online IDE. which can be used to run Scala programs without installing.
  • Using Command-Line: Make sure we have the Java 8 JDK (also known as 1.8). run javac -version in the command line and make sure we see javac 1.8.___ If we don’t have version 1.8 or higher, Install the JDK Firstly, open a text editor Notepad or Notepad++. write the code in the text editor and save the file with (.scala) extension. open the command prompt follow step by step process on your system.
    // Scala program to print Hello World! 
    object Beginner 
    {
        // Main Method 
        def main(args: Array[String]) 
        {
            // prints Hello World
            println("Hello World!") 
        }
    }

    Step 1: Compile above file using scalac Hello.Scala after compilation it will generate a Beginner.class file and class file name is same as Object name(Here Object name is Beginner).
    Step 2: Now open the command with object name scala Beginner. It will give the result.

  • Using Scala IDE: IDE like IntelliJ IDEA, ENSIME run scala program easily. write the code in the text editor and press to run it.