05. Loops & Arrays

来源:互联网 发布:身份证阅读器软件下载 编辑:程序博客网 时间:2024/06/05 21:47

Switch Statements

Switch (on char, byte, short, int, String, enum)

Most common mistake is leaving out the "break" statement. If you do, control continues into the next case.

Default is optional.


While Loops

While loop tests at the top which means statements in the block may never be executed

do/while loop executes the block at least once


Silent Integer Overflow

Range for int: -2,147,438,648 to 2,147,438,647


For loops

for (initialization; condition; increment/decrement)  stmt;

Use a break statement to get out of a loop


Which loop to use

For loop: when the exact number of iterations is known

While loop: when you want to use a sentinel value to terminate

do/while loop: when you want the block executed at least once


Arrays in Memory

- Typically, array elements are stored in adjacent memory cells

- The subscript (or index) is used to calculate an offset to find the desired element

E.g. integer 4 bytes

Address 101418 22 26

Contents 348 1 2

// variable (data) has the starting address (10)

int[] data = {3, 4, 8, 1, 2};

data[3];

What happens behind the scenes is:

10 + 3*4 = 22

- Arithmetric calculation does not depend on the size of data type in an array

That's why subscript (index) numbering starts at 0


Watch out for Off-by-One Errors

- One of the very common mistakes

- Array subscripts (index) start at 0

- But, the number of elements or length starts at 1


Java Enhanced for loop

Simply want to iterate over each element in an array

for (vardecl : array)  stmt;


Sample Final Exam Questions

What are main characteristics of arrays in Java?

- Ability to declare a bunch of the same thing (data type) or declare and initialize with an initialization list

- Array has a field, length, and can be accessed by .length

- Access the array with square brackets and subscript numbering (index)

- Array's subscript numbering (index) starts at zero

- Typically, array elements are stored in adjacent memory cells

- The subscript (index) is used to calculate an offset to find the desired element

- Arithmetic calculation does not depend on the size of data types in an array

- Once it is created, its length cannot be changed

- Array index bounds are checked on every access

0 0