chapter 3 data types, arithmetic and arrays

34
Chapter 3 Data Types, Arithmetic and Arrays Foundational Java Key Elements and Practical Programming 1 Foundational Java by David Parsons © 2012

Upload: others

Post on 09-Dec-2021

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 3 Data Types, Arithmetic and Arrays

Chapter 3 Data Types, Arithmetic and

Arrays

Foundational Java Key Elements and Practical Programming

1 Foundational Java by David Parsons © 2012

Page 2: Chapter 3 Data Types, Arithmetic and Arrays

Data Types

• Java has two groups of data types:

– Primitive

• integer, floating point, character, boolean

– Reference

• array, class, interface

2 Foundational Java by David Parsons © 2012

Page 3: Chapter 3 Data Types, Arithmetic and Arrays

Primitive Types

• All primitive type names are lower case

• Integers (all signed) – byte (8-bit) short (16-bit)

– int (32-bit) long (64-bit)

• Real Numbers (signed) – float (32 bit) double (64 bit)

• Other – boolean true & false only

– char 16-bit Unicode

3 Foundational Java by David Parsons © 2012

Page 4: Chapter 3 Data Types, Arithmetic and Arrays

Literals

• Literals

– ‘Immutable’ values

– Fixed when the program starts running

4

10 // an int

45.5 // a double

true // a boolean

'a' // a char

"string" // a String (not a primitive type)

Foundational Java by David Parsons © 2012

Page 5: Chapter 3 Data Types, Arithmetic and Arrays

Variables

• Variables

– We give variables names to create and use them

– Have a type

– Have storage allocated to at runtime

– Can contain changing values

5 Foundational Java by David Parsons © 2012

Page 6: Chapter 3 Data Types, Arithmetic and Arrays

Naming and Declaration

• Naming Conventions

– Variables use Camel (caMel) case

– start with a lower case letter, embedded words begin with upper case, no under_scores

• Variable declaration and assignment

– Local variables must be given an initial value when they are declared

6

int intValue = 3; // declare and assign intValue

intValue = 5; // reassign intValue

int anotherIntValue = intValue; // assign one variable to the value of another

Foundational Java by David Parsons © 2012

Page 7: Chapter 3 Data Types, Arithmetic and Arrays

Literal Number Types • A literal whole number is assumed by the compiler to

be an int

• This literal is too large to fit into an ‘int’ variable:

• Change the type of the variable from ‘int’ to ‘long’ • Add an ‘L’ to the end of the literal so the compiler will

treat it as a long data type rather than an int

• A similar situation occurs with floating point numbers – use a letter suffix to change the type of the literal

7

double d = 3.5; // double is default floating point

float f = 4.56F; // will compile - F or f = float

int myNumber = 9; // int is default integral

int myBigNumber = 2147483648; // won’t compile

long myBigNumber = 2147483648L; // will compile

Foundational Java by David Parsons © 2012

Page 8: Chapter 3 Data Types, Arithmetic and Arrays

Boolean Variables

• boolean variables are very simple

• They can only have the values ‘true’ or ‘false’ (must be in lower case)

• These values can be assigned as literals

• They can also be assigned the result of an expression that returns a boolean value

8

// assigning booleans

boolean isFull = true;

isFull = false;

Foundational Java by David Parsons © 2012

Page 9: Chapter 3 Data Types, Arithmetic and Arrays

Unicode Characters

• A char variable can hold a single 16 bit Unicode character

• Can be assigned to a literal in single quotes

• Can alternatively be assigned the Unicode value of the character (up to 65535)

9

// assign the literal character ‘c' to a char variable

char myChar = ‘c';

// assign the Unicode value of ‘c’ (99)

char myOtherChar = 99;

Foundational Java by David Parsons © 2012

Page 10: Chapter 3 Data Types, Arithmetic and Arrays

Escape Sequences • Represent special, often non-printable

characters

• May appear in any character or String literal

10

// assign the tab escape sequence character

char tab = '\t‘;

// embed quotes in a String literal

