1 of 30

Ch-9

Working with Array and String

2 of 30

What is Array?

  • An array is a group variables. It represents a collection of homogeneous type of elements.
  • Suppose we need to stored percentages of 50 students.
  • Instead of creating individual 50 variables for storing percentages we can create a single array consisting of 50 elements starting with 0th element to 49th element.
  • Individual element of an array can be accessed by using its index number in square brackets preceded by array name. For eg. Per[5] represents 6th element of per array.

3 of 30

Array Introduction

  • Arrays are useful to represent vector, matrix and other multi-dimensional data.
  • Vector is a one dimensional(1-D) data structure that can be used to store list of items like characters, numbers.
  • Matrix is used to represent two dimensional(2-D) data structure like table of rows and columns.
  • Creating an array is a two step process.
    • Declare an array object
    • Create an array object.

4 of 30

Types of array

  • Arrays are of two types:
    • One dimensional array
      • For eg. Marks[]
    • Two dimensional array
      • For eg. Marks[][]

5 of 30

(1) Declare an array object

  • To declare a 1-D array we use a pair of square brackets after array name or after data type.
    • Syntax:

<data type> <array name> [];

Or

<data type> [] <array name>

For eg.

int marks[]

or

Int [] marks

6 of 30

(2) Create an array object

  • An array object named marks with size for five elements can be created as follows:

marks = new int [5];

We can combine declaration and creation statement as follows:

int marks[] = new int [5];

or

int [] marks = new int [5];

7 of 30

Initialization

  • Array elements can also be initialized as follows:
    • Int marks[] = {50,60,70,80,90};
  • Remember that array index starts with 0th element.

marks[0]

50

marks[1]

60

marks[2]

70

marks[3]

80

marks[4]

90

Element Reference

Array

content

0

1

2

3

4

Array

Index

8 of 30

1-D array program

class Array1

{

public static void main(String[] s)

{

int marks[];

marks = new int [7];

for(int i=0;i<7;i++)

{

System.out.println(“marks[ “ + i + “ ] is” + marks[i]);

}

}

}

Output

marks[0] is 0

marks[1] is 0

marks[2] is 0

marks[3] is 0

marks[4] is 0

marks[5] is 0

marks[6] is 0

9 of 30

One can specify the initial values of data elements while declaring an array.

class Array2

{

public static void main(String[] s)

{ int marks1[];

marks1 = new int[3];

int marks2[] = new int[3];

int [] marks3 = new int[3];

int marks4[] = {50,60,70};

int [] marks5 = {70,80,90};

System.out.print(“Array marks1:\t”);

display(marks1,3);

System.out.print(“Array marks2:\t”);

display(marks2,3);

System.out.print(“Array marks3:\t”);

display(marks3,3);

System.out.print(“Array marks4:\t”);

display(marks4,3);

System.out.print(“Array marks5:\t”);

display(marks5,3); }

Static void display(int arr[], int size)

{

for(int i=0;i<size;i++)

{

system.out.print(arr[i]+”\t”);

}

System.out.println();

}

Output

Array marks1: 0 0 0

Array marks2: 0 0 0

Array marks3: 0 0 0

Array marks4: 50 60 70

Array marks5: 70 80 90

10 of 30

One can specify the initial values of data elements while declaring an array.

class ArrayAvg

{

public static void main(String[] s)

{

double numbers [] = {10.5, 20.6, 30.8, 15.5, 17.3, 25.5, 27.2, 20, 30, 18.5};

byte ctr;

double sum=0;avg;

System.out.println(“List of numbers is”);

for(ctr=0;ctr<10;ctr++)

{

System.out.println(numbers[ctr]);

sub = sum numbers[ctr];

}

avg=sum/10;

System.out.println(“\nAverage of above

numbers is “ + avg);

}

}

Output

10.5

20.6

30.8

15.5

17.3

25.5

27.2

20.0

30.0

18.5

Average of above num is: 21.59

11 of 30

Sort() method

  • Sort() method can be used to sort entire or part of array.
  • Sort can take either 3 or 2 arguments.
  • These 3 arguments are array, start & last
  • It can also sort partial array from index start to last.
  • For eg. Java.util.Arrays.sort(list)
  • Java.util.Arrays.sort(list,3,9)

12 of 30

fill() method

  • fill method is used to fill the whole or partial array with specified value.
  • When fill method is invoked with two arguments: array and value; it assigns the specified value to all array elements.
  • For eg. Java.util.Arrays.fill(list,7)
  • When fill method is invoked with four arguments: array, start, last, value; it fills partial array from element at start to last with specified value.
  • For eg. Java.util.Arrays.fill(list,2,6,5)
  • Remember that array index number starts with 0.

13 of 30

2-D (Two dimensional) Array

  • Two dimensional arrays are used to store tabular data in the form of rows and columns.
  • To create a 2-D array with 5 rows and 3 columns we can write the statement: � int marks[][] = new int [5][3];
  • Note that in a 2-D array first index number denotes row.

14 of 30

2-D (Two dimensional) Array

