ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Scala program to demonstrate the NullPointerException

Here, we are going to demonstrate the NullPointerException in Scala programming language.
Submitted by Nidhi, on June 08, 2021

Problem Solution:

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

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.

Scala Exception Handling Programs »

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.