String quotation = "Java is C++ \"without the guns, clubs and knives\"";

Backspace \b horizontal tab \t

single quote \' double quote \"

new line \n carriage return \r

form feed \f backslash \\

octal Unicode

character value

\xxx hexadecimal Unicode

character value

\uxxxx

Foundational Java by David Parsons © 2012

Page 11: Chapter 3 Data Types, Arithmetic and Arrays

Scope • The scope of a variable is its code block, defined

within braces {…}

• Variables can’t be used in code until after declaration

• Declare as close to point of first use as possible

11

{

int myVariable = 3; // can use ‘myVariable’ now

} // ‘myVariable’ is now out of scope and can’t be used

int myVariable = 0;

{

myVariable = 3; // can use ‘myVariable’ now

} // ‘myVariable’ is still in scope and can be used

Foundational Java by David Parsons © 2012

Page 12: Chapter 3 Data Types, Arithmetic and Arrays

Exercise 3.1 • Use the example class provided in the exercise files • It contains a number of deliberate errors relating to

literals and scope • Fix these errors by applying your knowledge of the

various concepts that have been introduced so far in this chapter

• The method contains some braces that serve no useful function, they are simply there to enable you to demonstrate your understanding of scope

• In making your changes do not change any of the data types, change only the values or the way they are expressed

Foundational Java by David Parsons © 2012 12

Page 13: Chapter 3 Data Types, Arithmetic and Arrays

Arithmetic Operators • add + subtract - • multiply * divide / • remainder % • Variable on the left of an assignment (=) operator

equals the result of an arithmetic expression on the right:

• Expression is a combination of operators and operands (variables or literals)

13

variable = expression;

double netPay = grossPay – deductions;

double distanceInKm = distanceInMiles * 1.6093;

int perimeter= height * 2 + width * 2;

int numberoOfGroupsofFour = classSize / 4;

int studentsNotInGroupOfFour = classSize % 4; Foundational Java by David Parsons © 2012

Page 14: Chapter 3 Data Types, Arithmetic and Arrays

Order of Precedence

• Multiply, divide and modulus have precedence over addition and subtraction

• Use parentheses to change precedence

• operators of the same are evaluated from left to right

14

int result = (4 + 2) * 3; // result is 18

int result = 10 * 3 / 2; // result is 15

int result = 4 + 2 * 3; // result is 10

Foundational Java by David Parsons © 2012

Page 15: Chapter 3 Data Types, Arithmetic and Arrays

Remainder Operator

• The remainder operator returns the remainder from a division

• If the value if ‘classSize’ was 22, the result of the division would be 4, but the result for the remainder would be 2

• An integer remainder is usually known as a ‘modulus’, but since we can also use this operator with floating-point data types it is not strictly speaking a modulus operator

15

int numberOfGroupsofFour = classSize / 4;

int studentsNotInGroupOfFour = classSize % 4;

Foundational Java by David Parsons © 2012

Page 16: Chapter 3 Data Types, Arithmetic and Arrays

Increment and Decrement Operators

• Add 1 to, or take 1 away from, the value of the variable

• This is simply a shorthand for

• Similarly…

• Is a shorthand version of

16

counter = counter + 1;

counter = counter + 1;

counter++ // increments ‘counter’ by 1

counter-- // decrements ‘counter’ by 1

Foundational Java by David Parsons © 2012

Page 17: Chapter 3 Data Types, Arithmetic and Arrays

Prefix and Postfix Operators

• Postfix notation: counter++ or counter--

• Prefix notation: ++counter or --counter • Prefix and postfix notations have a different

order of precedence in expressions – Prefix

– Postfix

• Safer not to embed them in larger expressions

17

int counter = 1;

int currentCount = counter++; // currentCount = 1

int counter = 1;

int currentCount = ++counter; // currentCount = 2;

Foundational Java by David Parsons © 2012

Page 18: Chapter 3 Data Types, Arithmetic and Arrays

Shorthand Assignment Operators

• We also have shorthand for assignment operators with arithmetic

• In this syntax outline, ‘?’ means any one of the five arithmetic operators: – In general terms: var = var ? n

