Presentation is loading. Please wait.

Presentation is loading. Please wait.

Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:

Similar presentations


Presentation on theme: "Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:"— Presentation transcript:

1 Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples: int[] counts; double[] scores; String[] studentNames;

2 Array Allocation Arrays are allocated using the Java new operator The syntax is: new type[size]; Examples: counts = new int[10]; scores = new double[15]; studentNames = new String[10];

3 Array Organization 0 1 2 3 4 5 6 7 8 9 counts Each box is an int variable The numbers on top are each variable’s subscript or index An array of size 10 has subscripts 0 to 9

4 Array Subscripts Arrays can contain any one type of value (either primitive values or references) Subscripts are used to access specific array values Examples: counts[0] // first variable in counts counts[1] // second variable in counts counts[9] // last variable in counts counts[10] // error – trying to access // variable outside counts

5 Expressions as Subscripts Array subscripts do not have to be constants Array subscripts do need to be integer expressions that evaluate to valid subscript values for the current array allocation Examples: counts[i] counts[2*i] counts[I/2]

6 Array Initialization Arrays can be initialized by giving a list of their elements If your list contains n elements the subscripts will range from 0 to n – 1 You do not need to allocate the array explicitly after it is initialized Example: int [] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

7 Initializing an Array of Strings final Sring[ ] NAME = { “Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}; // procedure that prints the day of week public void printName (int day, OutputBox out) { out.print(NAME[day – 1]); }

8 Aliases It is possible to have two different variables refer to the same array When this happens these variables are called aliases Creating aliases is not a good programming practice Example of how it can happen: int [ ] A, B; … B = new int [10]; A = B;

9

10 Loops and Array Processing Initializes counts to 0, 10, 20, …, 90 for (int i=0; i < 10; i++) { counts[i] = i * 10; } Prints the contents of counts using length for (int i=0; i < counts.length; i++) { out.println(counts[i]); }

11 Extra Capacity Array Arrays cannot grow after they have been allocated You can allocate more space than you believe your application will need If you guess too low, you will still run out of space You do not need to use all the elements in an array (but total computer memory is finite)

12 Searching This loop terminates as soon as it finds the value 90 stored in grades bool found = false; int i = 0; while (i < size && !found) { // 90 is not in grades[0]..grades[i - 1] if (grades[i] == 90) found = true; else i++; }

13

14 Processing Parallel Arrays This loop counts the number of students whose performance improved from the first test to the second int improved = 0; for (int i = 0; i < size; i++) { if (grades1[i] < grades2[i]) improved++; }

15

16 Arrays of Objects Arrays of objects are declared in the same manner as arrays of primitive variables Assuming that a class Student was declared elsewhere a client application could declare and allocate an array of 10 students using Student[ ] students; students = new Student[10];

17 Passing Arrays as Arguments When an array is passed as an argument to a method, what is passed is a pointer to the array, not a new array (arrays are passed by reference) This means that if the method makes changes to the array, these changes are still in effect when the method returns to its caller This is not true for primitive values which are passed by value and not by reference Method header example: public void read(Student[ ] students) {

18 Two Dimensional Arrays Two dimensional arrays allows us to store data that are recorded in table. For example: Table contains 12 items, we can think of this as a matrix consisting of 4 rows and 3 columns. Item1Item2Item3 Salesgirl #1101530 Salesgirl #2143033 Salesgirl #3200321 Salesgirl #4102004 Sold Person

19 2D arrays manipulations Declaration: –int myArray [ ][ ]; Creation: –myArray = new int[4][3]; // OR –int myArray [ ][ ] = new int[4][3]; Initialisation: –Single Value; myArray[0][0] = 10; –Multiple values: int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}}; int tableA[][] = {{10, 15, 30}, {14, 30, 33}};

20 Variable Size Arrays Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows: –int a[][] = new int [3][]; –a[0]= new int [3]; –a[1]= new int [2]; –a[2]= new int [4];

21 Try: Write a program to Add two Matrix Define 2 dimensional matrix variables: –Say: int a[][], b[][]; Define their size to be 2x3 Initialise like some values Create a matrix c to storage sum value –c[0][0] = a[0][0] + b[0][0] Print the contents of result matrix.

22 Introduction String manipulation is the most common operation performed in Java programs. The easiest way to represent a String (a sequence of characters) is by using an array of characters. –Example: –char place[] = new char[4]; –place[0] = ‘J’; –place[1] = ‘a’; –place[2] = ‘v’; –place[3] = ‘a’; Although character arrays have the advantage of being able to query their length, they themselves are too primitive and don’t support a range of common string operations. For example, copying a string, searching for specific pattern etc. Recognising the importance and common usage of String manipulation in large software projects, Java supports String as one of the fundamental data type at the language level. Strings related book keeping operations (e.g., end of string) are handled automatically.

23 String Operations in Java Following are some useful classes that Java provides for String operations. –String Class –StringBuffer Class –StringTokenizer Class

24 String Class String class provides many operations for manipulating strings. –Constructors –Utility –Comparisons –Conversions String objects are read-only (immutable)

25 Strings Basics Declaration and Creation: String stringName; stringName = new String (“string value”); Example: String city; city = new String (“Bangalore”); Length of string can be accessed by invoking length() method defined in String class: int len = city.length();

26 String operations and Arrays Java Strings can be concatenated using the + operator. –String city = “New” + “York”; –String city1 = “Delhi”; –String city2 = “New “+city1; Strings Arrays –String city[] = new String[5]; –city[0] = new String(“Melbourne”); –city[1] = new String(“Sydney”); –… –String megacities[] = {“Brisbane”, “Sydney”, “Melbourne”, “Adelaide”, “Perth”};

27 String class - Constructors public String()Constructs an empty String. Public String(String value)Constructs a new string copying the specified string.

28 String – Some useful operations public int length()Returns the length of the string. public charAt(int index)Returns the character at the specified location (index) public int compareTo( String anotherString) public int compareToIgnoreCase( String anotherString) Compare the Strings. reigonMatch(int start, String other, int ostart, int count) Compares a region of the Strings with the specified start.

29 String – Some useful operations public String replace(char oldChar, char newChar) Returns a new string with all instances of the oldChar replaced with newChar. public trim()Trims leading and trailing white spaces. public String toLowerCase() public String toUpperCase() Changes as specified.

30 String Class - example // StringDemo.java: some operations on strings class StringDemo { public static void main(String[] args) { String s = new String("Have a nice Day"); // String Length = 15 System.out.println("String Length = " + s.length() ); // Modified String = Have a Good Day System.out.println("Modified String = " + s.replace('n', 'N')); // Converted to Uppercse = HAVE A NICE DAY" System.out.println("Converted to Uppercase = " + s.toUpperCase()); // Converted to Lowercase = have a nice day" System.out.println("Converted to Lowercase = " + s.toLowerCase()); }


Download ppt "Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:"

Similar presentations


Ads by Google