05. Loops & Arrays

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 1014 18 22 26

Contents 34 8 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值