– can be replaced with: var ?= n

• For example…

18

myVariable = myVariable + 2; is equivalent to myVariable += 2;

myVariable = myVariable - 2; is equivalent to myVariable -= 2;

myVariable = myVariable * 2; is equivalent to myVariable *= 2;

myVariable = myVariable / 2; is equivalent to myVariable /= 2;

myVariable = myVariable % 2; is equivalent to myVariable %= 2;

Foundational Java by David Parsons © 2012

Page 19: Chapter 3 Data Types, Arithmetic and Arrays

Promotion

• Mixed Type Calculations (promotion)

• The narrower type operand is converted to the broader type automatically

int * long int becomes long

float * double float becomes double

int * double int becomes double

• Useful to know about, even though it is automatic

19 Foundational Java by David Parsons © 2012

Page 20: Chapter 3 Data Types, Arithmetic and Arrays

Type Casting

• Explicit Conversion (casting)

• Where conversion is otherwise not allowed or not automatic

• e.g. a double value that we want to convert to a float

• Useful technique for objects as well as primitives

20

float floatValue = (float)doubleValue;

(type we want) value we’ve got

Foundational Java by David Parsons © 2012

Page 21: Chapter 3 Data Types, Arithmetic and Arrays

String Concatenation

• Strings can be concatenated with values of other types using the ‘+’ operator

– Primitives or objects

– Primitives are automatically converted to Strings

• You can also use the ‘+=’ operator

21

int myVariable = 99;

System.out.println("The value of myVariable is " + myVariable);

// prints "The value of myVariable is 99”

String greeting = ″Hello ″

String message = greeting += ″Mr. President″;

System.out.println(greeting);

Foundational Java by David Parsons © 2012

Page 22: Chapter 3 Data Types, Arithmetic and Arrays

Concatenation v. Addition

• String concatenation uses the ‘+’ operator in a different way to how it is used in arithmetic

• It only concatenates when at least one String is in an expression.

• e.g. ‘+’ operator with char data types:

• Contrast with first character as a String (double quotes)

22

System.out.println(″a″ + ′b′ + ′c′); // prints abc

System.out.println(′a′ + ′b′ + ′c′); // prints 294 (97 + 98 + 99)

Foundational Java by David Parsons © 2012

Page 23: Chapter 3 Data Types, Arithmetic and Arrays

Exercise 3.2

• Create a class with a main method

• In the main method, calculate the fuel consumption of a car that just cost §72 to fill up at §1.80 a litre after going 390 km since it was last filled with fuel

• Display the number of kilometres travelled per litre

23 Foundational Java by David Parsons © 2012

Page 24: Chapter 3 Data Types, Arithmetic and Arrays

Arrays

• An array is a indexed collection

– It can contain primitive types or objects

• Type and size is specified when the array is declared

• Bounds-checked

– An exception occurs at runtime if index is invalid

• Efficient storage but cannot be dynamically resized

24 Foundational Java by David Parsons © 2012

Page 25: Chapter 3 Data Types, Arithmetic and Arrays

Declaring Arrays • An array reference is declared by putting empty square

brackets after the name of the data type • e.g. declare a reference to an array to store values of

type int • Arrays are reference types not primitives • Declaring the reference does not create the array • Arrays are created by using the keyword ‘new’,

followed by the data type and size of the array in square brackets

• e.g. create an array that can hold three int values:

25

;

int[] myArray;

myArray = new int[3];

Foundational Java by David Parsons © 2012

Page 26: Chapter 3 Data Types, Arithmetic and Arrays

Declaring an Array • Can declare the reference and create the array together

• Array indexes start at zero • This array has three elements:

– myArray[0] – myArray[1] – myArray[2]

• no myArray[3]!

• Values in an array will have a default value – Each int value in ‘myArray’ will be initialised to zero

26

int[] myArray = new int[3];

0 1 2 3

int[]myArray = new int[3];

// creates an array of type int with 3elements

// array contains {0,0,0} Foundational Java by David Parsons © 2012

