0% found this document useful (0 votes)
2 views

Output Variables DataTypes Week20part1 Block A

This document introduces programming in Scala, covering basic concepts such as output, variables, and data types. It explains the setup required to run Scala programs using IntelliJ IDEA and the Java Virtual Machine (JVM), and provides guidelines on writing and compiling Scala code. Key topics include variable declaration, data types, and the structure of a simple Scala program.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Output Variables DataTypes Week20part1 Block A

This document introduces programming in Scala, covering basic concepts such as output, variables, and data types. It explains the setup required to run Scala programs using IntelliJ IDEA and the Java Virtual Machine (JVM), and provides guidelines on writing and compiling Scala code. Key topics include variable declaration, data types, and the structure of a simple Scala program.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

CTEC1703

Computer Programming

Output, Variables, and Data Types


Week 20 part 1

Introduction to programming in Scala (Block A: week 20)

1
Objectives
 Introduce the module and Scala platform

 Create, compile and run basic programs within


IntelliJ IDEA

 Explore basic language features such as


formatting output, variables and data types

2
What is a computer program?
 A list of instructions to tell the computer what to do.

 Computer programs contain source code allowing us


to develop applications and software.

 We write code using a programming language. Our


high level language then gets translated into a low
level language (e.g. machine code) that interacts with
the underlying hardware.

 Much like natural languages, programming languages


have syntax and grammar rules.
3
Definitions
 Program – a set of instructions given to a computer.
 Software – the name given to a single program or set
of programs.
 Application Software – useful programs that a user
might need, e.g. word-processors, web browsers, etc.
 Systems Software – special programs that help the
computer to do its job, e.g. operating systems, network
software, etc. Often these interact with the underlying
hardware of the machine.

4
Why Scala?
 Programming languages fall into different paradigms –
Scala is described as a hybrid language as it is both
object-oriented and functional.

 Scala runs on the Java Virtual Machine (JVM),


meaning it is cross-platform compatible.

 With a wealth of libraries, Scala is a very expressive,


elegant, and powerful language. It is also statically
typed so type checking is done by the compiler.

5
What we need to run Scala programs
 Scala runs on the Java Virtual Machine (JVM), which
can run on Windows, Linux or Mac.

 We therefore need to install the Java Development Kit


(JDK), which comes with the Java Runtime
Environment (JRE), giving us access to a JVM as well
as other Java resources Scala may use.

 We then need to download the Scala language


binaries, either independently or as part of a
development environment.

6
Developing our own Scala programs
 You will need an editor, within which you can write your
programming code.

 You will need a compiler to check your code for errors


and then to convert your program into byte code that
the Java Virtual Machine (JVM) understands.

 You then need a way of running your program on the


JVM, also allowing for basic I / O.

7
Notepad and the Command Prompt
 On Windows the simplest way to build and run your
own programs is with Notepad and the Command
Prompt.

 Notepad is a very basic text editor – allows us to write


code.

 Command Prompt is a command-line interpreter -


allows us to compile our program, run it and view basic
output.

8
Compiling and Running a program
 Change to directory where program exists:
 Use command cd (change directory), e.g. cd C:\progs\

 Source code is compiled by:


 Entering scalac Hello.scala in the command-line
 If no errors, compiler creates one or more byte code files
Hello.class and tasty files Hello.tasty (used in Scala 3)

 Run the program by entering scala Hello in the


command-line.
9
Compile and Run process

scalac MyProg.scala

MyProg.class
MyProg$.class
MyProg.tasty

scala MyProg

10
IntelliJ all-in-one IDE
 It currently seems like a lot of effort to build, compile
and run a simple Scala program.

 A solution exists! IntelliJ IDEA. An Integrated


Development Environment application that facilitates
Scala development via a plugin.

 This provides a basis for managing, writing, compiling


and running your programs in a single location, without
having to type commands.

11
IntelliJ structure
 We can choose a single project providing us with a
storage location for all our Scala programs.

 A project can contain many modules – e.g. we could


have one module per lab exercise.

 A single module may contain many Scala source files


and therefore a variety of Scala applications.

12
IntelliJ key features
 Project tool window – modules, programs and libraries.

 Editor – source code, syntax highlighting, errors, code


completion, etc.

 Run tool window – program input and output.

 Problems / Build tool window – problematic code,


compilation errors, etc.

 Settings – change theme, font size, etc.

 Scala REPL – experiment with expressions.


13
The main method
 As a minimum a Scala program must have a single
object file containing a method called main.

 The main method triggers all activity – it makes a


program executable, and is the application's entry point.

 A larger Scala application would be split across multiple


source files, one of which would contain a main.

 A simple program may be written with main alone.

14
First Scala Program
object HelloWorld {
def main(args: Array[String]): Unit = {

//this will print the message "hello world"


println("Hello World")
}
}

 Normally saved in a file called HelloWorld.scala


 Scala is case sensitive – object not Object.
 “Camel case” naming convention – each word capitalised
except possibly the first: MyApplication, myVariable.
 Our Scala application names start with a capital letter.
15
Scala Syntax and Layout
 Braces { } hold together a block (section of code):
 Must always be paired.
 Should be lined up vertically for easy visibility.

 Within a block of code, although whitespace is ignored


by the compiler, indentation should be applied to make
the program structure easily visible.

 You should follow the “2-space convention”, i.e. each


