SlideShare a Scribd company logo
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 1
Exception handling and Multithreading
Exception handling: Try-Catch Blocks - Finally Block - Throw Keyword - Throws
Keyword - Custom Exception – Multithreading: Thread - Thread Life Cycle – Thread
Methods – Collections - File Handling
Exception Handling
 An exception is an unwanted or unexpected event, which occurs during the execution of a
program i.e at run time. These events change the flow control of the program in
execution. These are situations that are not too dangerous and can be handled by the
program.
Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is base class of
hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that
user programs should catch. NullPointerException is an example of such an exception. Another
branch, Error are used by the Java run-time system(JVM) to indicate errors having to do with the
run-time environment itself(JRE). StackOverflowError is an example of such an error.
 Exception handling is a mechanism which is used to handle abnormal conditions. You
can also avoid termination of your program unexpectedly.
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 2
 Scala makes "checked vs unchecked" very simple. It doesn't have checked exceptions.
All exceptions are unchecked in Scala, even SQLException and IOException.
Scala Program Example without Exception Handling
class ExceptionExample{
def divide(a:Int, b:Int) = {
a/b // Exception occurred here
println("Rest of the code is executing...")
}
}
object MainObject{
def main(args:Array[String]){
var e = new ExceptionExample()
e.divide(100,0)
}
}
Try Catch
Scala provides try and catch block to handle exception. The try block is used to enclose suspect
code. The catch block is used to handle exception occurred in try block. You can have any
number of try catch block in your program according to need.
Scala Try Catch Example
In the following program, we have enclosed our suspect code inside try block. After try block we
have used a catch handler to catch exception. If any exception occurs, catch handler will handle
it and program will not terminate abnormally.
class ExceptionExample{
def divide(a:Int, b:Int) = {
try{
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 3
a/b
}catch{
case e: ArithmeticException => println(e)
}
println("Rest of the code is executing...")
}
}
object MainObject{
def main(args:Array[String]){
var e = new ExceptionExample()
e.divide(100,0)
}
}
Output:
java.lang.ArithmeticException: / by zero
Rest of the code is executing...
Scala Try Catch Example 2
In this example, we have two cases in our catch handler. First case will handle only arithmetic
type exception. Second case has Throwable class which is a super class in exception hierarchy.
The second case is able to handle any type of exception in your program. Sometimes when you
don't know about the type of exception, you can use super class.
class ExceptionExample{
def divide(a:Int, b:Int) = {
try{
a/b
var arr = Array(1,2)
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 4
arr(10)
}catch{
case e: ArithmeticException => println(e)
case ex: Throwable =>println("found a unknown exception"+ ex)
}
println("Rest of the code is executing...")
}
}
object MainObject{
def main(args:Array[String]){
var e = new ExceptionExample()
e.divide(100,10)
}
}
Finally
The finally block is used to release resources during exception. Resources may be file, network
connection, database connection etc. the finally block executes guaranteed. The following
program illustrate the use of finally block.
Scala Finally Block Example
class ExceptionExample{
def divide(a:Int, b:Int) = {
try{
a/b
var arr = Array(1,2)
arr(10)
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 5
}catch{
case e: ArithmeticException => println(e)
case ex: Exception =>println(ex)
case th: Throwable=>println("found a unknown exception"+th)
}
finally{
println("Finaly block always executes")
}
println("Rest of the code is executing...")
}
}
object MainObject{
def main(args:Array[String]){
var e = new ExceptionExample()
e.divide(100,10)
}
}
Throw keyword
You can throw exception explicitly in you code. Scala provides throw keyword to throw
exception. The throw keyword mainly used to throw custom exception. An example is given
below of using scala throw exception keyword.
Scala Throw Example
class ExceptionExample2{
def validate(age:Int)={
if(age<18)
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 6
throw new ArithmeticException("You are not eligible")
else println("You are eligible")
}
}
object MainObject{
def main(args:Array[String]){
var e = new ExceptionExample2()
e.validate(10)
}
}
Throws Keyword
Scala provides throws keyword to declare exception. You can declare exception with method
definition. It provides information to the caller function that this method may throw this
exception. It helps to caller function to handle and enclose that code in try-catch block to avoid
abnormal termination of program. In scala, you can either use throws keyword or throws
annotation to declare exception.
Scala Throws Example
class ExceptionExample4{
@throws(classOf[NumberFormatException])
def validate()={
"abc".toInt
}
}
object MainObject{
def main(args:Array[String]){
var e = new ExceptionExample4()
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 7
try{
e.validate()
}catch{
case ex : NumberFormatException => println("Exception handeled here")
}
println("Rest of the code executing...")
}
}
Custom Exception
In scala, you can create your own exception. It is also known as custom exceptions. You must
extend Exception class while declaring custom exception class. You can create your own
exception message in custom class. Let's see an example.
Scala Custom Exception Example
class InvalidAgeException(s:String) extends Exception(s){}
class ExceptionExample{
@throws(classOf[InvalidAgeException])
def validate(age:Int){
if(age<18){
throw new InvalidAgeException("Not eligible")
}else{
println("You are eligible")
}
}
}
object MainObject{
def main(args:Array[String]){
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 8
var e = new ExceptionExample()
try{
e.validate(5)
}catch{
case e : Exception => println("Exception Occured : "+e)
}
}
}
Multithreading
 Multithreading is a process of executing multiple threads simultaneously. It allows you to
