comp-202: foundations of programmingcs202/2015-05/web/lectures/...comp-202: foundations of...
TRANSCRIPT
-
COMP-202: Foundations of Programming
Lecture 5: Arrays, Reference Type, and Methods
Sandeep Manjanna, Summer 2015
-
Announcements
• Assignment 2 posted and due on 30th of May
(23:30).
• Extra class tomorrow - 13:05 to 15:25 in TR0100.
• Midterm Exams : June 4th (12:35 – 14:35)
Rooms : 1B45 and 306 (Burnside)
• Final Exams : June 26th (14:00 – 17:00)
Room : MAAS 112
-
Review• Loops
1. In a group of nested loops, which loop is executed the most
number of times?
A. The outermost loop
B. The innermost loop
C. All loops are executed same number of times
2. What value is stored in x at the end of this loop?
for (x = 1; x
-
Review• While Loops
int x = 0;
while (x < 4)
{
System.out.println("Write this again");
x++;
}
Step
1
Step
2
Step
3
Initialize
Condition Check
Loop body
Execution
Once the
condition fails
Condition
Fail
-
Review• For Loops
for (int x = 0; x < 4; x++)
{
System.out.println("Write this again");
}
Step
1
Step
2
Initialize
Condition Check
Loop body
Execution
Once the
condition fails
Condition
Fail
Step
4 Update
Step
3
-
• Array of Scores of 8 students:int [ ] scores = {100, 95, 25, 99, 39, 100, 100, 90}
• Here is an array with 8 values in it.
• Each spot of the array has a value and an index.
• The value is any legitimate value of the type of the array, in this case int.
• The index is an integer. Interestingly the counting starts from 0 instead of 1.
• To get or set values of an array, we will use a similar syntax to a normal variable, except we have to specify which value of the array we wish to get or set. We do this by using the index.
100 95 25 99 39 100 100 90
[0] [1] [2] [3] [4] [5] [6] [7]
scores
Indices
Review
-
Creating Array (Method 1)
int[] myArray = {1, 5, 6, 3};
1) Allocate this memory. Find a free spot in memory that has
enough space to hold four integers.
2) Store the address of the beginning of the memory that was just
allocated into the variable myArray.
3) Set values to this newly allocated memory.
1 5 6 3
myArray
myArray
Review
-
Creating Array (Method 2)
This method is useful when we don’t know the values that
needs to be saved in the array:
int[] myArray;
myArray = new int[4];
myArray[0] = 1;
……1
Variable “myArray” is created
to point to an array.
myArray
myArray
[0] [1] [2] [3]
Indices
Review
-
This Lecture
� Reference Types
� Reference vs Primitive Types
� Multidimensional Arrays
� Methods
One step at a time….
-
Adding to our vocabulary -“break”
• ‘break’ is used to stop the execution of a loop before all the iterations are completed.
• Example:int i;
for(i=0; i
-
Objects
• Arrays, Scanners, and Strings are Objects.• You can tell because you need new to create them.
(Well, except Strings. Strings are special.)
• In fact, except for the primitive data types (the ones that start with lowercase, like int, double, float, byte, boolean, etc.), everything in Java is an Object.
• Objects are data bundled with methods to work with the data, and properties.
-
Methods and Properties of Objects
• Some String methods:• .equals(), .length(), .toLowerCase()
• Some Scanner methods:• .nextLine(), .nextInt(), .nextDouble()
• In general: object.method_name()
• Arrays have no methods. Instead, they have a property called length
• .length
• Because this is not a method, there is no () after
-
Reference Types
-
Reference Types vs Primitive Types
When we write
int x = 10;
what we are technically doing is the following:
1) Creating a space in memory that will store an int
2) Specifying that whenever we use the identifier x later in our program, we want to access that memory location.
3) Storing the value of 10 into that memory location.
10
x
-
Objects Using Reference Types
• The variables of objects, including arrays, don't directly store the values of the objects.
• Instead, they store a reference to the location in memory containing the value.
• Think of this as storing an address, which points to where the data is actually located in memory.
-
Reference Types vs Primitive Types
When we write
int x[] = {10, 3, 5};
what we are technically doing is the following:
1) Creating a space in memory that will store the address of an int array.
2) Specifying that whenever we use the identifier x later in our program, we want to access that space in memory (which stores an address).
3) Creating an array somewhere else in memory. That array will store the values 10, 3, and 5 and have length of 3. That array must be located somewhere in memory. Call that address ‘a’.
4) Setting the value of x to be ‘a’ (In other words, the value of a is stored into the space of memory reserved for the variable x).
-
Why references can get Confusing?
• There are some interesting consequences of storing addresses into variables instead of the values.
1. 2.int[] x = {1, 2, 3}; int x = 5;
int[] y = x; int y = x;
y[0] = 2; y = 10;
System.out.println(x[0]); System.out.println(x);
• What will the above print?
1. 2 ! Because changing y[0] also changes x[0]. x and y are
reference types.
2. 5 Because x and y are primitive types in here.
-
One Step at a time…
Memory
0 4 …. 1000 1004 1008 …. 2004 …. 2112
Addresses
Values
int[] x = {1,2,3}
1 2 3
The {1, 2, 3} creates an array in memory. The address of the start
of this spot in memory is 1000.
-
One Step at a time…
Memory
0 4 …. 1000 1004 1008 …. 2004 …. 2112
Addresses
Values
int[] x = {1,2,3}
1 2 3
int[] x creates a variable of type int array. This means we create
space in memory to store the address of an int array. In this case,
we use the storage space in memory of 2004, to store the address
1000.
x
1000
-
One Step at a time…
Memory
0 4 …. 1000 1004 1008 …. 2004 …. 2112
1000
Addresses
Valuesint[] x = {1,2,3}
1 2 3
int[] y = x;
This means:
1) Create space in memory to store an int[] variable
2) Store into that int[] variable the value of the expression “x”
yx
1000
-
One Step at a time…
Memory
0 4 …. 1000 1004 1008 …. 2004 …. 2112
1000 1000
Addresses
Values
1 2 3
int[] x = {1,2,3}
int[] y = x;
y[0] = 2;
This means:
1) Assign to the first value of the array referred to by y, the value
of the expression “2”
yx
2
-
Can also be seen as…
int[] x = {1,2,3}
int[] y = x;
y[0] = 2;
y
x
1 2 32
-
Consequences: Equality
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
System.out.println(arr1 == arr2);
Here the addresses stored in arr1 and arr2 variables are getting compared. Not the values.
This is also why we have to use .equals() to compare the values of Strings.
-
Why would one EVER make things so complicated?
It turns out there are some very good reasons that will be
crucial to the idea of object oriented programming.
One useful feature is the ability to pass addresses of data
means it's easier to share (and modify!) data between
methods!
We will see an example about how this helps once we
learn about methods.
Why so Confusing!!?
-
Try it out!!
• Write some code that actually copies an array of ints (i.e., not just make it point to the same part of memory).
e.g.,int[] arr1 = {1, 4, 3, 6, 7};
int[] arr2;
// make arr2 have a copy of the data in arr1
-
Common Array Problems 1
• Referring to an index that doesn't exist.ArrayIndexOutOfBounds exception
int[] x = {1, 2, 3};
System.out.println(x[-1]);
System.out.println(x[3]);
-
Common Array Problems 2
• Trying to do operations on a null pointer.
NullPointerException
String[] names = new String[35]; System.out.println(names[0].length());
-
Multidimensional Arrays
• So far, the elements of all the arrays we have seen have been simple values: primitive types or Strings.
Such arrays are one-dimensional
• However, we can create arrays whose elements are themselves one-dimensional arrays
Such an array is really an array of arrays
• These arrays are two-dimensional arrays (or 2D arrays)
-
Two Dimensional Arrays
• Elements in a two dimensional array are accessed using two indices.
• The first index specifies the one-dimensional array containing the element we want to access.
• The second index specifies the element we want to access within the one-dimensional array specified by the first index.
Two Dimensional Arrays
-
Creating 2D Arrays
To create an array using an initializer list, you could write:
type[] variableName = {exp1, exp2, exp3, ...}, where exp1, exp2, exp3, etc all evaluated to type
• Well, in this case type is just an array. But we need array of arrays,
int[][] board = { {1,2,3}, {1,4}, {6,2} }
This is creating an array of int[] . The first array in the array is {1,2,3} the second is {1,4} and the third is {6,2}
-
Creating a 2D Array
int[][] board = { {1,2,3}, {1,4}, {6,2} }
We can use new operator to create multidimensional arrays.
Example:
type[][] variableName= new type[size_1][size_2];
1 2 3
1 4
6 2
board[0]
board[1]
board[2]
board
-
Accessing a 2D Array
int[][] x = new int[3][4];
//creates an array which contains 3 arrays of size 4.
x[0][1] = 3;
//assigns to the 2nd spot of the 1st array, the value 3;
x[2][3] = 10;
//assigns to the 4th spot of the 3rd array, the value of 10;
x[10][2] = 5;
//causes an array out of bounds exception
int[] y = x[2];
//stores into y the address of the 3rd array
-
What would be printed???
int [][] x = {{1,2,3},{4,5,2,7},{9,3,5,2,6}};
System.out.println(x.length);
System.out.println(x[2].length);
System.out.println(x[0]);
System.out.println(x[0][1]);
Two Dimensional Arrays
-
String(More about Strings)
-
String vs char[]
• A String is just a fancy version of char[] –both store an array of char values.
• A String has in addition:• Useful methods like .equals(), .toLowerCase()
• A special way to be created, using "" syntax
• (So we don't have to go {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd'} as for a char[].)
-
More String Methods
.charAt(int i) Gets the ith char of a String (starting from 0)
.substring(int a, int b) Gets the substring starting at position a ending just before position b.
.compareTo(String other) Tells you which String comes first, orthographically.
.indexOf(char c) Gets the index of the first occurrence of c
.toLowerCase() Gets a lower-case version of the String.
.toUpperCase() Gets an upper-case version of the String
-
A Note on Describing Methods
• When you see something like:.substring(int a, int b)
• This means this is a method that:1. takes two inputs (or arguments, parameters).
2. the first is of type int
3. the second is of type int as well
• You call the method by:"some string".substring(1, 4)
• The "int"s are just there as reminders. Don't type them in!
-
Try it out!!
• Write some code that turns a String into a format that is like a name—i.e., the first letter is capitalized, and all subsequent ones are not.
"bob" � "Bob"
"BOB" � "Bob"
"BoB" � "Bob"
"bOb" � "Bob"
• Hint: use the methods Character.isLowerCase(char ch) and/or Character.isUpperCase(char ch) to check the case of a char.
-
Caesar Cipher
• Used in the ancient Roman army to obscure important messages
ATTACKATMIDNIGHT*
DWWDFNDWPLGQLJKW
• Encrypt by shifting all letters by three positions
A (1st letter) � D (4th letter)
T (20th letter) � W (23rd letter)
*Ancient Romans didn't use lowercase letters, or spaces
-
• Implement the encryption algorithm for a Caesar cipher
• Steps:
• Read each character of plaintext (String.charAt(int i))
• Convert it to its numerical value (by casting)
• Add 3
• Tricky: implement wrap-around (e.g., Z � C)
• Convert it back to a char, and save it or print it out
Try it out!!
-
String[] args
• So what exactly is args there for?
public static void main(String[] args)
• Another way to pass input data to a program
Command line: java NameOfClass arg1 arg2 … argN
DrJava: run NameOfClass arg1 arg2 … argN
• Examples of uses:
• Name of file to open when you run the program
-
Command-line Calculator
• This program takes three arguments. The first represents an int , the second is a single character, in {'+', '-', '*', or '/'}, and the third is another int. It prints the result of computing the calculation.
e.g., run Calc 3 + 4 � 7
run Calc 88 / 5 � 17
run Calc 2 * -111� -222
-
Methods
-
Calling Methods
• You have been calling a lot of methods already
• Some examples?String.equals()
String.length()
-
Using Java Libraries
• The JDK comes with many libraries, which contain classes and methods for you to use.
• String library
• Math library
• Swing library (used for graphics)
• Libraries for networking
-
Math Library
• Contains useful and common methods you can use off-the-shelf (i.e., don't have to write yourself)
• Also, constants like E or PI
• How do you access them?
import java.lang.math;
-
Documentation
• Read the Application Programming Interface(API) for the specification of a library.
• e.g., Math library: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
• What information do you get from an API?
-
Sample Entry
static double abs(double a)
Returns the absolute value of
a double value.
Name of the method
-
Sample Entry
static double abs(double a)
Returns the absolute value of
a double value.
The number and type
of input arguments
The name of the method together with the
number and type of input arguments is called the
signature of the method.
-
static double abs(double a)
Returns the absolute value of
a double value.
Description of what the
method does.
Sample Entry
-
Sample Entry
static double abs(double a)
Returns the absolute value of
a double value.
The return type of the method
-
static double abs(double a)
Returns the absolute value of
a double value.
This keyword means this method does
not have to be called on a particular
object. Don't worry too much about it
for now.
Sample Entry
-
static double abs(double a)
Returns the absolute value of
a double value.
Based on this API entry, we know that we call
use this method with something like:
Math.abs(-4.0)
and that this expression evaluates into the value
4.0 with type double.
Sample Entry
-
static double abs(double a)
Returns the absolute value of
a double value.
We also know that
Math.abs("5.0")
would result in an error.
Sample Entry
-
Try it out!!
• Give the input arguments (with types), and return types of the following Math library methods, and describe what they do.
Math.pow
Math.random
Math.max
-
Summary
� Reference Types
� Multidimensional Arrays
� Introduction to Methods