SlideShare a Scribd company logo
1 of 53
Download to read offline
Dr. Martin Chapman
programming@kcl.ac.uk
martinchapman.co.uk/teaching
Programming Practice and Applications (4CCS1PPA)
Topic 2: Storing Data
Q: If you were programming a computer game, when would you need to store data? 1
Friday 30th September
To understand why and how to store data in a program.
To understand the different types of simple data we can
store in a program.
STORING DATA: OBJECTIVES
2
Must be inside a file called HelloWorld.java
REMEMBER: A SIMPLE JAVA PROGRAM
3
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
public class MartinPrinter {
public static void main(String[] args) {
System.out.println("+------+");
System.out.println("|Martin|");
System.out.println("+------+");
}
} MartinPrinter.java
A SLIGHTLY MORE COMPLEX PROGRAM
4
When we have more than one line in a program, the program
is executed line-by-line.
Because class names
summarise
functionality, they are
typically nouns.
We tend to use different classes to hold
distinct pieces of functionality, like this.
😴
A THIRD PROGRAM: SOME MORE BOILERPLATE
5
The number of milliseconds that have elapsed since midnight,
January 1, 1970.
public class TimePrinter {
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
}
} TimePrinter.java
🖥
Using the syntax shown in the last three slides, we are able to solve
new straight forward problems (try these in your lab).
• Print a 3x3 text grid to the terminal (using symbols).
• Print the current time to the terminal three times.
What about slightly more complex problems?
• Because the statements in a program are executed line-by-line,
it takes time for a program to run. In theory, the more lines (or if
particular operations are performed within those lines), the
longer the program takes to run.
• Print how long it takes for the computer to execute the print line
statements from Slide 4 (only using ).
PROBLEM SOLVING
6Topic2-1
System.currentTimeMillis()
public class MartinPrinter {
public static void main(String[] args) {
System.out.println("+------+");
System.out.println("|Martin|");
System.out.println("+------+");
System.out.println( );
}
} MartinPrinter.java
RUNNING TIME
7
Record the current time
Compute the difference between the
time now and the recorded time.
For solving problems like this in Java, it is clear that we need to
store some data.
Calculating running time is quite a specific problem
motivating the storage of data.
• But it avoids the introduction of new syntax at this stage.
There are a number of other more intuitive problems that
require the storage of data, that might be too complex to
discuss at this stage.
• Storing the current score in a game.
• Storing the result of user input.
• Counting the number of cars entering a car park.
ASIDE: STORING DATA
8
😴
When programming, variables provide us with a place in which to
store data.
Here’s an example of a variable declaration:
VARIABLES
9
To help us conceptualise a variable, and what we can do with
it, we have a choice of (useful) metaphors.
public class VariableTester {
public static void main (String[] args) {
int myFirstIntegerVariable;
}
} VariableTester.java
(USEFUL) METAPHORS GALORE
10
public class VariableTester {
public static void main (String[] args) {
int myFirstIntegerVariable;
}
}
A named fileA labelled box
We give a variable a name.
A VARIABLE AS A BOX (METAPHOR 1) (1)
11
There is a label on our box.
int myFirstIntegerVariable;
Not all the words in a Java program have a special meaning. Some
are selected by us.
REMEMBER: NAMING RULES AND CONVENTIONS IN JAVA (1)
12
But there are rules for human selected text (intuitive)
• Cannot begin with a number (because we wouldn’t be able to
identify values).
• Cannot contain spaces.
• Cannot contain symbols other than $ and _.
• Cannot be reserved Java keywords (such as int).
int myVerySpecialPlaceInWhichToStoreThings;
camelCaseNotation is typical, but not enforced
• Variable names do not capitalise the first letter
(myFirstIntegerVariable)
Making intelligible and presentable variable name choices is part of
the artistic element of coding.
REMEMBER: NAMING RULES AND CONVENTIONS IN JAVA (2)
13
Using the same variable name twice will result in a name conflict.
• But any name selected will differ from the same name written
in a different case.
int myAMZNGVARIABLE777776611
🙈
We can assign values to the variable.
A VARIABLE AS A BOX (METAPHOR 1) (2)
14
int myFirstIntegerVariable;
myFirstIntegerVariable = 1;
int myFirstIntegerVariable = 1;
or
1
We can open the box, and put things in.
To run, this code would still
have to be in a main
method, in a class, I’ve just
shortened it for readability.
The first time we assign a
value to a variable is called
initialisation.
We can declare and
initialise a variable in the
same line if we already
know the value it will
contain.
We can reference the variable as many times as we like,
using its name.
A VARIABLE AS A BOX (METAPHOR 1) (3)
15
1
We can open the box and look inside as many times as we like.
System.out.println(myFirstIntegerVariable);
System.out.println(myFirstIntegerVariable);
int myFirstIntegerVariable = 1;
🙈
We can reassign the variable as many times as we like.
A VARIABLE AS A BOX (METAPHOR 1) (4)
16
We can open the box, take something out, and put
something else in.
int myFirstIntegerVariable = 1;
myFirstIntegerVariable = 3;
myFirstIntegerVariable = 20;
1320
We declare that this variable is designed to store integers
(whole numbers within a certain range).
A VARIABLE AS A BOX (METAPHOR 1) (5)
17
We place a label on the box, so that it is clear what we
expect to find inside.
int myFirstIntegerVariable;
We give a variable a name.
A file has a name.
A VARIABLE AS A FILE (METAPHOR 2) (1)
18
int myFirstIntegerVariable;
We can assign values to the variable.
We can open the file, and enter some information.
A VARIABLE AS A FILE (METAPHOR 2) (2)
19
int myFirstIntegerVariable;
myFirstIntegerVariable = 1;
int myFirstIntegerVariable = 1;
or
We can reference the variable as many times as we like,
using its name.
We can open the file and extract the information as often as
we wish.
A VARIABLE AS A FILE (METAPHOR 2) (3)
20
System.out.println(myFirstIntegerVariable);
System.out.println(myFirstIntegerVariable);
int myFirstIntegerVariable = 1;
We can reassign the variable as many times as we like.
We can delete the text in the file, and enter something new.
A VARIABLE AS A FILE (METAPHOR 2) (4)
21
int myFirstIntegerVariable = 1;
myFirstIntegerVariable = 3;
myFirstIntegerVariable = 20;
We declare that this variable is designed to store integers
(whole numbers within a certain range).
A file demonstrates the type of data it can hold through its
labelled extension (e.g. .txt means text content).
A VARIABLE AS A FILE (METAPHOR 2) (5)
22
int myFirstIntegerVariable;
Like a labelled file extension, languages care, to different
degrees, about you being explicit about the types of things you
intend to store in a variable.
• Errors can be determined at compile time.
• Our code is readable.
• Some loss of flexibility.
Java forces us to explicitly state what we intend to store in a
variable.
• Languages like Python or Javascript are less strict.
TYPED LANGUAGES
23
public class VariableTester {
public static void main (String[] args) {
int myFirstIntegerVariable;
}
} VariableTester.java
Of course we’re already adhering to this rule in our example.
INTEGER TYPES
24
Here, we’ve told Java that we’ve decided to only store integers in
this variable.
The format of a variable declaration is thus type followed by name.
🙈
A good way to learn how to program is to try to break things.
For example, what happens if we don’t specify a type?
BREAKING THE RULES (1): NO TYPE
25
public class VariableTester {
public static void main (String[] args) {
myFirstIntegerVariable;
}
}
The role of the Java compiler is not just to transform our
text file into a program, but also to tell us when our text file
contains certain keywords that are not valid Java syntax.
Every time we do something wrong, like in the previous
slide, we will receive an error message in the terminal,
rather than any output from our own program.
ERROR: NOT A STATEMENT
26These are called compile-time errors.
🤔
What happens if we try and interact with a variable (e.g. try
and print it), without first assigning a value to that variable?
BREAKING THE RULES (2): NO VALUE
27
int myFirstIntegerVariable;
System.out.println(myFirstIntegerVariable);
🤔
ERROR: VARIABLE MIGHT NOT HAVE BEEN INITIALISED
28
This occurs because variables, when they are used in this way,
are not given default values.
Aside: this contrasts other languages, where the accessible
content of uninitialised variables depends on the state of
memory.
Later on, we will see variables used in a different way. Then,
variables will have default values.
What happens if we assign a floating point number to an
declared integer variable?
BREAKING THE RULES (3): WRONG TYPE
29
int myFirstIntegerVariable = 3.1415;
ERROR: POSSIBLE LOSSY CONVERSION
30
In the same way that you cannot (easily) place an image into a
text file, you cannot place data of a different type into a typed
variable (directly).
This is usually because it would result in us losing some data
(more shortly).
Fortunately, variables can store different types of data, not just
integers, so we simply declare the right type for our purpose…
BREAKING THE RULES (3): WRONG TYPE
31
int myFirstIntegerVariable = 3.1415;
What happens if we assign a floating point number to an
declared integer variable?
Double is a type that allows us to represent floating point
numbers.
DOUBLE TYPES
32
double myFirstDoubleVariable = 3.1415;
Different data types have different representations in
memory.
😴
It is not strictly true that you cannot assign values of
different types to typed variables.
If this were true programming in Java would be very
frustrating.
In reality, values can be converted (or cast) as different
types.
This will happen automatically (implicit casting) but only
when there will be no loss of precision.
ASIDE: CASTING
33
😴
For instance, in our previous example, when we tried to assign a
floating point number to an integer variable, Java would be unable to
store the fractional part (given the memory format used to store an
integer), so automatic casting does not take place, and we get an
error.
ASIDE: CASTING (IMPLICIT)
34
int myFirstIntegerVariable = 3.1415;
double myFirstDoubleVariable = 3;
System.out.println(myFirstDoubleVariable);
However, the other way round is fine, because nothing is lost. An
integer is implicitly converted to a double with extra precision.
😴
We could, if we desperately wanted, force Java to omit the
additional precision of a double, thus allowing us to store
the double as an integer.
ASIDE: CASTING (EXPLICIT)
35
This bracketed notation is called an explicit cast.
Explicit casts from double to integer are rare (in my
experience), but later in the course we will see when
explicit casts are more important.
int myFirstIntegerVariable = (int)3.1415;
System.out.println(myFirstIntegerVariable);
😴
ASIDE: CASTING
36
Why `casting’? Because the same value is cast in different roles.
🤐
What happens if we assign a huge number to an integer
variable?
BREAKING THE RULES (4): OUT OF RANGE (1)
37
int myFirstIntegerVariable = 4294967296;
ERROR: INTEGER NUMBER TOO LARGE
38
🤐
BREAKING THE RULES (4): OUT OF RANGE (2)
39
Why is this? Variables are given a maximum size in memory.
The sizes selected were designed to maximise speed and
reduce memory consumption.
• More about this in 4CCS1CS1
• Why have I chosen this number specifically?
What happens if we assign a huge number to an integer
variable?
int myFirstIntegerVariable = 4294967296;
🤐
For the majority of the tasks in PPA, you will not have to be
concerned about memory.
More generally, we will typically concern ourselves with what
is going on at a high level, rather than at the machine level.
ASIDE: MEMORY ALLOCATION OF VARIABLES
40
This doesn’t
mean we will be
purposefully
inefficient!
If we want to store a large number, we have to use a
different datatype, a long; `long integer’
BREAKING THE RULES (4): OUT OF RANGE (3)
41
What’s this?
long myFirstLongVariable = 4294967296l;
We call these literals.
Sometimes the type of a literal isn’t always clear, so we need
additional syntax to help us specify type.
So far, we have seen several syntactic representations of
data types. We use these to express values in our program.
ASIDE: LITERALS
42
In the previous example it is isn’t clear whether the literal is
supposed to be an integer or a long, so we postfix an `l’ to
make this distinction.
double myFirstDoubleVariable = 3.1415;
long myFirstLongVariable = 4294967296l;
😴
public class MartinPrinter {
public static void main(String[] args) {
long currentTime = System.currentTimeMillis();
System.out.println("+------+");
System.out.println("|Martin|");
System.out.println("+------+");
System.out.println(System.currentTimeMillis() - currentTime);
}
}
ASIDE: BACK TO RUNNING TIME
43
Anything that can
be printed can
also be stored
Open question: How do we know that time is returned in a
long format?
We can do simple arithmetic in Java, using
standard notation (more later).
We now have enough syntax to solve our running time problem.
MartinPrinter.java
😴
public class MartinPrinter {
public static void main(String[] args) {
long currentTime = System.currentTimeMillis();
System.out.println("+------+");
System.out.println("|Martin|");
System.out.println("+------+");
System.out.println(System.currentTimeMillis() - currentTime);
ASIDE: COMMENTS
44
Now that we have code of reasonable complexity, it makes sense that
we should annotate this code with a description, in order to remind us
of what it does, should we wish to come back to it in the future.
Single line comments (ignored plaintext, which starts with a double
slash notation) enable us to do this.
// Record the current time.
// Perform the operation we wish to measure.
Annotating any code you find
in these slides with comments,
as you write it out, is excellent
for revision.
🤓
BREAKING THE RULES (4): OUT OF RANGE (4)
45
The opposite is true of double. We could represent a smaller
value using the type float. (Think double = double size).
Remember: If we want to store a large number, we have to
use a different datatype, a long; `long integer’
float myFirstFloatVaraible = 3.1415f;
Note the intuitive literal
long myFirstLongVariable = 4294967296l;
COMPARISON OF TYPES
46
Somewhat a style choice.
I rarely use longs, opting for integers (I have no need, usually, for
the additional space).
• We might have to use longs if the values given to us are of
the long type (as we saw with our running time example).
I rarely use floats, because doubles offer more precision, and the
memory overhead is negligible.
FLOAT OR DOUBLE? LONG OR INT?
47
🖥
The types we have seen so far — int, long, float, double — are simple, so
we refer to them as primitive types.
For some of these primitive types, we have answered the following:
• What kind of literal values can they store? How do we differentiate
literals (i.e. do we need to postfix a particular character)?
• What happens if you try and assign values of a different type to
variables of this type?
• Can other type values be implicitly cast to this type?
• What happens if other type values are explicitly cast to this type?
Complete this analysis for all types. There are 8 primitive types in total, so
you must research the 4 types we have not talked about.
OTHER DATA TYPES (1)
48Topic2-2
🖥
Keep an exhaustive list of any tests you do as code, and note the result
using comments.
• These comments don’t necessarily have to describe what the code
does (as we saw previously), but instead what you have learnt.
• Comments like this are good for your own understanding but you
shouldn’t generally use them in code you submit for assessment.
OTHER DATA TYPES (2)
49Topic2-2
// Integer variables accept integer literals.
int myFirstIntegerVariable = 1;
// Integer variables do not accept double literals.
int mySecondIntegerVariable = 1.0;
Keep this for reference and for revision.
🤔
Java is traditionally an imperative language.
• There’s an expectation that we solve problems by
issuing instructions that change a program’s state (held
in variables).
• We describe how things are done in a series of steps.
ASIDE: IMPERATIVE VS. FUNCTIONAL LANGUAGES (1)
50
🤔
Other languages (e.g. Haskel, Prolog) are declarative.
• Often considered an abstraction over imperative languages, where we
state what to do, not how to do it.
• Popularly defined by the sub-approach functional programming, where
state cannot be changed (i.e. variables cannot be changed), but instead
problems are solved using a set of functions that correlate input to output.
• So we could solve some of the problems stated in these slides without
storing any results.
In the latest version of Java, the introduction of certain syntactic elements (e.g.
Lambda expressions) suggests more of a synthesis with functional programming.
Which is better? Hotly debated. But imperative is currently more widely used.
ASIDE: IMPERATIVE VS. FUNCTIONAL LANGUAGES (2)
51
🤔
ASIDE: IMPERATIVE VS. FUNCTIONAL LANGUAGES (3)
52
function double (arr) {
let results = []
for (let i = 0; i < arr.length; i++){
results.push(arr[i] * 2)
}
return results
}
function double (arr) {
return arr.map((item) => item * 2)
}
Dr. Martin Chapman
programming@kcl.ac.uk
martinchapman.co.uk/teaching
Programming Practice and Applications (4CCS1PPA)
Topic 2: Storing Data
These slides will be available on KEATS, but will be subject to
ongoing amendments. Therefore, please always download a new
version of these slides when approaching an assessed piece of work,
or when preparing for a written assessment. 53
Friday 30th September