perform multiple operations independently.
 You can achieved multitasking by using Multithreading. Threads are lightweight sub-
processes which occupy less memory. Multithreading are used to develop concurrent
applications in Scala.
 Scala does not provide any separate library for creating thread. If you are familiar with
multithreading concept of Java, you will come to know that it is similar except the syntax
of Scala language itself.
 You can create thread either by extending Thread class or Runnable interface. Both
provide a run method to provide specific implementation.
Scala Thread Life Cycle
Thread life cycle is a span of time in which thread starts and terminates. It has various phases
like new, runnable, terminate, block etc. Thread class provides various methods to monitor
thread's states.
The Scala thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 9
1) New
This is the first state of thread. It is just before starting of new thread.
2) Runnable
This is the state when thread has been started but the thread scheduler has not selected it to be the
running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run due to waiting
for input or resources.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 10
Thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface
Scala Thread Example by Extending Thread Class
The following example extends Thread class and overrides run method. The start() method is
used to start thread.
class ThreadExample extends Thread{
override def run(){
println("Thread is running...");
}
}
object MainObject{
def main(args:Array[String]){
var t = new ThreadExample()
t.start()
}
}
Output:
Thread is running...
Scala Thread Example by Extending Runnable Interface
The following example implements Runnable interface and overrides run method. The start()
method is used to start thread.
class ThreadExample extends Runnable{
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 11
override def run(){
println("Thread is running...")
}
}
object MainObject{
def main(args:Array[String]){
var e = new ThreadExample()
var t = new Thread(e)
t.start()
}
}
Thread Methods
Thread class provides various methods to deals with thread's states. You can use these methods
to control the flow of thread.
The following table contains commonly used methods of Thread class.
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 12
Thread sleep() Method
The sleep() method is used to sleep thread for the specified time. It takes time in milliseconds as
an argument.
class ThreadExample extends Thread{
override def run(){
for(i<- 0 to 5){
println(i)
Thread.sleep(500)
}
}
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 13
}
object MainObject{
def main(args:Array[String]){
var t1 = new ThreadExample()
var t2 = new ThreadExample()
t1.start()
t2.start()
}
}
Thread join() Method Example
The join() method waits for a thread to die. In other words, The join() method is used to hold the
execution of currently running thread until the specified thread finished it's execution.
class ThreadExample extends Thread{
override def run(){
for(i<- 0 to 5){
println(i)
Thread.sleep(500)
}
}
}
object MainObject{
def main(args:Array[String]){
var t1 = new ThreadExample()
var t2 = new ThreadExample()
var t3 = new ThreadExample()
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 14
t1.start()
t1.join()
t2.start()
t3.start()
}
}
setName() Method Example
In the following example, we are setting and getting names of threads.
class ThreadExample() extends Thread{
override def run(){
for(i<- 0 to 5){
println(this.getName()+" - "+i)
Thread.sleep(500)
}
}
}
object MainObject{
def main(args:Array[String]){
var t1 = new ThreadExample()
var t2 = new ThreadExample()
var t3 = new ThreadExample()
t1.setName("First Thread")
t2.setName("Second Thread")
t1.start()
t2.start()
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 15
}
}
Thread Priority Example
You can set thread priority by using it's predefined method. The following example sets priority
for the thread.
class ThreadExample() extends Thread{
override def run(){
for(i<- 0 to 5){
println(this.getName())
println(this.getPriority())
Thread.sleep(500)
}
}
}
object MainObject{
def main(args:Array[String]){
var t1 = new ThreadExample()
var t2 = new ThreadExample()
t1.setName("First Thread")
t2.setName("Second Thread")
t1.setPriority(Thread.MIN_PRIORITY)
t2.setPriority(Thread.MAX_PRIORITY)
t1.start()
t2.start()
}
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 16
}
Thread Multitasking Example
The following example is running multiple tasks by using multiple threads. This example
explains that how can we implement multitasking in Scala.
class ThreadExample() extends Thread{
override def run(){
for(i<- 0 to 5){
println(i)
Thread.sleep(500)
}
}
def task(){
for(i<- 0 to 5){
println(i)
Thread.sleep(200)
}
}
}
object MainObject{
def main(args:Array[String]){
var t1 = new ThreadExample()
t1.start()
t1.task()
}
}
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 17
Collections
Collections are the container of things that contains a random number of elements. All collection
classes are found in the package scala.collection. Collections are of two types –
1. Mutable Collections
2. Immutable Collections
Mutable Collection – This type of collection is changed after it is created. All Mutable
collection classes are found in the package scala.collection.mutable.
Immutable Collection – This type of collection will never change after it is created. All
Immutable collection classes are found in the package scala.collection.immutable.
Most Common Collection types are –
 List
 Map
 Set
 Tuple
 Iterators
