CS 1054 Lecture 9 Grouping Objects contd Fixedsize
CS 1054: Lecture 9 Grouping Objects (contd. . )
Fixed-size collections n n Sometimes the maximum collection size can be pre-determined. Programming languages usually offer a special fixed-size collection type: an array. Java arrays can store objects or primitive-type values. Arrays use a special syntax.
Declaring and Creating array variables Consider a scenario where you need to create an array of 24 integers. Step 1: Declare an array of size 24 Step 2: Create an array of size 24
Actual Code public class some. Class { private int[] hour. Counts; public some. Class() { hour. Counts = new int[24]; }. . . }
The hour. Counts array
Using an array n n Square-bracket notation is used to access an array element: hour. Counts[. . . ] Elements are used like ordinary variables. n On the left of an assignment: n n hour. Counts[hour] =. . . ; In an expression: n n adjusted = hour. Counts[hour] – 3; hour. Counts[hour]++;
The for loop n n n Similar to a while loop. Often used to iterate a fixed number of times. Often used to iterate over an array.
A Java example for loop version for(int hour = 0; hour < hour. Counts. length; hour++) { System. out. println(hour + ": " + hour. Counts[hour]); } while loop version int hour = 0; while(hour < hour. Counts. length) { System. out. println(hour + ": " + hour. Counts[hour]); hour++; }
For loop pseudo-code General form of a for loop for(initialization; condition; post-body action) { statements to be repeated } Equivalent in while-loop form initialization; while(condition) { statements to be repeated post-body action }
A bit about Java n Developed at Sun Microsystems in 1991 n n n James Gosling, Patrick Naughton Architecture – neutral language that could be used to create software to be embedded in various electronic devices What does architecturally-neutral mean?
Java’s Magic: The Bytecode n n Bytecode is a highly optimized set of instructions designed to be executed by Java run-time system. JVM – interpreter for bytecode
Some OOP principles Abstraction ð Encapsulation ð Polymorphism n Inheritance ð
- Slides: 13