More Related Content

What's hot

Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interfacemanish kumar
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Programming in Java: Library Classes
Programming in Java: Library ClassesProgramming in Java: Library Classes
Programming in Java: Library ClassesMartin Chapman
 
This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...rapidbounce
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packagesmanish kumar
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2Vince Vo
 
Fnctions part2
Fnctions part2Fnctions part2
Fnctions part2yndaravind
 
Variables in python
Variables in pythonVariables in python
Variables in pythonJaya Kumari
 

What's hot (20)

Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Notes on c++
Notes on c++Notes on c++
Notes on c++
 
Oops
OopsOops
Oops
 
Programming in Java: Library Classes
Programming in Java: Library ClassesProgramming in Java: Library Classes
Programming in Java: Library Classes
 
M C6java2
M C6java2M C6java2
M C6java2
 
This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packages
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Monad Fact #6
Monad Fact #6Monad Fact #6
Monad Fact #6
 
Inheritance Mixins & Traits
Inheritance Mixins & TraitsInheritance Mixins & Traits
Inheritance Mixins & Traits
 
Fnctions part2
Fnctions part2Fnctions part2
Fnctions part2
 
Inheritance
InheritanceInheritance
Inheritance
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 

Similar to Programming in Java: Storing Data

C interview questions
C interview questionsC interview questions
C interview questionsSoba Arjun
 