  • 2-D array is nothing but a group of one dimensional arrays.

marks[0]

marks[1]

marks[2]

marks[3]

marks[4]

marks[0][0]

marks[0][1]

marks[0][2]

marks[1][0]

marks[1][1]

marks[1][2]

marks[2][0]

marks[2][1]

marks[2][2]

marks[3][0]

marks[3][1]

marks[3][2]

marks[4][0]

marks[4][1]

marks[4][2]

marks

15 of 30

Strings

  • String is nothing but a sequence of characters.
  • String can be considered as 1-D array of characters.
  • Java supports two types of strings that are handled by two classes : String and StringBuffer.
  • Out of these two buffers we will see String only.

16 of 30

String constructor:

(1) String() without arguments create a string object with no character.

For eg. String str1 = new String();

(2) String(char ary[]): Creates a String object with its initial value using ary argument.

For eg. char name[] = {‘J’,’a’,’v’,’a’} String str2 = new String(name)

(3) String(char ary[],int start, int len): Creates a String object using 1-D ary argument starting at ary[start] with len number of characters.

For eg. String str3 = new String(name,1,2)

(4) String(String strObj): Creates a String object which is same as object specified in argument.

For eg. String str4 = new String(str3)

(5) String(String literal): Creates a String object that refers to the literal specified in argument.

For eg.String str5 = new String(“Java”)

17 of 30

String class methods:

(1) boolean equals(String str): Returns true if invoking string is same as str.

For eg. str1 = “India is great” str2 = “INDIA IS GREAT”

str1.equals(str2) 🡪Returns false here.

(2) boolean equalsIgnoreCase(String str): Returns true if invoking string is same as str after ignoring case.

For eg. str1.equalsIgnoreCase(str2) 🡪 Returns True here.

(3) Int compareTo(String str): Returns 0, >0 or <0

For eg. str1.compareTo(str2) 🡪 Returns 32 ie. ASCII value

(4) int compareToIgnoreCase(String str): Similar to CompareTo but case insensitive.

For eg. Str1.CompareToIgnoreCase(str2) 🡪 Returns 0

18 of 30

String class methods:

  1. int length(): Returns number of characters in invoking string.

(2) char indexAt(int index): Returns character at index position from the invoking string. (Index considered from 0)

(3) byte[] getBytes(): Returns Array of characters as bytes from invoking string.

(4) void getChars(int fromIndx, int toIndx, char target[], int targetIndx) : Copies characters of invoking string from fromIndx to toIndx to target array.

(5) String concate(String str): Returns string after appending str with the invoking string.

(6) String toLowerCase(): Returns string with all characters of invoking string converted to lower case.

(7) String toUpperCase(): Returns string with all characters of invoking string converted to upper case.

19 of 30

String class methods:

  1. Date: Constructs date object using current system time.

(2) Date(long ElapsedTime): Constructs date object using specified time in milliseconds elapsed since January 1, 1970 GMT.

(3) String toString (): Returns a string representing date and time of invoking object.

(4) Long getTime() : Returns number of milliseconds since January 1, 1970 GMT.

(5) void setTime(long elapsedTime): Sets new date and time of an object using elapsed time.

20 of 30

__________ is a group variables. It represents a collection of homogeneous type of elements.

Array

An array index number starts with which number?

0

How many types of arrays are there?

2

21 of 30

________ is a one dimensional array.

Vector

____________ is a two dimensional array.

Matrix

Creating an array consists of how many steps?

2

22 of 30

int marks[] What type of array statement is this?

Declaration

marks = new int [10] What type of statement is this?

Array object creation

_______ method is used to sort entire or part of array.

sort

23 of 30

Sort function can take how many arguments?

2 or 3

sort function contains which 3 arguments ?

Array , start and last

Sort function is available in which java package?

Java.util.Arrays

24 of 30

fill function can take how many arguments?

2 or 4

fill function contains which 3 arguments ?

Array , start , last and value

fill function is available in which java package?

Java.util.Arrays

25 of 30

In the statement “int marks[][] = new int [5][3];” which number represents column?

3

A ________is nothing but a sequence of characters.

String

Java supports how many types of strings classes?

2

26 of 30

Java supports which string classes?

String and StringBuffer

A ________is nothing but a sequence of characters.

String

Java supports how many types of strings classes?

2

27 of 30

Length function

Int length() : Returns number of characters in invoking string.

28 of 30

indexAt function

Char indexAt(int index): Returns character at index position from the invoking string, index considered from 0.

29 of 30

getBytes() function

Byte[] getBytes(): Returns an array of characters as bytes from invoking string.

30 of 30

Void getChars(int fromIndx, inttoIndx, char target[], int targetIndx): copies characters of invoking string from fromIndx to toIndx-1 to target array from targetIndx onwards.

String concat(String str): Returns a string after appending str with the invoking string.

String toLowerCase(): Returns a string with all characters of invoking string converted to lowercase.

String toUpperCase(): Returns a string with all characters of invoking string converted to uppercase.