Lec 3 Arrays and Strings Mar 23

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

MCS

CS212-Object Oriented
Programming
Lecture 3
Arrays and Strings
(Mar 2023)
Instructor: Lt Col Muhammad Imran Javaid
Email: imranjavaid@mcs.edu.pk

Military College of Signals , NUST


Arrays
• Now we know , how to deal with repeated code, by using loops

• What if we have repeated variables?

• We use Arrays

• What is an Array?

– An array is basically a (fixed-length) sequence of variables of the same type


which can be accessed using an integer index (starting at 0)

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

• For example, following statement allocates an array with enough memory


for 10 integer elements and assigns the array to the myList variable:-
myList = new int[10];

• 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.

• Declaring an array variable, creating an array, and assigning the reference of


the array to the variable can be combined in one statement, as shown below
int[] myList = new int[10];
• Elements of the array can be accessed via variableName[index] , where index
is a 0-based index with a valid range from 0 to length-1
• We can read the length of an array array via array.length

7
Sample Program
/** Example for allocating & using int array and accessing their values */

public class ArrayDemo1 {


public static void main(String[] args) {
// declares an array of integers
int[] myList;
// allocates memory for 10 integers
myList = new int[10];
// initialize array elements
for(int i = 0; i < myList.length; i++) {
myList[i] = (i + 1) * 100;
}
// access array elements
for(int i = 0; i < myList.length; i++) {
System.out.printf("Element at index %d: %d\n",
i, myList[i]);
}
}
8 }
Sample Program
/** Example for allocating & using int array and accessing their values
*/

public class ArrayDemo2 {


public static void main(String[] args) {
// create and initialize an array
int[] myList = {
100, 200, 300,
400, 500, 600,
700, 800, 1000 };
// access array elements
for(int i = 0; i < myList.length; i++) {
System.out.printf("Element %d: %d\n",
i + 1, myList[i]);
}
}
9 }
Sample Program
/** Example for allocating & using string arrays and accessing their values */
public class ArrayDemo2 {
public static final void main ( String [] args ) {
String [] array = new String [4]; // create an string array for length 4
array [0] = "Hello ";
array [1] = "world ";
array [2] = ",it's ";
array [3] = "me!";
System . out. print ( array [0]) ; // prints " hello "
System . out. print( array [1]) ; // prints " world "
System . out. print( array [2]) ; // prints ", it 's "
System . out. println ( array [3]) ; // prints "me !"
array [3] = "EE-OOP";
System . out. print( array [3]) ; // prints " EE-OOP "
System . out. print( array [1]) ; // prints " world "
System . out. print ( array [2]) ; // prints ", it 's "
System . out. print ( array [0]) ; // prints " hello "
}
10 }
Sample Program
/** Example for iterating backwards over arrays using their length */
public class IntArrayIterateBackwards {
public static final void main ( String [] args ) {
int [] array = new int [5]; // create an integer array for length 5
System . out. print ("Initially,all elements are 0:");
for (int i=0; i<array.length; i++) { //indexes are valid from 0 to array.length -1
System . out. print (' ');
System . out. print (array[i]); //access an element of array by using "[index]"
} // prints "0 0 0 0 0"
System . out. println ();
array [4] = 44; // set fifth element to 44
array [2] = 22; // set third element to 22
array [0] = 99; // set first element to 99
array [1] = 11; // set second element to 11
System . out. print (" Now some elements are set: ");
for (int i = array.length; (--i) >= 0;) { // iterate backwards is slightly faster
System . out. print (' '); //since we compare i with constance , not variable
System . out. print ( array [i]); // access an element of array by using "[ index ]"
} // prints "44 0 22 11 99"
11
}
Multidimensional Arrays
• An array can have elements which are arrays too
• This can be used to represent 2-D matrices or data of a pixel graphic, for instance
• All the things discussed so far then apply fully to the multi-dimensional arrays as well
• Creating a 3-D integer array with 3 × 4 × 5 elements is done via
int[][][] a = new int[3][4][5]

• 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:

public static void arraycopy(


Object src, // the source array
int srcPos, // starting position in source array
Object dest, // the destination array
int destPos, // starting position in destination array
int length) // the number of array elements to copy
For Example:
public class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'i', 'n', 'e', 'x',
'p', 'e', 'n', 's', 'i', 'v', 'e' };
char[] copyTo = new char[9];
System.arraycopy(copyFrom, 2, copyTo, 0, 9);
System.out.println(new String(copyTo));
}
}
15
Array Manipulations
• Java provides several methods for performing array manipulations (such as copying,
sorting and searching arrays) in the java.util.Arrays class. For Example:-

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

Initialization : String myString = null;


String Literal vs. String Object

Use Less Memory Less efficient: wastes memory


