Lec 3 Arrays and Strings Mar 23
Lec 3 Arrays and Strings Mar 23
Lec 3 Arrays and Strings Mar 23
CS212-Object Oriented
Programming
Lecture 3
Arrays and Strings
(Mar 2023)
Instructor: Lt Col Muhammad Imran Javaid
Email: imranjavaid@mcs.edu.pk
• We use Arrays
• What is an Array?
2
Arrays
• Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
• Array is a container object that holds a fixed number of values of a same data type.
• The length of an array is established when it is created. After creation, its length is
fixed.
• Each item in an array is called an element, and each element is accessed by its
numerical index.
• As shown in the following illustration, numbering begins with 0. The 9th element, for
example, would therefore be accessed at index 8.
3
Declaring Array Variables
• Like declarations for variables of other types, an array declaration has
two components: the array's type and the array's name. The syntax for
declaring an array variable:-
// preferred way
type[] arrayRefVar;
OR
// works but not preferred way
type arrayRefVar[];
• An array's type is written as type[], where type is the data type of the
contained elements; the brackets are special symbols indicating that this
variable holds an array.
4
Declaring Array Variables
• Although, Java allows to place the brackets after the array's name,
however, convention discourages this form; because the brackets identify
the array type and should appear with the type designation.
• The size of the array is not part of its type (which is why the brackets are
empty).
• An array's name can be any valid identifier.
// preferred way
// preferred way
String[] cars;
int[] myList;
OR
OR
// works but not preferred way
// works but not preferred way
String cars[];
int myList[];
5
Creating Arrays
• As with variables of other types, the declaration does not actually create an
array; it simply tells the compiler that this variable will hold an array of the
specified type.
• One way to create an array is with the new operator. The following syntax is
used to create an array of specified size & type and assign its reference to a
array variable:-
arrayRefVar = new type[arrySize];
• If we create an array, its elements are set to 0 (or null in object arrays such as
String[] )
6
Creating Arrays
• Alternatively, we can use the shortcut syntax to create and initialize an array:
int[] myList = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };
• Here the length of the array is determined by the number of values provided
between braces and separated by commas.
7
Sample Program
/** Example for allocating & using int array and accessing their values */
• a[1][2][4] accesses the 5th element of the third one-dimensional array in the second
two-dimensional array stored in the three-dimensional array
• Initialization can be done via nested braces, e.g.,
char[][] z = { {'a', 'b'}, {'c', 'd’}}
• We can allocate and initialize each element/dimension of the array separately as well
12
Multidimensional Arrays
• In the Java a multidimensional array is an array whose components are themselves arrays.
• Unlike arrays in C or Fortran, the rows are allowed to vary in length. For Example:
public class Demo2DArray {
public static void main(String[] args) {
int[][] twoDim = {
{ 11, 12, 13 },
{ 21, 22, 23, 24, 25 },
{ 31, 32 },
{ 41, 42, 43, 44 }
};
for(int row = 0; row < twoDim.length; row++) {
for(int col = 0; col < twoDim[row].length; col++) {
System.out.printf("%d, ", twoDim[row][col]);
}
System.out.println("\b\b ");
}
}
}
13
Multidimensional Arrays
/** Example for allocating and using a 2d- int arrays and iterating over them */
public class IntArray2DNewIterate {
public static final void main ( String [] args ) {
int [][] array = new int [5][3]; // create a 2-d integer array for length 5*3
for ( int i = 0; i < array . length ; i++) { // iterating over first dimension
for (int j = 0; j < array [i]. length ; j++) { // iterating over second dimension
array [i][j] = (i * j); // setting element
}
}
// now we want to print the array
for ( int [] row : array ) { //fast read-only iterationover "rows", i.e., first dim of 2d
for (int value : row ) { // fast read - only iteration over elements in selected row
System .out . print (" ");
System .out . print ( value ); // print the element value
}
System . out. println ();
}
}
14 }
Copying Arrays
• The System class has an arraycopy() method that can be used to efficiently copy data
from one array into another:
import java.util.Arrays;
public class ArrayCopyDemo2 {
public static void main(String[] args) {
char[] copyFrom = { 'i', 'n', 'e', 'x',
'p', 'e', 'n', 's', 'i', 'v', 'e' };
char[] copyTo = Arrays.copyOfRange(copyFrom, 2, 11);
System.out.println(new String(copyTo));
}
}
• Note that the second parameter of the copyOfRange() method is the initial index of
the range to be copied, inclusively, while the third parameter is the final index of the
16 range to be copied, exclusively.
Array Manipulations
• Some other useful operations provided by methods in
the java.util.Arrays class, are:
– Searching an array for a specific value to get the index at which it is placed
(the binarySearch() method).
– Comparing two arrays to determine if they are equal or not (the equals() method).
– Filling an array to place a specific value at each index (the fill() method).
– Sorting an array into ascending order. This can be done either sequentially, using
the sort() method, or concurrently, using the parallelSort() method. Parallel
sorting of large arrays on multiprocessor systems is faster than sequential array
sorting.
17
Strings
• A string is a sequence of symbols.
• A Java String contains an immutable sequence of Unicode characters.
• Java provides you with String class , java.lang package, which does not require an import
statement.
• Unlike C/C++, where string is simply an array of char, A Java String is an object of the
class java.lang.
• String is immutable. That is, its content cannot be modified once it is created. For
example, the method toUpperCase() constructs and returns a new String instead of
modifying the its existing content.
• You can use the method equals() of the String class to compare the contents of two
Strings. You can use the relational equality operator '==' to compare the references (or
pointers) of two objects.
18
String Basics-Declaration and Creation
A String can be constructed by either:
– Directly assigning a string literal to a String reference - just like a primitive, or
– via the "new" operator and constructor, similar to any other classes. However, this is not
commonly-used and is not recommended.
Example
String str1 = "Java is Great"; // Implicit construction via string literal
String str2 = new String("I'm cool"); // Explicit construction via new
String str = “MCS";
str=“EE-59”;
String name=str;
String stringName= new String (“string value”);
String city= new String (“Islamabad”);
String txt = "Please locate where 'locate' occurs!"; // Find Character in String
System.out.println(txt.indexOf("locate")); // Outputs 7
string2=String.copyValueOf(array1); //copyValueOf(array1,6,3);
23
String Comparison
• Shallow comparison: = =
• Deep comparison : equals( ); OR compareTo( );
• The == will check whether the two String variables refer to the same string
• If they reference separate strings, you will get false regardless of whether or not the
strings happen to be identical
• It does not compare the strings themselves, it compares the references to the
strings, hence called shallow comparison.
str1
A string
str2
String Comparison
• Deep Comparison : Using equals( ) method of the String class.;
• Equals( ) is used to decide whether the strings referred by two String
variables are equal or not.
• This method does a case sensitive comparison
• Two strings are equal if they are the same length and each character in
one string is identical to the corresponding character in the other.
• Use equalsIgnoreCase( ) method to check for equality between two
strings ignoring the case of the string characters.
Same Object / Same Reference
• We have learned how to allocate arrays of fixed sizes or with sizes provided
in variables/expressions.
31
Assignment
• Binary Search • Parallel Sort
32
Copyright Notice
33