new block is indented by 2 spaces from its outer block.
IntelliJ can assist with this! (Ctrl+Alt+L)
16
Scala Syntax and Layout (cont...)
 In many languages instructions are terminated with a
semi-colon ; at the end of each line. In scala this is
optional unless there are multiple statements per line.

 Comments allow developers to document their code for


maintenance purposes:
 Inline comments - //a comment
 Block comments - /* a block
comment */
 All comments are ignored by the compiler – they do not
execute.
17
The Scala REPL
 The REPL is a command-line interpreter that allows you to
experiment by typing in expressions for evaluation, giving instant
feedback. This is useful to experiment with language features.

 It reads an expression, evaluates it, prints it, and reads the next
expression. read-eval-print-loop (REPL)

 You can run a REPL within IntelliJ from the Tools menu. You may
even run a selection of code from your program in the interpreter.

 You can also run a Scala REPL within a command prompt by


typing scala (if you have the binaries installed). You can use the
 arrow keys to go to previous commands, and tab completion
can also be helpful.
18
Producing output
 The standard output stream is a channel between a
program and its environment, e.g. the Run tool window.
 The methods print and println are used for this.
 Most notably we can print numbers, characters and
strings (i.e. Character sequences).
print(0.5); println('a'); print(25);
print("\tHi\n\tFred\n"); println("\\Go\\")

 A character preceded by a \ is an escape sequence


with a special meaning . A newline is \n, a tab \t,
double quote is \", etc.
19
String concatenation using +
 A string literal is a sequence of characters in double
quotes. Anything passed to the print methods other
than a string is converted to a string, e.g. print(0.5)
converts 0.5 to a string and prints it.

 Strings can be concatenated (i.e. joined) together, e.g.


println("Hello" + " there " + "Fred!")

 Other values are also concatenated with strings if either


the left or right operand is a string, e.g.
println("The number was " + 55 + '!')

20
Variables
 Almost every program needs to store data – we can
store data in our programs with variables

 A variable has a data type and an identifier (i.e. name)


and is made up of the following structure:
identifier: data type e.g. myNumber: Int

 The data type determines the amount of memory


required and the type of values that can be stored. The
identifier allows us to refer to a variable in our program
rather than having to write the actual memory address.
21
Variable declaration & initialisation
 When we want to use a variable in our program we
firstly need to declare it using the var keyword to:
 tell the compiler to provide a place in memory, of the correct
size for the type
 label it with our chosen name

 We then must initialise the variable by assigning it a


value:
 var myNumber: Int = 5

22
The Assignment Operator
 The assignment operator uses the "equals sign" = to
assign values to a variable – this may be used for:
 Initialisation of a variable
 Overwriting the existing value stored in a variable

 You can assign a literal value or the value of one


variable to another:
 myNumber = 10; myNumber = otherNumber;

 Note on LHS myNumber represents a memory location,


whereas on RHS otherNumber represents a value.
23
myVar1

99 4 bytes

0x001000

myVar2

'e' 2 bytes

0x003050
Variable Naming syntax rules
 The identifier you give your variables has to conform to
a set of syntax rules:
 May begin with a letter, $ or _ but latter two are discouraged.
 Subsequent characters may be letters, digits, $ or _
 Names are case sensitive and white space is not allowed.
 Cannot use any reserved keywords, e.g. "if", "val", "var", etc.
 It is possible to use certain symbolic operators in names, but
this is only encouraged in very specific circumstances.
total5 //OK 5total //not OK total 5 //not OK

_total or $total //discouraged val //keyword, not OK

25
Cannot use as identifiers for variables:

26
Variable Naming conventions
 The identifier you give your variables should conform to
a common conventions of good practice:
 Start with lower case letters.
 Use full words where possible or sensible abbreviations.
 Equally, don't make names too long – you’ll have to repeat this!
 If more than one word, capitalise first letter of each subsequent
word – i.e. "Camel case".
name //OK firstName //OK firstname //discouraged

thisIsAVeryVeryLongName //discouraged i //may be


OK

27
Basic Data Types
 Commonly used value types are:
 Int – (4 bytes) integer type, whole numbers -2147483648 to
+2147483647 (i.e. -231 .. +231-1)
 Double – (8 bytes) holds real numbers such as 3.142
 Boolean – holds one of two values, true or false
 Char – (2 bytes) holds letters, punctuation and control
characters, as Unicode, an extension of ASCII code
 String – A sequence of characters

 Other types of note are:


 Byte (1 byte) Short (2 bytes) Long (8 bytes) Float (4 bytes)

28
Example declarations
var name: String = "fred"

var ratePerHour: Double = 8.55

var letter: Char = 'z'

var bigNumber: Long = 500000000000L

var result: Boolean = true

var exp: Boolean = 'a' > 'b'


29
Summary
 IntelliJ IDEA allows us to run Scala programs on the
JVM.

 We can use print and read methods for output and


input.

 Variables allow us to store and reuse values in


memory.

 Basic data types such as Int, Char and String allow us


to carry out many common programming tasks.
30
Suggested reading
 Online Tutorials:
 https://www.tutorialspoint.com/scala/
 http://docs.scala-lang.org/
 https://alvinalexander.com/scala/scala-programming-cookbook
-recipes-faqs

 Textbooks:
 Programming in Scala (3rd edition) by Martin Odersky
 An Introduction to programming and problem-solving using
Scala (2nd edition) by Mark C. Lewis and Lisa L. Lacher

31

You might also like