Array Declarations Arrays contain a fixed number of variables of identical type Array declaration...

30
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;

description

Array Organization 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

Transcript of Array Declarations Arrays contain a fixed number of variables of identical type Array declaration...

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

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;

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

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];

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

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

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

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 countscounts[1] // second variable in countscounts[9] // last variable in countscounts[10] // error – trying to access // variable outside counts

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

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]

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

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};

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

Initializing an Array of Strings

final Sring[ ] NAME = { “Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”};

// procedure that prints the day of weekpublic void printName (int day, OutputBox out) { out.print(NAME[day – 1]);}

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

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;

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

Loops and Array Processing

• Initializes counts to 0, 10, 20, … , 90for (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]);}

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

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)

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

Searching

• This loop terminates as soon as it finds the value 90 stored in gradesbool 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++;}

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

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++;}

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

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];

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

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) {

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

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.

Item1 Item2 Item3

Salesgirl #1 10 15 30

Salesgirl #2 14 30 33

Salesgirl #3 200 32 1

Salesgirl #4 10 200 4

SoldPerson

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

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}};

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

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];

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

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.

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

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.

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

String Operations in Java

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

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

String Class

• String class provides many operations for manipulating strings.– Constructors– Utility– Comparisons– Conversions

• String objects are read-only (immutable)

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

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();

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

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”};

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

String class - Constructors

public String() Constructs an empty String.

Public String(String value) Constructs a new string copying the specified string.

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

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.

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

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.

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

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());

}}