List
List is a collection of similar types of elements which are immutable. It represents the Linked
list. If the list contains t types of elements then it can be represented as –
List[t]
The empty list is specified by Nil which is an object that represents an empty list. The method::
pronounced cons transforms an object and a list into a new list whose head is the object and
whose tail is the first list.
val numbers: List[Int] = List(10, 20, 30 ,40) //List of Integers
val empty: List[Int] = List() // Empty List
val twodim: List[List[Int]] =
List (
List (0, 1, 0),
List (1, 1, 0)
)
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 18
List Constructors –
All lists are built from two more fundamental constructors that are Nil and::.Nil represents an
empty list. The infix operator:: expresses list extension. That is, x:: xs represents a list whose
first element is x, which is followed by list xs. You can also define the list as follows:
val numbers = 10 :: (20 :: (30 :: (40 :: Nil)))
val empty = Nil
val twodim = (0 :: (1 :: (0 :: Nil))) ::
(1 :: (1 :: (0 :: Nil))) :: Nil
For simplicity you can define the above list as follows:-
val numbers = 10 :: 20 :: 30 :: 40 :: Nil
e.g.
object Intellipaat {
def main(args: Array[String]) {
val numbers = 10 :: (20 :: (30 :: (40 :: Nil)))
val data = Nil
println( "Head of Number is : " + numbers.head )
println( "Tail of Number is : " + numebrs.tail )
println( "Check number is empty or not : " + numbers.isEmpty )
println( "Check data is empty or not : " + data.isEmpty )
}
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 19
}
 List.concat() – It is used to perform concatenation of two lists.
 List.fill() – It creates a list that contains the same element.
 List.tabulate() – It converts the list in tabular form.
 List.reverse – It is used to reverse the list elements.
Map (Hash Table)
It is a collection of key/value pairs where keys are unique and value is retrieved according to the
key. Scala Online Training provides mutable and immutable versions of Map. If you want to use
an immutable map then use Map and if you want to use a mutable map the use mutable. Map.
e.g.
var I:Map[String ,Int] = Map() // Creates empty hash table whose values are integers and keys
are string type
val data = Map(
‘a’ ->10,
‘b’ -> 20,
‘c’->30,
‘d’ ->40
)
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 20
e.g.
object Intellipaat {
def main(args: Array[String]) {
val numbers = Map(
‘a’ ->10, ‘b’ -> 20, ‘c’->30, ‘d’ ->40
)
val data: Map[char, Int] = Map()
println( "Keys in Numbers are : " + numbers.keys )
println( "Values in numbers are : " + numbers.values )
println( "Check number is empty or not : " + numbers.isEmpty )
println( "Check data is empty or not : " + data.isEmpty )
}
}
 Map.++() – It is used to concatenate two or more maps.
 Map.contains – It checks that if a given key exists in the map or not.
 Foreach loop – It is used to print the keys and values of the map.
Set
It is a collection of elements that are of the same type but do not contain the same elements. By
default, scala uses an immutable set. Scala provides mutable and immutable versions of Set. If
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 21
you want to use an immutable set then use Set and if you want to use mutable set the use
mutable. Set.
var i : Set[Int] = Set() // Empty set of integer type
var i : Set[Int] = Set(10, 20, 30, 40) // Set of integer type
Basic Operations on Set:
All operations on sets can be expressed in terms of the following three methods:
e.g.
object Intellipaat {
def main(args: Array[String]) {
val numbers = Set(10, 20, 30, 40)
val data: Set[Int] = Set()
println( "Head of Number is : " + numbers.head )
println( "Tail of numbers is : " + numbers.tail )
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 22
println( "Check number is empty or not : " + numbers.isEmpty )
println( "Check data is empty or not : " + data.isEmpty )
}
}
 Set.++() – It is used to concatenate the two or more sets.
 Set.min – It is used to find the minimum value from the elements of the set.
 Set.max() – It is used to find the maximum value from the elements of the set.
 Set.intersect – It is used to find the common values between two sets.
 Set.& – It is also used to find the common values between two sets.
Tuples
It is a collection of heterogeneous types of objects that is different types of objects which
combine a fixed number of items together.
A tuple that contains an Int and a String:
val i = (1, "intellipaat")
To access tuple elements ‘._’ is used.
e.g.
object Intellipaat {
def main(args: Array[String]) {
val i = (10, 20, 30, 40)
val total = i._1 + i._2 + i._3 + i._4
println( "Total of Elements is : " + total)
}
}
 Tuple.productIterator() – It is used to iterate over all the elements of a Tuple.
 Tuple.toString() – It is used to concatenate all the elements of the tuple into a string.
 Tuple.swap – It is used to swap the elements of a Tuple.
Iterator
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 23
It is used to access the elements of the collection one by one. Two important operations of an
iterator are –
 next
 hasNext
next – It is used to return the next element of the iterator and move ahead of the state of the
iterator.
hasNext – It is used to find out whether there are more elements to return.
e.g.
object Intellipaat {
def main(args: Array[String]) {
val i = Iterator("hello", "intellipaat", "a", "ecommerce", “site”)
while (i.hasNext){
println(i.next())
}
}
}
 iterartor.min – It is used to return the minimum value elements form iterator.
 iterator.max – It is used to return the maximum value elements form iterator.
 iterator.size – It is used to return the number of elements in the iterator.
 iterator.length – It is also used to return the number of elements in the iterator.