String Literal vs. String Object
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object
s1 == s1; // true, same pointer
s1 == s2; // true, s1 and s2 share storage in common pool
s1 == s3; // true, s3 is assigned same pointer as s1
s1.equals(s3); // true, same contents
s1 == s4; // false, different pointers
s1.equals(s4); // true, same contents
s4 == s5; // false, different pointers in heap
s4.equals(s5); // true, same contents
Concatenation Example
• Declare and construct two strings, then concatenate str2 to the end of str1
String str1 = new String(“This is the winter “);
String str2 = new String(“of our discontent”);
str1 = str1.concat(str2); //message to str1 to concat str2 to its
end

str2 of our discontent

str1 This is the winter

This is the winter of our


discontent
Note! The same result occurs for str1 = str1 + str2;
String Manipulations
String txt = "Hello World";

System.out.println(txt); // Outputs Hello World


System.out.println(txt.toUpperCase()); // Outputs HELLO WORLD
System.out.println(txt.toLowerCase()); // Outputs hello world

String txt = "Please locate where 'locate' occurs!"; // Find Character in String
System.out.println(txt.indexOf("locate")); // Outputs 7

String firstName = “Ahmad"; // Concatenation


String lastName = “Aariz";
System.out.println(firstName + " " + lastName); // Outputs Ahmad Aariz

String string1 = “Hello How are you”;


char [ ] array1=string1.toCharArray( ); // conversion to character array

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

String s1 = new String (“I am a string”);


String s2 = “ a string”;
String s3 = s1.substring(0,4);
String s4 = “ a string”;
String s5 = s3 + s2;
if (s5 == s1) { } false
if (s1.equals(s5)) { }
true
if (s2 == s4) { }
true
if (s5.equals(s3+s4)) { }
True
String Comparison
• Deep Comparison Using compareTo( ) method of the String class
• compareTo( ) is used to decide whether the string object from which it
is called is less than , equal to or greater than the string passed as
argument to it.
– Returns an integer which is negative if the String object is less than the
argument String
– Returns positive integer if the String object is greater than the argument String.
– Returns zero if both are equal.
• System.out.println(“hello”.compareTo(“hell”)); // 1
Java StringBuffer Class
• Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.
• StringBuffer objects can be altered directly. However, a String object is always a fixed
string
• How to create StringBuffer objects?
StringBuffer string1 = “Hello How are you”; //not allowed
StringBuffer string1 = new StringBuffer(“Hello How are you”);
• StringBuffer contains a block of memory called buffer which may or may not contain a
string and if it does, the string need not occupy all of the buffer
Important Constructors of StringBuffer class
• StringBuffer(): creates an empty string buffer with the initial capacity of 16.
• StringBuffer(String str): creates a string buffer with the specified string.
• StringBuffer(int capacity): creates an empty string buffer with the specified capacity as
length.
Important Methods of StringBuffer
Class
Method Description
StringBuffer append(String s) Is used to append the specified string with this string.
StringBuffer insert(int offset, String s) is used to insert the specified string with this string at the specified position.
StringBuffer replace(int startIndex, int is used to replace the string from specified startIndex and endIndex.
endIndex, String str):
StringBuffer delete(int startIndex, int is used to delete the string from specified startIndex and endIndex.
endIndex)
StringBuffer reverse( ) is used to reverse the string.
int capacity( ) is used to return the current capacity.
void ensureCapacity(int is used to ensure the capacity at least equal to the given minimum.
minimumCapacity):
char charAt(int index) is used to return the character at the specified position.
int length( ) is used to return the length of the string i.e. total number of characters.
String substring(int beginIndex) is used to return the substring from the specified beginIndex.
String substring(int beginIndex, int is used to return the substring from the specified beginIndex and endIndex.
endIndex)
Summary
• We have learned how to create “repetitive data structures”: arrays.

• We have learned how to allocate arrays of fixed sizes or with sizes provided
in variables/expressions.

• We have learned how to access (read, write) array elements

• We have learned how to loop over array elements

• We have learned how to initialize arrays upon creation

• We have learned how to deal with multi-dimensional, i.e., nested array

• We have learnt about strings( Literals/Objects) in java &their manipulations


30
Assignment
BT-Level CLO
C-2 01

• Write Java programs to demonstrate use of following methods of


Arrays class:
– binarySearch()
– equals()
– fill()
– sort()
– parallelSort()

31
Assignment
• Binary Search • Parallel Sort

32
Copyright Notice

The material in this presentation has been taken from textbooks,


reference books, research literature and various sources on
Internet; and compiled/edited for classroom teaching at MCS-NUST
without any infringement into the copyrights of the author(s). The
original authors retain their respective copyrights as per their
stated claims. Commercial use of the material contained herein in
full or in part through copying, publication and reproducing in any
form is strictly prohibited

33

You might also like