sanjay goel, school of business, university at albany, suny 1 msi 692: special topics in information...
Post on 20-Dec-2015
218 Views
Preview:
TRANSCRIPT
1Sanjay Goel, School of Business, University at Albany, SUNY
MSI 692: Special Topics in Information Technology
Lecture 4: Strings & Arrays
Sanjay GoelUniversity at Albany, SUNY
Fall 2004
2Sanjay Goel, School of Business, University at Albany, SUNY
• Recap• Strings• Arrays
– Creation and Access– Copying & assigning arrays– Storage & Indexing– Multidimensional Array
• Examples
Outline for the ClassArrays
4Sanjay Goel, School of Business, University at Albany, SUNY
RecapStructured 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
5Sanjay Goel, School of Business, University at Albany, SUNY
RecapVisibility 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
6Sanjay Goel, School of Business, University at Albany, SUNY
RecapUsage-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.
7Sanjay Goel, School of Business, University at Albany, SUNY
RecapDefinitions
• 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
8Sanjay Goel, School of Business, University at Albany, SUNY
RecapReturn 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.
9Sanjay Goel, School of Business, University at Albany, SUNY
RecapVariables
• 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.
10Sanjay Goel, School of Business, University at Albany, SUNY
RecapMethod 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.
11Sanjay Goel, School of Business, University at Albany, SUNY
Functional AbstractionCall-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.
12Sanjay Goel, School of Business, University at Albany, SUNY
Functional AbstractionRecursion
• 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));
}
13Sanjay Goel, School of Business, University at Albany, SUNY
Functional AbstractionMethod 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.
14Sanjay Goel, School of Business, University at Albany, SUNY
Functional AbstractionErrors
• 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
16Sanjay Goel, School of Business, University at Albany, SUNY
Objects and ClassesStandard 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.
17Sanjay Goel, School of Business, University at Albany, SUNY
Objects and ClassesString 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.
18Sanjay Goel, School of Business, University at Albany, SUNY
Objects and ClassesStandard 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;}
19Sanjay Goel, School of Business, University at Albany, SUNY
Creating ClassesThe 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”))
20Sanjay Goel, School of Business, University at Albany, SUNY
Creating ClassesThe 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”) ;
21Sanjay Goel, School of Business, University at Albany, SUNY
Creating ClassesThe 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 stringsif (strWord.compareTo(strWord2 < 0)
//Display a message - - What will it be?
23Sanjay Goel, School of Business, University at Albany, SUNY
ArraysIntroduction
• 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
24Sanjay Goel, School of Business, University at Albany, SUNY
ArraysStorage 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: 012345
25Sanjay Goel, School of Business, University at Albany, SUNY
ArraysMemory 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.
26Sanjay Goel, School of Business, University at Albany, SUNY
ArraysArray 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]
27Sanjay Goel, School of Business, University at Albany, SUNY
ArraysArray 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
28Sanjay Goel, School of Business, University at Albany, SUNY
ArraysArray 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]
29Sanjay Goel, School of Business, University at Albany, SUNY
ArraysAssigning 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
30Sanjay Goel, School of Business, University at Albany, SUNY
ArraysLength 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.
31Sanjay Goel, School of Business, University at Albany, SUNY
ArraysPassing 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 Scenarios1. 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 methoda. No change happens in the calling method
show using stack
32Sanjay Goel, School of Business, University at Albany, SUNY
ArraysCopying 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
33Sanjay Goel, School of Business, University at Albany, SUNY
ArraysTypes 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
34Sanjay Goel, School of Business, University at Albany, SUNY
ArraysMultidimensional Array
• Just like single dimensional arrays we have multi-dimensional arraysint[] a1; Row
int[][] a2; Matrix
int[][][] a3; 3D Grid
• Declaring 2D arraysint[][] a2 = new int[expr1][expr2];
• Initializing 2D arraysint[][] 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
35Sanjay Goel, School of Business, University at Albany, SUNY
ArraysExamples
• 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
top related