File Handling
File Handling is a way to store the fetched information in a file. Scala provides packages from
which we can create, open, read and write the files. For writing to a file in scala we borrow
java.io._ from Java because we don’t have a class to write into a file, in the Scala standard
library. We could also import java.io.File and java.io.PrintWriter.
Creating a new file :
java.io.File defines classes and interfaces for the JVM access files, file systems and attributes.
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 24
File(String pathname) converts theparameter string to abstract path name, creating a new file
instance.
Writing to the file
java.io.PrintWriter includes all the printing methods included in PrintStream.
Below is the implementation for creating a new file and writing into it.
// File handling program
import java.io.File
import java.io.PrintWriter
// Creating object
object Geeks
{
// Main method
def main(args:Array[String])
{
// Creating a file
val file_Object = new File("abc.txt" )
// Passing reference of file to the printwriter
val print_Writer = new PrintWriter(file_Object)
// Writing to the file
print_Writer.write("Hello, This is Geeks For Geeks")
// Closing printwriter
print_Writer.close()
}
}
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 25
A text file abc.txt is created and contains the string “Hello, This is Geeks For Geeks”
Scala does not provide class to write a file but it provide a class to read the files. This is the class
Source. We use its companion object to read files. To read the contents of this file, we call the
fromFile() method of class Source for reading the contents of the file which includes filename as
argument.
Reading a File
scala.io.Source includes methods for iterable representation of the source file.
Source.fromFile creates a source from the input file.
file.next return the next element in the iteration and moves the iterator one step ahead.
file.hasnext checks if there is next element available to iterate.
getLines– Iterate through file line by line
Below is the implementation for Reading each character from a file.
// Scala File handling program
import scala.io.Source
// Creating object
object GeeksScala
{
// Main method
def main(args : Array[String])
{
// file name
val fname = "abc.txt"
// creates iterable representation
// of the source file
val fSource = Source.fromFile(fname)
while (fSource.hasNext)
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 26
{
println(fSource.next)
}
// closing file
fSource.close()
}
}
Output:
We can use getLines() method to read individual lines instead of the whole file at once.
Below is the implementation for Reading each line from a file.
// Scala file handling program to Read each
// line from a single file
import scala.io.Source
// Creating object
object gfgScala
{
// Main method
def main(args:Array[String])
{
val fname = "abc.txt"
val fSource = Source.fromFile(fname)
for(line<-fSource.getLines)
{
println(line)
}
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 27
fSource.close()
}
}
Creating a file in Scala and writing content to it
As Scala, uses Java library the libraries of java methods are used.
In this program to will create a new file called by file myfile.txt and then write one sentence in
the file.
Program to create a file in Scala
import java.io._
object WriteFileExample {
def main(args:Array[String]){
// creating file object
val file = new File("myfile.txt" )
//creating object of the PrintWrite
//by passing the reference to the file
val pw = new PrintWriter(file)
//writing text to the file
pw.write("Welcome @ IncludeHelpn")
pw.write("writing text to the filen")
//closing the PrintWriter
pw.close()
println("PrintWriter saved and closed...")
}
}
191AIC302T-Object Oriented Programming with SCALA
Unit-V
Department of AI & DSPage 28
Output
PrintWriter saved and closed...
Reading Content line by line in Scala
You can alternatively read the contents of a file in Scala line by line,
import scala.io.Source
object MainObject{
def main(args:Array[String]){
//file name
val filename = "myfile.txt"
//file reading - creating object name by passing
//filename i.e. file object
val filereader = Source.fromFile(filename)
//printing characters
for(line<-fileSource.getLines){
println(line)
}
//closing
filereader.close()
}
}

More Related Content

Similar to Unit 5 notes.pdf

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
JasmeetSingh326
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
KALAISELVI P
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
Shipra Swati
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
Intro C# Book
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?
Pramod Yadav
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
GaneshKumarKanthiah
 

Similar to Unit 5 notes.pdf (20)

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java unit3
Java unit3Java unit3
Java unit3
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 

More from Revathiparamanathan

UNIT 1 NOTES.docx
UNIT 1 NOTES.docxUNIT 1 NOTES.docx
UNIT 1 NOTES.docx
Revathiparamanathan
 
Unit 3,4.docx
Unit 3,4.docxUnit 3,4.docx
Unit 3,4.docx
Revathiparamanathan
 
UNIT II.docx
UNIT II.docxUNIT II.docx
UNIT II.docx
Revathiparamanathan
 
UNIT V.docx
UNIT V.docxUNIT V.docx
UNIT V.docx
Revathiparamanathan
 
COMPILER DESIGN.docx
COMPILER DESIGN.docxCOMPILER DESIGN.docx
COMPILER DESIGN.docx
Revathiparamanathan
 
UNIT -III.docx
UNIT -III.docxUNIT -III.docx
UNIT -III.docx
Revathiparamanathan
 
UNIT -IV.docx
UNIT -IV.docxUNIT -IV.docx
UNIT -IV.docx
Revathiparamanathan
 
UNIT - II.docx
UNIT - II.docxUNIT - II.docx
UNIT - II.docx
Revathiparamanathan
 
UNIT -V.docx
UNIT -V.docxUNIT -V.docx
UNIT -V.docx
Revathiparamanathan
 
UNIT - I.docx
UNIT - I.docxUNIT - I.docx
UNIT - I.docx
Revathiparamanathan
 
CC -Unit3.pptx
CC -Unit3.pptxCC -Unit3.pptx
CC -Unit3.pptx
Revathiparamanathan
 
CC -Unit4.pptx
CC -Unit4.pptxCC -Unit4.pptx
CC -Unit4.pptx
Revathiparamanathan
 
CC.pptx
CC.pptxCC.pptx
Unit 4 notes.pdf
Unit 4 notes.pdfUnit 4 notes.pdf
Unit 4 notes.pdf
Revathiparamanathan
 