Page 27: Chapter 3 Data Types, Arithmetic and Arrays

Assigning Values

• We can assign values to the array elements using index numbers in brackets

• For example this array will contain integer values representing the average monthly rainfall in millimetres in Auckland, New Zealand from January to December:

27

int[] monthlyRainfall = new int[12];

monthlyRainfall[0] = 74;

monthlyRainfall[1] = 81;

monthlyRainfall[2] = 86;

//etc…

Foundational Java by David Parsons © 2012

Page 28: Chapter 3 Data Types, Arithmetic and Arrays

Initializer Blocks • Assigning values individually can be tedious • Alternative is to use an initializer block

– Assign a new array reference to a number of comma-separated values surrounded by braces

• e.g. example this array is initialized with twelve integer values representing the average monthly rainfall in millimetres in Auckland, new Zealand from January to December:

• Array size based on number of values provided – 12 in this example

• An initializer can only be used with a newly declared array reference

28

int[] monthlyRainfall = {74,81,86,93,100,116,126,111,93,80,84,91};

Foundational Java by David Parsons © 2012

Page 29: Chapter 3 Data Types, Arithmetic and Arrays

Accessing Array Data

• The data in an array element can be updated or retrieved using the index number – Update the last element of the rainfall array

– retrieve a value from an element

– include an element in output

• • Using an index number which is out of range will

lead to a run time exception

29

monthlyRainfall[11] = 92;

int augustRainfall = monthlylRainfall[7];

System.out.println(″March rainfall was ″ + monthlyRainfall[2]);

monthlyRainfall[12] = 92; // exception at run time

Foundational Java by David Parsons © 2012

Page 30: Chapter 3 Data Types, Arithmetic and Arrays

Arrays are Typed • Arrays can only store values of the type specified by

the reference

• Types are checked at compile time

• e.g. cannot assign a double to an element of int array

30

monthlyRainfall[0] = 74.3; // compiler error!

can’t assign a double to an int

Foundational Java by David Parsons © 2012

Page 31: Chapter 3 Data Types, Arithmetic and Arrays

The length Field • Arrays have a public length field

• Useful to know to help avoid going beyond the bounds of the array

• Can be used to control a loop

31

System.out.println(monthlyRainfall.length); // '12' printed in console

Foundational Java by David Parsons © 2012

Page 32: Chapter 3 Data Types, Arithmetic and Arrays

Multidimensional Arrays • Java also supports multidimensional arrays,

declared using multiple pairs of brackets

• This code relates to a two dimensional array that contains two names for each month in the year (short and long versions)

32

String[][] monthNames = new String[12][2];

monthNames[0][0] = "Jan";

monthNames[0][1] = "January";

monthNames[1][0] = "Feb";

monthNames[11][1] = "December";

Foundational Java by David Parsons © 2012

Page 33: Chapter 3 Data Types, Arithmetic and Arrays

Exercise 3.3 • This exercise converts distances expressed in Kilometers to

their equivalents in miles and nautical miles – One kilometer equals .62 miles and .54 nautical miles.

• Create a new class with a ‘main’ method • In ‘main’ create and initialize an array of type ‘double’

containing the values .62 and .54 (representing the conversion multipliers.)

• Create and initialize an array of type ‘int’ containing the values 2, 5 and 10 (representing distances in kilometers)

• For each element in the integer array, calculate and display the equivalent distances in miles and nautical miles – Use String concatenation to add text labels to make the output

understandable

33 Foundational Java by David Parsons © 2012

Page 34: Chapter 3 Data Types, Arithmetic and Arrays

Exercise • Create a new class with a ‘main’ method • Create and initialise an array of type ‘double’

containing the values .62 and .54 (representing the conversion multipliers from Kms to miles and nautical miles)

• Create and initialise an array of type ‘int’ containing the values 2, 5 and 10 (representing distances in kilometers)

• For each element in the integer array, calculate and display the equivalent distances in miles and nautical miles. Use String concatenation to add text labels to make the output understandable.

34 Foundational Java by David Parsons © 2012