Q:

Scala program to demonstrate the NullPointerException

belongs to collection: Scala Exception Handling Programs

0

Here, we will demonstrate the NullPointerException using the try and catch blocks.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the NullPointerException is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to demonstrate the
// NullPointerException

object Sample {
  // Main method
  def main(args: Array[String]) {
    val str: String = null
    try {
      // Generate NullPointerException
      println("Length of string: " + str.length);
    } catch {
      case e: NullPointerException => println(e);
    }
  }
}

Output:

java.lang.NullPointerException

Explanation:

In the above program, we used an object-oriented approach to create the program.

And, we created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.

In the main() function, we created a string variable str initialized with null. Then we tried to find the length of the string in the try block. That's why NullPointerException gets generated that will be caught in the catch block and print an appropriate message on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Scala program to demonstrate the NumberFormatExcep...