Unit 3 notes.pdf
Unit 3 notes.pdfUnit 3 notes.pdf
Unit 3 notes.pdf
Revathiparamanathan
 
Unit 1 notes.pdf
Unit 1 notes.pdfUnit 1 notes.pdf
Unit 1 notes.pdf
Revathiparamanathan
 
Unit 2 notes.pdf
Unit 2 notes.pdfUnit 2 notes.pdf
Unit 2 notes.pdf
Revathiparamanathan
 
CC.pptx
CC.pptxCC.pptx
Unit-4 Day1.pptx
Unit-4 Day1.pptxUnit-4 Day1.pptx
Unit-4 Day1.pptx
Revathiparamanathan
 
Scala Introduction.pptx
Scala Introduction.pptxScala Introduction.pptx
Scala Introduction.pptx
Revathiparamanathan
 

More from Revathiparamanathan (20)

UNIT 1 NOTES.docx
UNIT 1 NOTES.docxUNIT 1 NOTES.docx
UNIT 1 NOTES.docx
 
Unit 3,4.docx
Unit 3,4.docxUnit 3,4.docx
Unit 3,4.docx
 
UNIT II.docx
UNIT II.docxUNIT II.docx
UNIT II.docx
 
UNIT V.docx
UNIT V.docxUNIT V.docx
UNIT V.docx
 
COMPILER DESIGN.docx
COMPILER DESIGN.docxCOMPILER DESIGN.docx
COMPILER DESIGN.docx
 
UNIT -III.docx
UNIT -III.docxUNIT -III.docx
UNIT -III.docx
 
UNIT -IV.docx
UNIT -IV.docxUNIT -IV.docx
UNIT -IV.docx
 
UNIT - II.docx
UNIT - II.docxUNIT - II.docx
UNIT - II.docx
 
UNIT -V.docx
UNIT -V.docxUNIT -V.docx
UNIT -V.docx
 
UNIT - I.docx
UNIT - I.docxUNIT - I.docx
UNIT - I.docx
 
CC -Unit3.pptx
CC -Unit3.pptxCC -Unit3.pptx
CC -Unit3.pptx
 
CC -Unit4.pptx
CC -Unit4.pptxCC -Unit4.pptx
CC -Unit4.pptx
 
CC.pptx
CC.pptxCC.pptx
CC.pptx
 
Unit 4 notes.pdf
Unit 4 notes.pdfUnit 4 notes.pdf
Unit 4 notes.pdf
 
Unit 3 notes.pdf
Unit 3 notes.pdfUnit 3 notes.pdf
Unit 3 notes.pdf
 
Unit 1 notes.pdf
Unit 1 notes.pdfUnit 1 notes.pdf
Unit 1 notes.pdf
 
Unit 2 notes.pdf
Unit 2 notes.pdfUnit 2 notes.pdf
Unit 2 notes.pdf
 
CC.pptx
CC.pptxCC.pptx
CC.pptx
 
Unit-4 Day1.pptx
Unit-4 Day1.pptxUnit-4 Day1.pptx
Unit-4 Day1.pptx
 
Scala Introduction.pptx
Scala Introduction.pptxScala Introduction.pptx
Scala Introduction.pptx
 

Recently uploaded

Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 

Recently uploaded (20)

Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 