Vba and macro creation (using excel)
Vba and macro creation (using excel)Vba and macro creation (using excel)
Vba and macro creation (using excel)Javier Morales Cauna
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptxRockyIslam5
 
Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?Martin Chapman
 
Java basics variables
 Java basics   variables Java basics   variables
Java basics variablesJoeReddieMedia
 
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfjorgeulises3
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 
 staple  here  (-­‐2  if  not  stapled  or .docx
  staple  here  (-­‐2  if  not  stapled  or .docx  staple  here  (-­‐2  if  not  stapled  or .docx
 staple  here  (-­‐2  if  not  stapled  or .docxmayank272369
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringEyob Lube
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template PatternJonathan Simon
 

Similar to Programming in Java: Storing Data (20)

Maxbox starter
Maxbox starterMaxbox starter
Maxbox starter
 
Numerical data.
Numerical data.Numerical data.
Numerical data.
 
C interview questions
C interview questionsC interview questions
C interview questions
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Vba and macro creation (using excel)
Vba and macro creation (using excel)Vba and macro creation (using excel)
Vba and macro creation (using excel)
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
 
Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?
 
Java basics variables
 Java basics   variables Java basics   variables
Java basics variables
 
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
java intro.pptx.pdf
java intro.pptx.pdfjava intro.pptx.pdf
java intro.pptx.pdf
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
 staple  here  (-­‐2  if  not  stapled  or .docx
  staple  here  (-­‐2  if  not  stapled  or .docx  staple  here  (-­‐2  if  not  stapled  or .docx
 staple  here  (-­‐2  if  not  stapled  or .docx
 
Ds
DsDs
Ds
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
 
Core java
Core javaCore java
Core java
 

More from Martin Chapman

Principles of Health Informatics: Artificial intelligence and machine learning
Principles of Health Informatics: Artificial intelligence and machine learningPrinciples of Health Informatics: Artificial intelligence and machine learning
Principles of Health Informatics: Artificial intelligence and machine learningMartin Chapman
 
Principles of Health Informatics: Clinical decision support systems
Principles of Health Informatics: Clinical decision support systemsPrinciples of Health Informatics: Clinical decision support systems
Principles of Health Informatics: Clinical decision support systemsMartin Chapman
 
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...Martin Chapman
 
Technical Validation through Automated Testing
Technical Validation through Automated TestingTechnical Validation through Automated Testing
Technical Validation through Automated TestingMartin Chapman
 
Scalable architectures for phenotype libraries
Scalable architectures for phenotype librariesScalable architectures for phenotype libraries
Scalable architectures for phenotype librariesMartin Chapman
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Martin Chapman
 
Using AI to autonomously identify diseases within groups of patients
Using AI to autonomously identify diseases within groups of patientsUsing AI to autonomously identify diseases within groups of patients
Using AI to autonomously identify diseases within groups of patientsMartin Chapman
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Martin Chapman
 
Principles of Health Informatics: Evaluating medical software
Principles of Health Informatics: Evaluating medical softwarePrinciples of Health Informatics: Evaluating medical software
Principles of Health Informatics: Evaluating medical softwareMartin Chapman
 
Principles of Health Informatics: Usability of medical software
Principles of Health Informatics: Usability of medical softwarePrinciples of Health Informatics: Usability of medical software
Principles of Health Informatics: Usability of medical softwareMartin Chapman
 
Principles of Health Informatics: Social networks, telehealth, and mobile health
Principles of Health Informatics: Social networks, telehealth, and mobile healthPrinciples of Health Informatics: Social networks, telehealth, and mobile health
Principles of Health Informatics: Social networks, telehealth, and mobile healthMartin Chapman
 
Principles of Health Informatics: Communication systems in healthcare
Principles of Health Informatics: Communication systems in healthcarePrinciples of Health Informatics: Communication systems in healthcare
Principles of Health Informatics: Communication systems in healthcareMartin Chapman
 
Principles of Health Informatics: Terminologies and classification systems
Principles of Health Informatics: Terminologies and classification systemsPrinciples of Health Informatics: Terminologies and classification systems
Principles of Health Informatics: Terminologies and classification systemsMartin Chapman
 
Principles of Health Informatics: Representing medical knowledge
Principles of Health Informatics: Representing medical knowledgePrinciples of Health Informatics: Representing medical knowledge
Principles of Health Informatics: Representing medical knowledgeMartin Chapman
 
Principles of Health Informatics: Informatics skills - searching and making d...
Principles of Health Informatics: Informatics skills - searching and making d...Principles of Health Informatics: Informatics skills - searching and making d...
Principles of Health Informatics: Informatics skills - searching and making d...Martin Chapman
 
Principles of Health Informatics: Informatics skills - communicating, structu...
Principles of Health Informatics: Informatics skills - communicating, structu...Principles of Health Informatics: Informatics skills - communicating, structu...
Principles of Health Informatics: Informatics skills - communicating, structu...Martin Chapman
 
Principles of Health Informatics: Models, information, and information systems
Principles of Health Informatics: Models, information, and information systemsPrinciples of Health Informatics: Models, information, and information systems
Principles of Health Informatics: Models, information, and information systemsMartin Chapman
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Martin Chapman
 
Using Microservices to Design Patient-facing Research Software
Using Microservices to Design Patient-facing Research SoftwareUsing Microservices to Design Patient-facing Research Software
Using Microservices to Design Patient-facing Research SoftwareMartin Chapman
 
Using CWL to support EHR-based phenotyping
Using CWL to support EHR-based phenotypingUsing CWL to support EHR-based phenotyping
Using CWL to support EHR-based phenotypingMartin Chapman
 

More from Martin Chapman (20)

Principles of Health Informatics: Artificial intelligence and machine learning
Principles of Health Informatics: Artificial intelligence and machine learningPrinciples of Health Informatics: Artificial intelligence and machine learning
Principles of Health Informatics: Artificial intelligence and machine learning
 
Principles of Health Informatics: Clinical decision support systems
Principles of Health Informatics: Clinical decision support systemsPrinciples of Health Informatics: Clinical decision support systems
Principles of Health Informatics: Clinical decision support systems
 
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
 
Technical Validation through Automated Testing
Technical Validation through Automated TestingTechnical Validation through Automated Testing
Technical Validation through Automated Testing
 
Scalable architectures for phenotype libraries
Scalable architectures for phenotype librariesScalable architectures for phenotype libraries
Scalable architectures for phenotype libraries
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...
 
Using AI to autonomously identify diseases within groups of patients
Using AI to autonomously identify diseases within groups of patientsUsing AI to autonomously identify diseases within groups of patients
Using AI to autonomously identify diseases within groups of patients
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...
 
Principles of Health Informatics: Evaluating medical software
Principles of Health Informatics: Evaluating medical softwarePrinciples of Health Informatics: Evaluating medical software
Principles of Health Informatics: Evaluating medical software
 
Principles of Health Informatics: Usability of medical software
Principles of Health Informatics: Usability of medical softwarePrinciples of Health Informatics: Usability of medical software
Principles of Health Informatics: Usability of medical software
 
Principles of Health Informatics: Social networks, telehealth, and mobile health
Principles of Health Informatics: Social networks, telehealth, and mobile healthPrinciples of Health Informatics: Social networks, telehealth, and mobile health
Principles of Health Informatics: Social networks, telehealth, and mobile health
 
Principles of Health Informatics: Communication systems in healthcare
Principles of Health Informatics: Communication systems in healthcarePrinciples of Health Informatics: Communication systems in healthcare
Principles of Health Informatics: Communication systems in healthcare
 
Principles of Health Informatics: Terminologies and classification systems
Principles of Health Informatics: Terminologies and classification systemsPrinciples of Health Informatics: Terminologies and classification systems
Principles of Health Informatics: Terminologies and classification systems
 
Principles of Health Informatics: Representing medical knowledge
Principles of Health Informatics: Representing medical knowledgePrinciples of Health Informatics: Representing medical knowledge
Principles of Health Informatics: Representing medical knowledge
 
Principles of Health Informatics: Informatics skills - searching and making d...
Principles of Health Informatics: Informatics skills - searching and making d...Principles of Health Informatics: Informatics skills - searching and making d...
Principles of Health Informatics: Informatics skills - searching and making d...
 
Principles of Health Informatics: Informatics skills - communicating, structu...
Principles of Health Informatics: Informatics skills - communicating, structu...Principles of Health Informatics: Informatics skills - communicating, structu...
Principles of Health Informatics: Informatics skills - communicating, structu...
 
Principles of Health Informatics: Models, information, and information systems
Principles of Health Informatics: Models, information, and information systemsPrinciples of Health Informatics: Models, information, and information systems
Principles of Health Informatics: Models, information, and information systems
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...
 
Using Microservices to Design Patient-facing Research Software
Using Microservices to Design Patient-facing Research SoftwareUsing Microservices to Design Patient-facing Research Software
Using Microservices to Design Patient-facing Research Software
 
Using CWL to support EHR-based phenotyping
Using CWL to support EHR-based phenotypingUsing CWL to support EHR-based phenotyping
Using CWL to support EHR-based phenotyping
 

Recently uploaded

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

Programming in Java: Storing Data

  • 1. Dr. Martin Chapman programming@kcl.ac.uk martinchapman.co.uk/teaching Programming Practice and Applications (4CCS1PPA) Topic 2: Storing Data Q: If you were programming a computer game, when would you need to store data? 1 Friday 30th September
  • 2. To understand why and how to store data in a program. To understand the different types of simple data we can store in a program. STORING DATA: OBJECTIVES 2
  • 3. Must be inside a file called HelloWorld.java REMEMBER: A SIMPLE JAVA PROGRAM 3 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
  • 4. public class MartinPrinter { public static void main(String[] args) { System.out.println("+------+"); System.out.println("|Martin|"); System.out.println("+------+"); } } MartinPrinter.java A SLIGHTLY MORE COMPLEX PROGRAM 4 When we have more than one line in a program, the program is executed line-by-line. Because class names summarise functionality, they are typically nouns. We tend to use different classes to hold distinct pieces of functionality, like this.
  • 5. 😴 A THIRD PROGRAM: SOME MORE BOILERPLATE 5 The number of milliseconds that have elapsed since midnight, January 1, 1970. public class TimePrinter { public static void main(String[] args) { System.out.println(System.currentTimeMillis()); } } TimePrinter.java
  • 6. 🖥 Using the syntax shown in the last three slides, we are able to solve new straight forward problems (try these in your lab). • Print a 3x3 text grid to the terminal (using symbols). • Print the current time to the terminal three times. What about slightly more complex problems? • Because the statements in a program are executed line-by-line, it takes time for a program to run. In theory, the more lines (or if particular operations are performed within those lines), the longer the program takes to run. • Print how long it takes for the computer to execute the print line statements from Slide 4 (only using ). PROBLEM SOLVING 6Topic2-1 System.currentTimeMillis()
  • 7. public class MartinPrinter { public static void main(String[] args) { System.out.println("+------+"); System.out.println("|Martin|"); System.out.println("+------+"); System.out.println( ); } } MartinPrinter.java RUNNING TIME 7 Record the current time Compute the difference between the time now and the recorded time. For solving problems like this in Java, it is clear that we need to store some data.
  • 8. Calculating running time is quite a specific problem motivating the storage of data. • But it avoids the introduction of new syntax at this stage. There are a number of other more intuitive problems that require the storage of data, that might be too complex to discuss at this stage. • Storing the current score in a game. • Storing the result of user input. • Counting the number of cars entering a car park. ASIDE: STORING DATA 8
  • 9. 😴 When programming, variables provide us with a place in which to store data. Here’s an example of a variable declaration: VARIABLES 9 To help us conceptualise a variable, and what we can do with it, we have a choice of (useful) metaphors. public class VariableTester { public static void main (String[] args) { int myFirstIntegerVariable; } } VariableTester.java
  • 10. (USEFUL) METAPHORS GALORE 10 public class VariableTester { public static void main (String[] args) { int myFirstIntegerVariable; } } A named fileA labelled box
  • 11. We give a variable a name. A VARIABLE AS A BOX (METAPHOR 1) (1) 11 There is a label on our box. int myFirstIntegerVariable;
  • 12. Not all the words in a Java program have a special meaning. Some are selected by us. REMEMBER: NAMING RULES AND CONVENTIONS IN JAVA (1) 12 But there are rules for human selected text (intuitive) • Cannot begin with a number (because we wouldn’t be able to identify values). • Cannot contain spaces. • Cannot contain symbols other than $ and _. • Cannot be reserved Java keywords (such as int). int myVerySpecialPlaceInWhichToStoreThings;
  • 13. camelCaseNotation is typical, but not enforced • Variable names do not capitalise the first letter (myFirstIntegerVariable) Making intelligible and presentable variable name choices is part of the artistic element of coding. REMEMBER: NAMING RULES AND CONVENTIONS IN JAVA (2) 13 Using the same variable name twice will result in a name conflict. • But any name selected will differ from the same name written in a different case. int myAMZNGVARIABLE777776611
  • 14. 🙈 We can assign values to the variable. A VARIABLE AS A BOX (METAPHOR 1) (2) 14 int myFirstIntegerVariable; myFirstIntegerVariable = 1; int myFirstIntegerVariable = 1; or 1 We can open the box, and put things in. To run, this code would still have to be in a main method, in a class, I’ve just shortened it for readability. The first time we assign a value to a variable is called initialisation. We can declare and initialise a variable in the same line if we already know the value it will contain.
  • 15. We can reference the variable as many times as we like, using its name. A VARIABLE AS A BOX (METAPHOR 1) (3) 15 1 We can open the box and look inside as many times as we like. System.out.println(myFirstIntegerVariable); System.out.println(myFirstIntegerVariable); int myFirstIntegerVariable = 1;
  • 16. 🙈 We can reassign the variable as many times as we like. A VARIABLE AS A BOX (METAPHOR 1) (4) 16 We can open the box, take something out, and put something else in. int myFirstIntegerVariable = 1; myFirstIntegerVariable = 3; myFirstIntegerVariable = 20; 1320
  • 17. We declare that this variable is designed to store integers (whole numbers within a certain range). A VARIABLE AS A BOX (METAPHOR 1) (5) 17 We place a label on the box, so that it is clear what we expect to find inside. int myFirstIntegerVariable;
  • 18. We give a variable a name. A file has a name. A VARIABLE AS A FILE (METAPHOR 2) (1) 18 int myFirstIntegerVariable;
  • 19. We can assign values to the variable. We can open the file, and enter some information. A VARIABLE AS A FILE (METAPHOR 2) (2) 19 int myFirstIntegerVariable; myFirstIntegerVariable = 1; int myFirstIntegerVariable = 1; or
  • 20. We can reference the variable as many times as we like, using its name. We can open the file and extract the information as often as we wish. A VARIABLE AS A FILE (METAPHOR 2) (3) 20 System.out.println(myFirstIntegerVariable); System.out.println(myFirstIntegerVariable); int myFirstIntegerVariable = 1;
  • 21. We can reassign the variable as many times as we like. We can delete the text in the file, and enter something new. A VARIABLE AS A FILE (METAPHOR 2) (4) 21 int myFirstIntegerVariable = 1; myFirstIntegerVariable = 3; myFirstIntegerVariable = 20;
  • 22. We declare that this variable is designed to store integers (whole numbers within a certain range). A file demonstrates the type of data it can hold through its labelled extension (e.g. .txt means text content). A VARIABLE AS A FILE (METAPHOR 2) (5) 22 int myFirstIntegerVariable;
  • 23. Like a labelled file extension, languages care, to different degrees, about you being explicit about the types of things you intend to store in a variable. • Errors can be determined at compile time. • Our code is readable. • Some loss of flexibility. Java forces us to explicitly state what we intend to store in a variable. • Languages like Python or Javascript are less strict. TYPED LANGUAGES 23
  • 24. public class VariableTester { public static void main (String[] args) { int myFirstIntegerVariable; } } VariableTester.java Of course we’re already adhering to this rule in our example. INTEGER TYPES 24 Here, we’ve told Java that we’ve decided to only store integers in this variable. The format of a variable declaration is thus type followed by name.
  • 25. 🙈 A good way to learn how to program is to try to break things. For example, what happens if we don’t specify a type? BREAKING THE RULES (1): NO TYPE 25 public class VariableTester { public static void main (String[] args) { myFirstIntegerVariable; } }
  • 26. The role of the Java compiler is not just to transform our text file into a program, but also to tell us when our text file contains certain keywords that are not valid Java syntax. Every time we do something wrong, like in the previous slide, we will receive an error message in the terminal, rather than any output from our own program. ERROR: NOT A STATEMENT 26These are called compile-time errors.
  • 27. 🤔 What happens if we try and interact with a variable (e.g. try and print it), without first assigning a value to that variable? BREAKING THE RULES (2): NO VALUE 27 int myFirstIntegerVariable; System.out.println(myFirstIntegerVariable);
  • 28. 🤔 ERROR: VARIABLE MIGHT NOT HAVE BEEN INITIALISED 28 This occurs because variables, when they are used in this way, are not given default values. Aside: this contrasts other languages, where the accessible content of uninitialised variables depends on the state of memory. Later on, we will see variables used in a different way. Then, variables will have default values.
  • 29. What happens if we assign a floating point number to an declared integer variable? BREAKING THE RULES (3): WRONG TYPE 29 int myFirstIntegerVariable = 3.1415;
  • 30. ERROR: POSSIBLE LOSSY CONVERSION 30
  • 31. In the same way that you cannot (easily) place an image into a text file, you cannot place data of a different type into a typed variable (directly). This is usually because it would result in us losing some data (more shortly). Fortunately, variables can store different types of data, not just integers, so we simply declare the right type for our purpose… BREAKING THE RULES (3): WRONG TYPE 31 int myFirstIntegerVariable = 3.1415; What happens if we assign a floating point number to an declared integer variable?
  • 32. Double is a type that allows us to represent floating point numbers. DOUBLE TYPES 32 double myFirstDoubleVariable = 3.1415; Different data types have different representations in memory.
  • 33. 😴 It is not strictly true that you cannot assign values of different types to typed variables. If this were true programming in Java would be very frustrating. In reality, values can be converted (or cast) as different types. This will happen automatically (implicit casting) but only when there will be no loss of precision. ASIDE: CASTING 33
  • 34. 😴 For instance, in our previous example, when we tried to assign a floating point number to an integer variable, Java would be unable to store the fractional part (given the memory format used to store an integer), so automatic casting does not take place, and we get an error. ASIDE: CASTING (IMPLICIT) 34 int myFirstIntegerVariable = 3.1415; double myFirstDoubleVariable = 3; System.out.println(myFirstDoubleVariable); However, the other way round is fine, because nothing is lost. An integer is implicitly converted to a double with extra precision.
  • 35. 😴 We could, if we desperately wanted, force Java to omit the additional precision of a double, thus allowing us to store the double as an integer. ASIDE: CASTING (EXPLICIT) 35 This bracketed notation is called an explicit cast. Explicit casts from double to integer are rare (in my experience), but later in the course we will see when explicit casts are more important. int myFirstIntegerVariable = (int)3.1415; System.out.println(myFirstIntegerVariable);
  • 36. 😴 ASIDE: CASTING 36 Why `casting’? Because the same value is cast in different roles.
  • 37. 🤐 What happens if we assign a huge number to an integer variable? BREAKING THE RULES (4): OUT OF RANGE (1) 37 int myFirstIntegerVariable = 4294967296;
  • 38. ERROR: INTEGER NUMBER TOO LARGE 38
  • 39. 🤐 BREAKING THE RULES (4): OUT OF RANGE (2) 39 Why is this? Variables are given a maximum size in memory. The sizes selected were designed to maximise speed and reduce memory consumption. • More about this in 4CCS1CS1 • Why have I chosen this number specifically? What happens if we assign a huge number to an integer variable? int myFirstIntegerVariable = 4294967296;
  • 40. 🤐 For the majority of the tasks in PPA, you will not have to be concerned about memory. More generally, we will typically concern ourselves with what is going on at a high level, rather than at the machine level. ASIDE: MEMORY ALLOCATION OF VARIABLES 40 This doesn’t mean we will be purposefully inefficient!
  • 41. If we want to store a large number, we have to use a different datatype, a long; `long integer’ BREAKING THE RULES (4): OUT OF RANGE (3) 41 What’s this? long myFirstLongVariable = 4294967296l;
  • 42. We call these literals. Sometimes the type of a literal isn’t always clear, so we need additional syntax to help us specify type. So far, we have seen several syntactic representations of data types. We use these to express values in our program. ASIDE: LITERALS 42 In the previous example it is isn’t clear whether the literal is supposed to be an integer or a long, so we postfix an `l’ to make this distinction. double myFirstDoubleVariable = 3.1415; long myFirstLongVariable = 4294967296l;
  • 43. 😴 public class MartinPrinter { public static void main(String[] args) { long currentTime = System.currentTimeMillis(); System.out.println("+------+"); System.out.println("|Martin|"); System.out.println("+------+"); System.out.println(System.currentTimeMillis() - currentTime); } } ASIDE: BACK TO RUNNING TIME 43 Anything that can be printed can also be stored Open question: How do we know that time is returned in a long format? We can do simple arithmetic in Java, using standard notation (more later). We now have enough syntax to solve our running time problem. MartinPrinter.java
  • 44. 😴 public class MartinPrinter { public static void main(String[] args) { long currentTime = System.currentTimeMillis(); System.out.println("+------+"); System.out.println("|Martin|"); System.out.println("+------+"); System.out.println(System.currentTimeMillis() - currentTime); ASIDE: COMMENTS 44 Now that we have code of reasonable complexity, it makes sense that we should annotate this code with a description, in order to remind us of what it does, should we wish to come back to it in the future. Single line comments (ignored plaintext, which starts with a double slash notation) enable us to do this. // Record the current time. // Perform the operation we wish to measure. Annotating any code you find in these slides with comments, as you write it out, is excellent for revision.
  • 45. 🤓 BREAKING THE RULES (4): OUT OF RANGE (4) 45 The opposite is true of double. We could represent a smaller value using the type float. (Think double = double size). Remember: If we want to store a large number, we have to use a different datatype, a long; `long integer’ float myFirstFloatVaraible = 3.1415f; Note the intuitive literal long myFirstLongVariable = 4294967296l;
  • 47. Somewhat a style choice. I rarely use longs, opting for integers (I have no need, usually, for the additional space). • We might have to use longs if the values given to us are of the long type (as we saw with our running time example). I rarely use floats, because doubles offer more precision, and the memory overhead is negligible. FLOAT OR DOUBLE? LONG OR INT? 47
  • 48. 🖥 The types we have seen so far — int, long, float, double — are simple, so we refer to them as primitive types. For some of these primitive types, we have answered the following: • What kind of literal values can they store? How do we differentiate literals (i.e. do we need to postfix a particular character)? • What happens if you try and assign values of a different type to variables of this type? • Can other type values be implicitly cast to this type? • What happens if other type values are explicitly cast to this type? Complete this analysis for all types. There are 8 primitive types in total, so you must research the 4 types we have not talked about. OTHER DATA TYPES (1) 48Topic2-2
  • 49. 🖥 Keep an exhaustive list of any tests you do as code, and note the result using comments. • These comments don’t necessarily have to describe what the code does (as we saw previously), but instead what you have learnt. • Comments like this are good for your own understanding but you shouldn’t generally use them in code you submit for assessment. OTHER DATA TYPES (2) 49Topic2-2 // Integer variables accept integer literals. int myFirstIntegerVariable = 1; // Integer variables do not accept double literals. int mySecondIntegerVariable = 1.0; Keep this for reference and for revision.
  • 50. 🤔 Java is traditionally an imperative language. • There’s an expectation that we solve problems by issuing instructions that change a program’s state (held in variables). • We describe how things are done in a series of steps. ASIDE: IMPERATIVE VS. FUNCTIONAL LANGUAGES (1) 50
  • 51. 🤔 Other languages (e.g. Haskel, Prolog) are declarative. • Often considered an abstraction over imperative languages, where we state what to do, not how to do it. • Popularly defined by the sub-approach functional programming, where state cannot be changed (i.e. variables cannot be changed), but instead problems are solved using a set of functions that correlate input to output. • So we could solve some of the problems stated in these slides without storing any results. In the latest version of Java, the introduction of certain syntactic elements (e.g. Lambda expressions) suggests more of a synthesis with functional programming. Which is better? Hotly debated. But imperative is currently more widely used. ASIDE: IMPERATIVE VS. FUNCTIONAL LANGUAGES (2) 51
  • 52. 🤔 ASIDE: IMPERATIVE VS. FUNCTIONAL LANGUAGES (3) 52 function double (arr) { let results = [] for (let i = 0; i < arr.length; i++){ results.push(arr[i] * 2) } return results } function double (arr) { return arr.map((item) => item * 2) }
  • 53. Dr. Martin Chapman programming@kcl.ac.uk martinchapman.co.uk/teaching Programming Practice and Applications (4CCS1PPA) Topic 2: Storing Data These slides will be available on KEATS, but will be subject to ongoing amendments. Therefore, please always download a new version of these slides when approaching an assessed piece of work, or when preparing for a written assessment. 53 Friday 30th September