Learning Objectives:
-
Identify the most appropriate data type category for a particular specification.
-
Declare variables of the correct types to represent primitive data.
-
Evaluate arithmetic expressions in a program code.
-
Evaluate what is stored in a variable as a result of an expression with an assignment statement.
-
Evaluate arithmetic expressions that use casting.
Essential Knowledge:
-
System.out.println
displays information on the computer monitor. -
A(data)type is a set of values(a domain)and a set of operations on them.
-
Data types can be categorized as primitive.
-
The primitive data types used in this course define the set of operations for numbers and
boolean
values. -
The three primitive data types used in this course are
int
,double
, andboolean
. -
Each variable has associated memory that is used to hold its value.
-
The memory associated with a variable of a primitive type holds an actual primitive value.
-
When a variable is declared
final
, its value cannot be changed once it is initialized. -
A literal is the source code representation of a fixed value.
-
Arithmetic expressions include expressions of type
int
anddouble
. -
The arithmetic operators consist of
+
,-
,*
,/
, and%
. -
An arithmetic operation that uses two
int
values will evaluate to anint
value. -
An arithmetic operation that uses two
double
values will evaluate to andouble
value. -
Operators can be used to construct compound expressions.
-
During evaluation, operands are associated with operators according to operator precedence to determine how they are grouped.
-
An attempt to divide an integer by zero will result in an
ArithmeticException
to occur. -
The assignment operator (
=
) allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left. -
During execution, expressions are evaluated to produce a single value.
-
The value of an expression has a type based on the evaluation of the expression.
-
Compound assignment operators (
+=
,-=
,*=
,/=
,%=
) can be used in place of the assignment operator. -
The casting operators (
int
) and (double
) can be used to create a temporary value converted to a different data type. -
Casting a
double
value to anint
causes the digits to the right of the decimal point to be truncated. -
Some programming code causes
int
values to be automatically cast (widened) todouble
values. -
Values of type
double
can be rounded to the nearest integer by(int)(x + 0.5)
or(int)(x - 0.5)
for negative numbers.
Identifier/Variables
-
A name made up by the programmer to identify and reserve the address in memory where a particular piece of data is stored.
-
Basically like how we use algebra in maths(letters that represent values in equations)
-
But we can also use words(as well as letters)in programs and we can have "text" or other values(as well as numerical values).
-
-
When a program runs, any data that it uses is stored in RAM.
-
If a variable name is not used, then the location is not reserved, so data can be overwritten at any time and lost.
-
Similar to reserving a table at a restaurant.
-
-
-
-
An identifier/variable is a name made up by the programmer to identify the address in RAM where a particular piece of data is stored.
Data Type
-
Defines the values that a variable can take.
-
Data consists of bit (1 or 0) patterns.
-
The data type tells the program and in turn, the computer, the "meaning" of the data, so it knows how to process the data.
-
The computer needs to be told how to process each bit pattern(what it "means").
-
Different kinds of values require different amounts of memory and are stored in different ways.
-
-
Based on the data type of a variable, the operating system (OS) allocates memory and decides what can be stored in the reserved memory.
Data Type Sizes
-
When humans write a number we think of the space that a small number takes up as being less than a large one.
-
e.g. 1 is shorter and takes up less space than 100,000.
-
When we want to write a large number we make sure there is more "space" available than for a small number.
-
We have problems when we want to change a small number to a large one and there is not enough "space" to write it.
-
Computers can't do this and reserve a certain amount of "space" for every number of a certain data type so small and large numbers all take up the same amount of space.
-
Leading 0's are added to the left, e.g. 00000001 = 1.
-
Larger ranges or more decimal points need more bits so more space.
Data Types in Java
-
2 categories of data type in Java:
-
Primitive data types:
-
We will look at these data types here.
-
Non-primitive data types:
-
Arrays and Strings are non-primitive data types, we will discuss them in much later topics(from 7. Strings onwards.
int
-
short for integer, which are all positive and negative numbers, including zero.
-
4 bytes
-
The int data type only allows values between -2,147,483,648 and 2,147,483,647(approx. +2 billion to -2 billion).
double
-
Sufficient for holding 15 decimal digits.
-
8 bytes
-
Range: -1.7E308 to 1.7E308
-
E = "ten to the power of"
-
When writing numbers as double it is suggested that, even for whole numbers, you always use a decimal point or write
D
on the end. -
e.g.
12.0
or12D
-
If you only write 12 then Javac will convert from
int
todouble
for you(i.e. from 12 -> 12.0)as this is a safe conversion.
boolean
-
Can only be either true or false.
-
1 byte
Other primitive data types not on your syllabus:
-
char
-
Short for character and is used to represent a single character(includes all symbols on a keyboard).
-
2 bytes in Java(to enable Unicode representation - see the Conversion topic).
-
All char values must be enclosed in single quotes, e.g. 'G'.
-
byte
-
Can hold whole number between -128 and 127(2 bytes).
-
Mostly used to save memory and when you are certain that the numbers would be in the limit specified by the byte data type.
-
short
-
Greater than byte in terms of size and less than
int
(2 bytes). -
Its range is -32,768 to 32767.
-
long
-
Used when int is not large enough to hold the value, it has wider range than
int
data type, ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807(8 bytes). -
Always suffix float values with the "
L
" otherwise Javac will consider it as anint
. -
float
-
Sufficient for holding 6 to 7 decimal digits(range: +3.4E38 to -3.4E38, 4 bytes = less range and accuracy than
double
but consequently uses less storage space). -
Always suffix float values with the "
F
" otherwise Javac will consider it as adouble
. -
e.g.
22.4F
.
Variable naming convention in Java
-
Should begin with a lower case letter and for multiple words use a capital from the 2nd word to begin each word(as no spaces are allowed, this helps make the name more readable):
-
e.g.
number
,smallNumber
,bigNumber
-
Note that variable names are case sensitive.
-
So
smallNumber
andsmallnumber
will be considered as different variables in Java.
How to declare a variable in Java
-
Java is a statically typed language(unlike Python for example).
-
Means that the data type of a variable must be declared(made known)at compile time.
-
To declare a variable follow this syntax:
-
data_type variableName
;
-
e.g.
int num;
Types of Operator in Java
-
Basic Arithmetic Operators
-
Assignment Operators
-
Unary +, -
-
Relational(comparison)operators
-
Logical Operators(including Unary !)
-
Unary Auto-increment & Auto-decrement Operators
-
Concatenation
-
Bitwise Operators
-
Ternary Operator
-
We will cover types 1 - 3 here.
1. Basic Arithmetic Operators
-
+
,-
,*
,/
,%
Arithmetic Operator Precedence Rules
-
Do anything involving a power or a square root next(these are also known as orders), again working from left to right if there is more than one.
-
Multiplication and division rank equally, so you go from left to right in the sum, doing each operation in the order in which it appears.
-
Again, subtraction and addition rank equally, and you simply move from left to right.
2. Assignment Operators
-
=
,+=
,-=
,*=
,/=
,%=
-
num2 = num1
-
Assigns the value of variable num1 to the variable num2.
-
In programming "
=
" means "assign". -
It does not mean "it is equal" it means "make it equal".
-
Left Side -> Right Side
-
(make it equal to)
-
num2 += num1
equivalent tonum2 = num2 + num1
-
num2 -= num1
equivalent tonum2 = num2 - num1
-
num2 *= num1
equivalent tonum2 = num2 * num1
-
num2 /= num1
equivalent tonum2 = num2 / num1
-
num2 %= num1
equivalent tonum2 = num2 % num1
Operand
-
An item of data being operated on.
-
e.g. in the following expression:
6 + 7
, the operands are6
&7
.
3. Unary Operators
-
Operators which only work on one operand(a single input).
-
-
-
int a = 5; // a is 5
-
int b = -a; // b is -5
-
int c = -b; // c is +5
-
- doesn't necessarily make an operand have a negative value. Instead, it changes whatever sign the operand has to start with(e.g. --a = +a).
Literals
-
Fixed values.
-
e.g.
10
,"ABC"
Assign a value to a variable
-
In other words "tell the computer what to remember".
-
You assign a value to a variable either:
-
Or at the end of the declaration line:
-
data_type variable_name
=
literal value;
-
e.g.
int num = 10; // This is actually the safest way - see "Local Variables" later for details.
-
When a variable is assigned a value for the 1st time, the variable is said to be initialised.
Variable Declaration Variations
-
datatype variableName;
-
Declares a variable & data type, and reserves memory for it.
-
It says nothing about what value is put in memory.
-
datatype variableName = initialValue;
-
Declares a variable & data type, reserves memory for it, and puts an initial value into that memory.
-
datatype variableNameOne, variableNameTwo, ... ;
-
Declares multiple variables, all of the same data type, reserves memory for each, but puts nothing in any variable.
-
datatype variableNameOne = initialValueOne, variableNameTwo = initialValueTwo, ... ;
-
Declares multiple variables, all of the same data type, reserves memory for each, and puts an initial value in each variable.
Variable naming "rules" in Java
-
Try discovering these rules for yourself by making up and trying some variable names.
-
e.g.
int
... (varName) -
Then try to compile or execute.
-
If there are errors then the variable name is invalid, if not then the variable name is obviously valid.
Primitive data types in Java

-
The most basic data types available within the Java language.
-
Primitive = "a fundamental component that is used to create other, larger parts."
-
Can only store 1 basic value of a specific kind.
-
Cannot be broken down into simpler data types.
-
Fixed memory sizes.
-
Use little memory & fast to process.
-
Directly contains the value of its type.
-
If you visit its memory location you will find the value of the variable.
-
This may not be particularly surprising at the moment but it becomes important after you cover topic 10.
int
Division
-
Integer division occurs if there is an integer on both sides of
/
. -
The result of integer division is an integer.
-
Integer division determines how many times one integer goes into another.
-
The remainder after integer division is simply dropped/the decimal part is truncated(cut off).
-
Integer arithmetic can be used in some parts of an expression and not in others, even though the final value of the expression is double.
-
1.5 + 7/2
=
double
division
-
Double division occurs if there is an double number on at least 1 side of /
-
You can do this to "force" "correct" division.
-
However, if we have variables instead of literals(fixed values), how can we "force" "correct" double division then?
-
Answer: See below.
Conversion between primitive data types
-
Implicitly - possible for automatic "safe" conversions.
-
Explicitly - the programmer asks for values to be converted with a type cast(necessary for non-automatic "unsafe" conversions but also useful for "safe" conversions - see later).
Safe / Automatic / Widening Conversions
-
If the data types are compatible and JAVAC can make the conversion without loss of information, it will automatically do so.
int a = 123456789;
double x = a; // Is allowed. ✔
Unsafe / Non-automatic / Narrowing Conversions
-
If the data types are compatible and JAVAC cannot make the conversion without a loss of information then a type cast has to be made(basically meaning the programmer must specifically ask for the conversion).
-
e.g.
double
->int
double x = 11.0;
int a = x; // Is NOT allowed! ❌
/*
A type cast looks like this:
(requiredType) variable
Basically TypeCasting means:
"treat this variable as a (... data type) even
if it was declared as some other data type".
*/
int a = (int)x; // Is allowed. ✔
x = (double)a;
/* Type-casting is recommended even
for safe conversions, as it makes
it clear what is happening. */
boolean
-
Is incompatible for converting into any other primitive data type.
-
That is, a boolean value cannot be converted into any other data type like
int
,double
, etc....
double
division with variables
-
So to return to our earlier question:
-
Can we "force" double ("correct") division using safe conversions instead of type casting?
More Practice:
-
13/5
= -
How can we force double division above?
- or
- or
-
int x = 13, y = 5;
-
x/y
= -
How can we force double division above?
- or
- or
-
Will these compile? If so, what will happen?