Unit 5 notes.pdf

  • 1. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 1 Exception handling and Multithreading Exception handling: Try-Catch Blocks - Finally Block - Throw Keyword - Throws Keyword - Custom Exception – Multithreading: Thread - Thread Life Cycle – Thread Methods – Collections - File Handling Exception Handling  An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time. These events change the flow control of the program in execution. These are situations that are not too dangerous and can be handled by the program. Exception Hierarchy All exception and errors types are sub classes of class Throwable, which is base class of hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.  Exception handling is a mechanism which is used to handle abnormal conditions. You can also avoid termination of your program unexpectedly.
  • 2. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 2  Scala makes "checked vs unchecked" very simple. It doesn't have checked exceptions. All exceptions are unchecked in Scala, even SQLException and IOException. Scala Program Example without Exception Handling class ExceptionExample{ def divide(a:Int, b:Int) = { a/b // Exception occurred here println("Rest of the code is executing...") } } object MainObject{ def main(args:Array[String]){ var e = new ExceptionExample() e.divide(100,0) } } Try Catch Scala provides try and catch block to handle exception. The try block is used to enclose suspect code. The catch block is used to handle exception occurred in try block. You can have any number of try catch block in your program according to need. Scala Try Catch Example In the following program, we have enclosed our suspect code inside try block. After try block we have used a catch handler to catch exception. If any exception occurs, catch handler will handle it and program will not terminate abnormally. class ExceptionExample{ def divide(a:Int, b:Int) = { try{
  • 3. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 3 a/b }catch{ case e: ArithmeticException => println(e) } println("Rest of the code is executing...") } } object MainObject{ def main(args:Array[String]){ var e = new ExceptionExample() e.divide(100,0) } } Output: java.lang.ArithmeticException: / by zero Rest of the code is executing... Scala Try Catch Example 2 In this example, we have two cases in our catch handler. First case will handle only arithmetic type exception. Second case has Throwable class which is a super class in exception hierarchy. The second case is able to handle any type of exception in your program. Sometimes when you don't know about the type of exception, you can use super class. class ExceptionExample{ def divide(a:Int, b:Int) = { try{ a/b var arr = Array(1,2)
  • 4. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 4 arr(10) }catch{ case e: ArithmeticException => println(e) case ex: Throwable =>println("found a unknown exception"+ ex) } println("Rest of the code is executing...") } } object MainObject{ def main(args:Array[String]){ var e = new ExceptionExample() e.divide(100,10) } } Finally The finally block is used to release resources during exception. Resources may be file, network connection, database connection etc. the finally block executes guaranteed. The following program illustrate the use of finally block. Scala Finally Block Example class ExceptionExample{ def divide(a:Int, b:Int) = { try{ a/b var arr = Array(1,2) arr(10)
  • 5. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 5 }catch{ case e: ArithmeticException => println(e) case ex: Exception =>println(ex) case th: Throwable=>println("found a unknown exception"+th) } finally{ println("Finaly block always executes") } println("Rest of the code is executing...") } } object MainObject{ def main(args:Array[String]){ var e = new ExceptionExample() e.divide(100,10) } } Throw keyword You can throw exception explicitly in you code. Scala provides throw keyword to throw exception. The throw keyword mainly used to throw custom exception. An example is given below of using scala throw exception keyword. Scala Throw Example class ExceptionExample2{ def validate(age:Int)={ if(age<18)
  • 6. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 6 throw new ArithmeticException("You are not eligible") else println("You are eligible") } } object MainObject{ def main(args:Array[String]){ var e = new ExceptionExample2() e.validate(10) } } Throws Keyword Scala provides throws keyword to declare exception. You can declare exception with method definition. It provides information to the caller function that this method may throw this exception. It helps to caller function to handle and enclose that code in try-catch block to avoid abnormal termination of program. In scala, you can either use throws keyword or throws annotation to declare exception. Scala Throws Example class ExceptionExample4{ @throws(classOf[NumberFormatException]) def validate()={ "abc".toInt } } object MainObject{ def main(args:Array[String]){ var e = new ExceptionExample4()
  • 7. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 7 try{ e.validate() }catch{ case ex : NumberFormatException => println("Exception handeled here") } println("Rest of the code executing...") } } Custom Exception In scala, you can create your own exception. It is also known as custom exceptions. You must extend Exception class while declaring custom exception class. You can create your own exception message in custom class. Let's see an example. Scala Custom Exception Example class InvalidAgeException(s:String) extends Exception(s){} class ExceptionExample{ @throws(classOf[InvalidAgeException]) def validate(age:Int){ if(age<18){ throw new InvalidAgeException("Not eligible") }else{ println("You are eligible") } } } object MainObject{ def main(args:Array[String]){
  • 8. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 8 var e = new ExceptionExample() try{ e.validate(5) }catch{ case e : Exception => println("Exception Occured : "+e) } } } Multithreading  Multithreading is a process of executing multiple threads simultaneously. It allows you to perform multiple operations independently.  You can achieved multitasking by using Multithreading. Threads are lightweight sub- processes which occupy less memory. Multithreading are used to develop concurrent applications in Scala.  Scala does not provide any separate library for creating thread. If you are familiar with multithreading concept of Java, you will come to know that it is similar except the syntax of Scala language itself.  You can create thread either by extending Thread class or Runnable interface. Both provide a run method to provide specific implementation. Scala Thread Life Cycle Thread life cycle is a span of time in which thread starts and terminates. It has various phases like new, runnable, terminate, block etc. Thread class provides various methods to monitor thread's states. The Scala thread states are as follows: 1. New 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated
  • 9. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 9 1) New This is the first state of thread. It is just before starting of new thread. 2) Runnable This is the state when thread has been started but the thread scheduler has not selected it to be the running thread. 3) Running The thread is in running state if the thread scheduler has selected it. 4) Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run due to waiting for input or resources. 5) Terminated A thread is in terminated or dead state when its run() method exits.
  • 10. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 10 Thread There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface Scala Thread Example by Extending Thread Class The following example extends Thread class and overrides run method. The start() method is used to start thread. class ThreadExample extends Thread{ override def run(){ println("Thread is running..."); } } object MainObject{ def main(args:Array[String]){ var t = new ThreadExample() t.start() } } Output: Thread is running... Scala Thread Example by Extending Runnable Interface The following example implements Runnable interface and overrides run method. The start() method is used to start thread. class ThreadExample extends Runnable{
  • 11. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 11 override def run(){ println("Thread is running...") } } object MainObject{ def main(args:Array[String]){ var e = new ThreadExample() var t = new Thread(e) t.start() } } Thread Methods Thread class provides various methods to deals with thread's states. You can use these methods to control the flow of thread. The following table contains commonly used methods of Thread class.
  • 12. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 12 Thread sleep() Method The sleep() method is used to sleep thread for the specified time. It takes time in milliseconds as an argument. class ThreadExample extends Thread{ override def run(){ for(i<- 0 to 5){ println(i) Thread.sleep(500) } }
  • 13. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 13 } object MainObject{ def main(args:Array[String]){ var t1 = new ThreadExample() var t2 = new ThreadExample() t1.start() t2.start() } } Thread join() Method Example The join() method waits for a thread to die. In other words, The join() method is used to hold the execution of currently running thread until the specified thread finished it's execution. class ThreadExample extends Thread{ override def run(){ for(i<- 0 to 5){ println(i) Thread.sleep(500) } } } object MainObject{ def main(args:Array[String]){ var t1 = new ThreadExample() var t2 = new ThreadExample() var t3 = new ThreadExample()
  • 14. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 14 t1.start() t1.join() t2.start() t3.start() } } setName() Method Example In the following example, we are setting and getting names of threads. class ThreadExample() extends Thread{ override def run(){ for(i<- 0 to 5){ println(this.getName()+" - "+i) Thread.sleep(500) } } } object MainObject{ def main(args:Array[String]){ var t1 = new ThreadExample() var t2 = new ThreadExample() var t3 = new ThreadExample() t1.setName("First Thread") t2.setName("Second Thread") t1.start() t2.start()
  • 15. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 15 } } Thread Priority Example You can set thread priority by using it's predefined method. The following example sets priority for the thread. class ThreadExample() extends Thread{ override def run(){ for(i<- 0 to 5){ println(this.getName()) println(this.getPriority()) Thread.sleep(500) } } } object MainObject{ def main(args:Array[String]){ var t1 = new ThreadExample() var t2 = new ThreadExample() t1.setName("First Thread") t2.setName("Second Thread") t1.setPriority(Thread.MIN_PRIORITY) t2.setPriority(Thread.MAX_PRIORITY) t1.start() t2.start() }
  • 16. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 16 } Thread Multitasking Example The following example is running multiple tasks by using multiple threads. This example explains that how can we implement multitasking in Scala. class ThreadExample() extends Thread{ override def run(){ for(i<- 0 to 5){ println(i) Thread.sleep(500) } } def task(){ for(i<- 0 to 5){ println(i) Thread.sleep(200) } } } object MainObject{ def main(args:Array[String]){ var t1 = new ThreadExample() t1.start() t1.task() } }
  • 17. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 17 Collections Collections are the container of things that contains a random number of elements. All collection classes are found in the package scala.collection. Collections are of two types – 1. Mutable Collections 2. Immutable Collections Mutable Collection – This type of collection is changed after it is created. All Mutable collection classes are found in the package scala.collection.mutable. Immutable Collection – This type of collection will never change after it is created. All Immutable collection classes are found in the package scala.collection.immutable. Most Common Collection types are –  List  Map  Set  Tuple  Iterators List List is a collection of similar types of elements which are immutable. It represents the Linked list. If the list contains t types of elements then it can be represented as – List[t] The empty list is specified by Nil which is an object that represents an empty list. The method:: pronounced cons transforms an object and a list into a new list whose head is the object and whose tail is the first list. val numbers: List[Int] = List(10, 20, 30 ,40) //List of Integers val empty: List[Int] = List() // Empty List val twodim: List[List[Int]] = List ( List (0, 1, 0), List (1, 1, 0) )
  • 18. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 18 List Constructors – All lists are built from two more fundamental constructors that are Nil and::.Nil represents an empty list. The infix operator:: expresses list extension. That is, x:: xs represents a list whose first element is x, which is followed by list xs. You can also define the list as follows: val numbers = 10 :: (20 :: (30 :: (40 :: Nil))) val empty = Nil val twodim = (0 :: (1 :: (0 :: Nil))) :: (1 :: (1 :: (0 :: Nil))) :: Nil For simplicity you can define the above list as follows:- val numbers = 10 :: 20 :: 30 :: 40 :: Nil e.g. object Intellipaat { def main(args: Array[String]) { val numbers = 10 :: (20 :: (30 :: (40 :: Nil))) val data = Nil println( "Head of Number is : " + numbers.head ) println( "Tail of Number is : " + numebrs.tail ) println( "Check number is empty or not : " + numbers.isEmpty ) println( "Check data is empty or not : " + data.isEmpty ) }
  • 19. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 19 }  List.concat() – It is used to perform concatenation of two lists.  List.fill() – It creates a list that contains the same element.  List.tabulate() – It converts the list in tabular form.  List.reverse – It is used to reverse the list elements. Map (Hash Table) It is a collection of key/value pairs where keys are unique and value is retrieved according to the key. Scala Online Training provides mutable and immutable versions of Map. If you want to use an immutable map then use Map and if you want to use a mutable map the use mutable. Map. e.g. var I:Map[String ,Int] = Map() // Creates empty hash table whose values are integers and keys are string type val data = Map( ‘a’ ->10, ‘b’ -> 20, ‘c’->30, ‘d’ ->40 )
  • 20. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 20 e.g. object Intellipaat { def main(args: Array[String]) { val numbers = Map( ‘a’ ->10, ‘b’ -> 20, ‘c’->30, ‘d’ ->40 ) val data: Map[char, Int] = Map() println( "Keys in Numbers are : " + numbers.keys ) println( "Values in numbers are : " + numbers.values ) println( "Check number is empty or not : " + numbers.isEmpty ) println( "Check data is empty or not : " + data.isEmpty ) } }  Map.++() – It is used to concatenate two or more maps.  Map.contains – It checks that if a given key exists in the map or not.  Foreach loop – It is used to print the keys and values of the map. Set It is a collection of elements that are of the same type but do not contain the same elements. By default, scala uses an immutable set. Scala provides mutable and immutable versions of Set. If
  • 21. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 21 you want to use an immutable set then use Set and if you want to use mutable set the use mutable. Set. var i : Set[Int] = Set() // Empty set of integer type var i : Set[Int] = Set(10, 20, 30, 40) // Set of integer type Basic Operations on Set: All operations on sets can be expressed in terms of the following three methods: e.g. object Intellipaat { def main(args: Array[String]) { val numbers = Set(10, 20, 30, 40) val data: Set[Int] = Set() println( "Head of Number is : " + numbers.head ) println( "Tail of numbers is : " + numbers.tail )
  • 22. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 22 println( "Check number is empty or not : " + numbers.isEmpty ) println( "Check data is empty or not : " + data.isEmpty ) } }  Set.++() – It is used to concatenate the two or more sets.  Set.min – It is used to find the minimum value from the elements of the set.  Set.max() – It is used to find the maximum value from the elements of the set.  Set.intersect – It is used to find the common values between two sets.  Set.& – It is also used to find the common values between two sets. Tuples It is a collection of heterogeneous types of objects that is different types of objects which combine a fixed number of items together. A tuple that contains an Int and a String: val i = (1, "intellipaat") To access tuple elements ‘._’ is used. e.g. object Intellipaat { def main(args: Array[String]) { val i = (10, 20, 30, 40) val total = i._1 + i._2 + i._3 + i._4 println( "Total of Elements is : " + total) } }  Tuple.productIterator() – It is used to iterate over all the elements of a Tuple.  Tuple.toString() – It is used to concatenate all the elements of the tuple into a string.  Tuple.swap – It is used to swap the elements of a Tuple. Iterator
  • 23. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 23 It is used to access the elements of the collection one by one. Two important operations of an iterator are –  next  hasNext next – It is used to return the next element of the iterator and move ahead of the state of the iterator. hasNext – It is used to find out whether there are more elements to return. e.g. object Intellipaat { def main(args: Array[String]) { val i = Iterator("hello", "intellipaat", "a", "ecommerce", “site”) while (i.hasNext){ println(i.next()) } } }  iterartor.min – It is used to return the minimum value elements form iterator.  iterator.max – It is used to return the maximum value elements form iterator.  iterator.size – It is used to return the number of elements in the iterator.  iterator.length – It is also used to return the number of elements in the iterator. File Handling File Handling is a way to store the fetched information in a file. Scala provides packages from which we can create, open, read and write the files. For writing to a file in scala we borrow java.io._ from Java because we don’t have a class to write into a file, in the Scala standard library. We could also import java.io.File and java.io.PrintWriter. Creating a new file : java.io.File defines classes and interfaces for the JVM access files, file systems and attributes.
  • 24. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 24 File(String pathname) converts theparameter string to abstract path name, creating a new file instance. Writing to the file java.io.PrintWriter includes all the printing methods included in PrintStream. Below is the implementation for creating a new file and writing into it. // File handling program import java.io.File import java.io.PrintWriter // Creating object object Geeks { // Main method def main(args:Array[String]) { // Creating a file val file_Object = new File("abc.txt" ) // Passing reference of file to the printwriter val print_Writer = new PrintWriter(file_Object) // Writing to the file print_Writer.write("Hello, This is Geeks For Geeks") // Closing printwriter print_Writer.close() } }
  • 25. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 25 A text file abc.txt is created and contains the string “Hello, This is Geeks For Geeks” Scala does not provide class to write a file but it provide a class to read the files. This is the class Source. We use its companion object to read files. To read the contents of this file, we call the fromFile() method of class Source for reading the contents of the file which includes filename as argument. Reading a File scala.io.Source includes methods for iterable representation of the source file. Source.fromFile creates a source from the input file. file.next return the next element in the iteration and moves the iterator one step ahead. file.hasnext checks if there is next element available to iterate. getLines– Iterate through file line by line Below is the implementation for Reading each character from a file. // Scala File handling program import scala.io.Source // Creating object object GeeksScala { // Main method def main(args : Array[String]) { // file name val fname = "abc.txt" // creates iterable representation // of the source file val fSource = Source.fromFile(fname) while (fSource.hasNext)
  • 26. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 26 { println(fSource.next) } // closing file fSource.close() } } Output: We can use getLines() method to read individual lines instead of the whole file at once. Below is the implementation for Reading each line from a file. // Scala file handling program to Read each // line from a single file import scala.io.Source // Creating object object gfgScala { // Main method def main(args:Array[String]) { val fname = "abc.txt" val fSource = Source.fromFile(fname) for(line<-fSource.getLines) { println(line) }
  • 27. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 27 fSource.close() } } Creating a file in Scala and writing content to it As Scala, uses Java library the libraries of java methods are used. In this program to will create a new file called by file myfile.txt and then write one sentence in the file. Program to create a file in Scala import java.io._ object WriteFileExample { def main(args:Array[String]){ // creating file object val file = new File("myfile.txt" ) //creating object of the PrintWrite //by passing the reference to the file val pw = new PrintWriter(file) //writing text to the file pw.write("Welcome @ IncludeHelpn") pw.write("writing text to the filen") //closing the PrintWriter pw.close() println("PrintWriter saved and closed...") } }
  • 28. 191AIC302T-Object Oriented Programming with SCALA Unit-V Department of AI & DSPage 28 Output PrintWriter saved and closed... Reading Content line by line in Scala You can alternatively read the contents of a file in Scala line by line, import scala.io.Source object MainObject{ def main(args:Array[String]){ //file name val filename = "myfile.txt" //file reading - creating object name by passing //filename i.e. file object val filereader = Source.fromFile(filename) //printing characters for(line<-fileSource.getLines){ println(line) } //closing filereader.close() } }