Critical Thinking The Key to Learning and Communication

advertisement
MSI 692: Special Topics
in Information Technology
Lecture 4: Strings & Arrays
Sanjay Goel
University at Albany, SUNY
Fall 2004
Sanjay Goel, School of Business, University at Albany, SUNY
1
Outline for the Class
Arrays
• Recap
• Strings
• Arrays
–
–
–
–
Creation and Access
Copying & assigning arrays
Storage & Indexing
Multidimensional Array
• Examples
Sanjay Goel, School of Business, University at Albany, SUNY
2
Recap
Sanjay Goel, School of Business, University at Albany, SUNY
3
Recap
Structured Programming and Methods
• What is the basic premise of Structured Programming?
– Top Down Refinement - You break the problem down into smaller and
smaller pieces until you have well defined isolated pieces of code that can
be easily coded.
• Methods are used for isolating functionality into manageable
units. These methods combined together are able to emulate the
logic. Methods can be defined by the user or can be provided by
the system.
• Methods:
– Method Name – Identifier for the method
– Method Signature –
– Method Body – Block which contains logic for the method
– Main method – Program execution begins in main
Sanjay Goel, School of Business, University at Albany, SUNY
4
Recap
Visibility Usage-Modifiers
• Visibility Usage-Modifiers Return-Type Identifier
(ParameterList) block
• Visibility
– Public: visible everywhere (as long as the class is public)
– (blank): visible in the package (default)
– Protected: like default (visible in subclasses in other packages)
– Private: visible in this class only
• In main() method you can not leave visibility blank
Sanjay Goel, School of Business, University at Albany, SUNY
5
Recap
Usage-Modifiers
• Final
– Cannot be overridden
• Static
– one per class (not each object instance)
– Attached to class not object
• Abstract
– must be overridden
• Native
– not written in Java. The body will be written in another
language
• Synchronized
– only one thread may execute in the method at a time.
Sanjay Goel, School of Business, University at Albany, SUNY
6
Recap
Definitions
• Return Type
– Type of value returned by the function
– e.g. int, double, float.
– If nothing is returned void is used.
•
Identifier
– Name of the method
• Parameter List
– Defines the number and types of each argument to the program.
• Block also called the method body which contains the logic of
the program. Three main components
– Variable initializations
– Statements (Logic, Loops, method calls etc.)
– Return Statement
Sanjay Goel, School of Business, University at Albany, SUNY
7
Recap
Return Statement
• Return statement transfers the control to the next
statement in the calling program.
• Syntax: return value;
• The value has to match the type that is specified in the
signature
• There should be no value if the return type defined is
void.
• If there is no return statement the control is passed
back to the calling program when the final closing brace
of the method is encountered during sequential
execution.
Sanjay Goel, School of Business, University at Albany, SUNY
8
Recap
Variables
• Scope of a Variable
– is the range of statements that can access the variable
•
Variables defined inside the class
– are accessible to all the methods
•
Variables defined inside the method and outside any block
– are accessible every where in the method.
•
In nested blocks
– the inner blocks can see the variables defined in the outer block.
• Analogy
– We have talked about decomposing and compartmentalizing our code.
Consider each of these boxes to be glass boxes which are see through on
the inside and not the outside. People inside can see outside but people
outside can not see inside.
Sanjay Goel, School of Business, University at Albany, SUNY
9
Recap
Method invocation and call by value
• Method Invocation and Call by Value:
– To call a method we write the name and provide appropriate
arguments to the method. The arguments have to match in
number and type.
• Primitives in Java are passed as call-by-value
– Which means that each argument is evaluated and its value is
passed to the method where the formal parameters are
initialized. Also if the value of the arguments changes in the
called function it does not impact the variable values in the
main function.
Sanjay Goel, School of Business, University at Albany, SUNY
10
Functional Abstraction
Call-by-reference
• Objects in Java are passed by call-by-reference
– This means that the if the value of the object is changed it reflects in the
calling function.
– Give the Swap example 
public static void main(String[] args) {
int a = 1;
int b = 2;
System.out.println(“a = “ + a);
System.out.println(“a = “ + a);
swap(a, b);
System.out.println(“a = “ + a);
System.out.println(“a = “ + a);
}
public void swap(int x, int y) {
int tmp = y;
y = x;
x = tmp;
return;}
• The return value from the function can be stored in a variable of
the correct type or used directly in an expression.
Sanjay Goel, School of Business, University at Albany, SUNY
11
Functional Abstraction
Recursion
• A method is called recursive if it calls itself either directly or
indirectly.
• For recursion to work we need to have a terminating condition
else it will continue indefinitely, e.g.
int factorial(int n) {
if (n <= 1)
return 1;
else
return (n * factorial(n-1));
}
Sanjay Goel, School of Business, University at Albany, SUNY
12
Functional Abstraction
Method Overloading
• Method Overloading means that multiple methods can be
defined with the same name as long as they have different
arguments.
• The compiler uses signature matching to determine which
method to call, e.g.
– min(int a, int b)
– min(double a, double b)
• In case a call is made to min with one integer and one double
value the compiler would use widening primitive conversion i.e.
convert int to double and then call the double method
• Note: Widening conversion is conversion from one type to
another that is guaranteed to maintain the sign and the most
significant digits of the value being converted.
• Ambiguous conversions will lead to compile time errors.
Sanjay Goel, School of Business, University at Albany, SUNY
13
Functional Abstraction
Errors
• Ambiguous conversions will lead to compile time errors.
• Functions, i.e
– min (int, float)
– min (float int)
• Call: min (int, int)
• Either of the two can be used hence error
• If two matches are found the most specific will be used, e.g.
– Functions min(float, float)
– min(double, double)
– Call: min(int, int)
– Min(float, float) is used since it is more specific than double
Sanjay Goel, School of Business, University at Albany, SUNY
14
Strings
Sanjay Goel, School of Business, University at Albany, SUNY
15
Objects and Classes
Standard Classes: String
•
•
•
String class represents character strings
All string literals in Java programs are implemented as
instances of this class, e.g. “abc”
String class includes methods for
–
–
–
–
–
Examining individual characters of the sequence
Comparing strings
Searching strings
Extracting substrings
Creating a copy of a string with upper or lower case
translation.
Sanjay Goel, School of Business, University at Albany, SUNY
16
Objects and Classes
String Methods
• String class has following methods
–
–
–
–
–
–
–
–
–
–
–
boolean equals(Object anObject) Compares this string with another
int length() Gets length of string
char charAt(int index) Returns char at index pos. in string
int compareTo(String str) Returns an integer based on lexigographic order
int indexOf(in ch) Gets position of character in string (-1 if not present)
int indexOf(String str) Gets position of first letter of str in the string
String concat(String str) Concatenates two strings and returns
String toLowerCase() Converts to lower case
String toUpperCase() Converts to upper case
char[] toCharArray() Returns character array
static String valueof(type prim) Converts primitive to string.
Sanjay Goel, School of Business, University at Albany, SUNY
17
Objects and Classes
Standard Classes: Palindrome
static boolean isPalindrome(String s) {
int left = 0;
int right = s.length() – 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right))
return false;
left++;
right--;
}
return true;
}
Sanjay Goel, School of Business, University at Albany, SUNY
18
Creating Classes
The equals Method
• Definition
– Returns true if the strings are the same and false if they differ.
– As soon as a character in one string is not equal to the corresponding
character in the second string, the comparison is terminated and the
condition returns to false.
• Syntax
• Example
– (strName.equals(strInput))
(strName.equals(“Bill”))
Sanjay Goel, School of Business, University at Albany, SUNY
19
Creating Classes
The equalsIgnoreCase Method
• Definition
– Is similar to the equals method but does not differentiate between
uppercase and lowercase.
• Syntax
• Example
– String strName = new String(“Joan”) ;
String strName2 = new String(“JOAN”) ;
Sanjay Goel, School of Business, University at Albany, SUNY
20
Creating Classes
The compareTo Method
• Definition
– Used to determine less than or greater than.
– Returns an integer with one of three possible values.
• Syntax
• Example
– String strWord = new String(“Hope”) ;
String strWord2 = new String(“Hopeless”) ;
//Compare the strings
if (strWord.compareTo(strWord2 < 0)
//Display a message - - What will it be?
Sanjay Goel, School of Business, University at Albany, SUNY
21
Arrays
Sanjay Goel, School of Business, University at Albany, SUNY
22
Arrays
Introduction
• When do we need arrays?
– When we have large data sets of the same type
– e.g. test scores of the students or prime numbers between 0 and 100.
– It is cumbersome to define a separate variable for each value.
– Allows you to define one single variable and just put multiple values in
• An array in Java is a container that holds a related group of values
of the same type.
– The elements in an array are ordered are numbered 0 through n-1
– where n is the number of individual elements in the array.
•
The position of an element in an array is called index of the
array
Sanjay Goel, School of Business, University at Albany, SUNY
23
Arrays
Storage in Memory
• Before we even start let us understand how memory is
organized and how data is stored in memory.
– Each location in memory has a unique address.
• Data:
0
1
2
3
4
5
Sanjay Goel, School of Business, University at Albany, SUNY
24
Arrays
Memory Pointers
• This means that the memory location where the array
points does not contain array data rather it contains a
reference or a pointer to the actual array data.
– When you declare an array you just create a pointer which
points to nothing.
– To find the address in memory of a specific element, the
computer can add the element’s index to the address of the
location of the first element.
Sanjay Goel, School of Business, University at Albany, SUNY
25
Arrays
Array Declaration and Memory Allocation
• This is a two step process:
• Array Declaration
– You declare array variables just like any other variable by specifying the
type followed by the name of the variable.
– variableType [] variableName;
– int [] myArray;
• Memory Allocation
– To actually create an array you have to use new.
• arrayName = new arrayType[length]
– length is an integer expression
– e.g. myArray = new int[10]
Sanjay Goel, School of Business, University at Albany, SUNY
26
Arrays
Array Length
• You can do both things in a single step
– arrayType arrayName = new arrayType[length]
– Once an array is created it has a fixed size.
– An array can be reassigned to point to a different array that
has a different size
Sanjay Goel, School of Business, University at Albany, SUNY
27
Arrays
Array Indexing
• Array Indexing
– Once you declare an array. Each element can be accessed by
using an index variable of integer type. The indexing is from 0
to n-1 for an array of length n.
– arrayName[expr]
• This expression is any integer expression
– ith element of the array is represented as arrayName[i-1]
Sanjay Goel, School of Business, University at Albany, SUNY
28
Arrays
Assigning Arrays
int [] a = new int[10];
a = new int[20];
or
int [] a1 = {10, 20, 30}
int [] a2 = {1, 2, 3, 4, 5}
a1 = a2; // Now both a1 and a2 are pointing to same variable
Sanjay Goel, School of Business, University at Albany, SUNY
29
Arrays
Length of an Array
• The length of the array is stored in a variable called
length and can be accessed as:
arrayName.length
e.g. a.length;
for (int i = 0; i < a.length. i++) {
}
• If you index past the end of the array you get an
IndexOutOfBoundsException error.
Sanjay Goel, School of Business, University at Albany, SUNY
30
Arrays
Passing arrays to methods
•
Java passes parameters by value.
•
Arrays are reference types i.e. they store the address of the array
location
•
So when we pass arrays as arguments a copy of the reference
value (address) is passed to the method.
•
Two Scenarios
1.
The contents of the array are modified
a.
The main program sees the changes to the array
 show using stack
2.
The array is assigned to another array in the method
a.
No change happens in the calling method
 show using stack
Sanjay Goel, School of Business, University at Albany, SUNY
31
Arrays
Copying Arrays
• You need to copy arrays element by element rather than just assigning one
array to another. By just assigning one array name to another you are just
copying pointers without copying the array.
• If you want to create a new array from an old array you need to create a new
array and assign all the values from the old array to the new array, e.g.
static int[] duplicate(int[] a) {
int[] theCopy = new int[a.length];
for(int I = 0; I < a.length; I++) {
theCopy[I] = a[I];
}
return theCopy;
}
a1 = duplicate(a2)
• Cloning: For one-dim arrays java provides a cloning mechanism
– i.e. a1 = (int[])a2.clone(); // built-in array copy
Sanjay Goel, School of Business, University at Albany, SUNY
32
Arrays
Types and Arrays
• Similar to integer arrays you can have arrays in other primitive
types and also classes.
• Primitive Types
– double [] d is an array of doubles
– char [] c is an array of characters
•
Non-Primitive Types
– String[] args is an array of Strings
– Point[] points is an array of points
• Show the example of sieve of eratosthenes
• Show the example of character count
Sanjay Goel, School of Business, University at Albany, SUNY
33
Arrays
Multidimensional Array
• Just like single dimensional arrays we have multi-dimensional
arrays
int[] a1;
Row
int[][] a2;
Matrix
int[][][] a3;
3D Grid
• Declaring 2D arrays
int[][] a2 = new int[expr1][expr2];
• Initializing 2D arrays
int[][] a = {{1,2},{3,4},{5,6}};
// 3x2
int[][] b = {{1,2,3}, {4,5,6}};
// 2x3
int[][] c = {{1,2,3,4,5,6}};
// 1x3
int[][] ragged = {{1,2}, {3,4,5}, {6}} // 3 rows each with different # of elements
Sanjay Goel, School of Business, University at Albany, SUNY
34
Arrays
Examples
•
Sum of an array two different ways manually without using
loops
•
Minimum and maximum of an array
•
Sieve of Eratosthenes
•
Example of Character Count
•
Sorting of arrays (selection sort)
•
Searching an ordered array
•
Algorithm Complexity
–
Sorting and Searching
Sanjay Goel, School of Business, University at Albany, SUNY
35
Download