This document provides an overview of exception handling and multithreading in Scala. It discusses try-catch blocks, finally blocks, and throwing and declaring exceptions. It also covers creating and controlling threads, thread life cycles, and implementing multitasking. Additionally, it summarizes common collection types like lists, maps, sets, and tuples in Scala.
Exception handling - Fundamentals of exception handling, Exception types, Termination or resumptive models, Uncaught exceptions, using try and catch, multiple catch clauses, nested try statements, throw, throws and finally, built- in exceptions, creating own exception sub classes.
Multithreading- Differences between thread-based multitasking and process-based multitasking, Java thread model, creating threads, thread priorities, synchronizing threads, inter thread communication
Exception handling - Fundamentals of exception handling, Exception types, Termination or resumptive models, Uncaught exceptions, using try and catch, multiple catch clauses, nested try statements, throw, throws and finally, built- in exceptions, creating own exception sub classes.
Multithreading- Differences between thread-based multitasking and process-based multitasking, Java thread model, creating threads, thread priorities, synchronizing threads, inter thread communication
Exceptions in java contains info about checked unchecked exceptions also methods for handling them. it also contains info about keywords like throw throws catch finally etc.
Qcon2011 functions rockpresentation_scalaMichael Stal
This is the part I of the tutorial I planned to give at QCon 2011 on Functional Programming with Scala. It also includes Scala 2.8 as well as upcoming features
An exception is a problem that arises during the time of execution of program. An exception can occur for many different reasons, including the following.
A user has enter invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communicatons,or the JVM has run out of memory.
Some of these exception are caused by user error, others by programmer error, and others by physical resources, that have failed in some manner.
Java - Exceptions. An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
In this chapter we will discuss exceptions in the object-oriented programming and in C# in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct. We will give various examples for using exceptions. We will look at the types of exceptions and the exceptions hierarchy in the .NET Framework. At the end, we will look at the advantages of using exceptions, best practices and how to apply them in different situations.
unit 4 msbte syallbus for sem 4 2024-2025AKSHAYBHABAD5
The Intel 8086 microprocessor, designed by Intel in the late 1970s, is an 8-bit/16-bit microprocessor and the first member of the x86 family of microprocessors1. Here’s a brief overview of its internal architecture:
Complex Instruction Set Computer (CISC) Architecture: The 8086 microprocessor is based on a CISC architecture, which supports a wide range of instructions, many of which can perform multiple operations in a single instruction1.
Bus Interface Unit (BIU): The BIU is responsible for fetching instructions from memory and decoding them, while also managing data transfer between the microprocessor and memory or I/O devices1.
Execution Unit (EU): The EU executes the instructions1.
Memory Segmentation: The 8086 microprocessor has a segmented memory architecture, which means that memory is divided into segments that are addressed using both a segment register and an offset1.
Registers: The 8086 microprocessor has a rich set of registers, including general-purpose registers, segment registers, and special registers
Java - exception. An exception (or extraordinary event) is a problem that occurs during the execution of a program. When an exception occurs, the normal flow of the program is interrupted and the program / application terminates abnormally, which is not recommended, therefore, these exceptions have to be controlled.
Types of exception to handle exception in java
Exceptions in java contains info about checked unchecked exceptions also methods for handling them. it also contains info about keywords like throw throws catch finally etc.
Qcon2011 functions rockpresentation_scalaMichael Stal
This is the part I of the tutorial I planned to give at QCon 2011 on Functional Programming with Scala. It also includes Scala 2.8 as well as upcoming features
An exception is a problem that arises during the time of execution of program. An exception can occur for many different reasons, including the following.
A user has enter invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communicatons,or the JVM has run out of memory.
Some of these exception are caused by user error, others by programmer error, and others by physical resources, that have failed in some manner.
Java - Exceptions. An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
In this chapter we will discuss exceptions in the object-oriented programming and in C# in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct. We will give various examples for using exceptions. We will look at the types of exceptions and the exceptions hierarchy in the .NET Framework. At the end, we will look at the advantages of using exceptions, best practices and how to apply them in different situations.
unit 4 msbte syallbus for sem 4 2024-2025AKSHAYBHABAD5
The Intel 8086 microprocessor, designed by Intel in the late 1970s, is an 8-bit/16-bit microprocessor and the first member of the x86 family of microprocessors1. Here’s a brief overview of its internal architecture:
Complex Instruction Set Computer (CISC) Architecture: The 8086 microprocessor is based on a CISC architecture, which supports a wide range of instructions, many of which can perform multiple operations in a single instruction1.
Bus Interface Unit (BIU): The BIU is responsible for fetching instructions from memory and decoding them, while also managing data transfer between the microprocessor and memory or I/O devices1.
Execution Unit (EU): The EU executes the instructions1.
Memory Segmentation: The 8086 microprocessor has a segmented memory architecture, which means that memory is divided into segments that are addressed using both a segment register and an offset1.
Registers: The 8086 microprocessor has a rich set of registers, including general-purpose registers, segment registers, and special registers
Java - exception. An exception (or extraordinary event) is a problem that occurs during the execution of a program. When an exception occurs, the normal flow of the program is interrupted and the program / application terminates abnormally, which is not recommended, therefore, these exceptions have to be controlled.
Types of exception to handle exception in java
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
About
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Technical Specifications
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
Key Features
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface
• Compatible with MAFI CCR system
• Copatiable with IDM8000 CCR
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
Application
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
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()
}
}