0% found this document useful (0 votes)
0 views

CS212 - Object Oriented Programming-Week2-2

The document provides an overview of arrays in Java, covering their definition, creation, and manipulation, including the use of enhanced for loops and passing arrays to methods. It also discusses multidimensional arrays, variable-length argument lists, and command-line arguments. Additionally, it introduces Java ArrayLists as dynamic arrays and highlights built-in functions for array manipulation.

Uploaded by

mehwish.kiran
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

CS212 - Object Oriented Programming-Week2-2

The document provides an overview of arrays in Java, covering their definition, creation, and manipulation, including the use of enhanced for loops and passing arrays to methods. It also discusses multidimensional arrays, variable-length argument lists, and command-line arguments. Additionally, it introduces Java ArrayLists as dynamic arrays and highlights built-in functions for array manipulation.

Uploaded by

mehwish.kiran
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

CS212 - Object

Oriented
Programming

Arrays in Java
Mehwish Kiran
[email protected]
Arrays

• It’s a Data structure


• An array is a group of variables (called elements or
components) containing values that all have the same
type. Do you know the
difference between
• Arrays are of reference data type. primitive data
types and reference
• Elements of an array can be either primitive types?
types or reference types
Array Index
• Also called subscript
• Position number in square brackets
• Must be positive integer or integer
• expression
• First element has index zero
a = 5;
b = 6;
c[a + b] += 2; // Adds 2 to c[ 11 ]
Creating and Declaring
Arrays in Java
• Arrays are objects that occupy memory
• Created dynamically with keyword new
• int c[] = new int[ 12 ];
• –Equivalent to
• int c[]; // declare array variable
• c = new int[ 12 ]; // create array
• We can create arrays of objects too
• String b[] = new String[ 100 ];
• String[] b = new String[ 100 ], x = new String[ 27 ];
Creating and Declaring
Arrays in Java

When an array is created, each of its elements receives a


default value:
• zero for the numeric primitive-type elements,
• false for boolean elements and n
• null for references
Remember while creating
arrays

Specifying the number of elements in the square brackets


of the declaration (e.g., int c[12];) is a syntax error.
Declaring multiple array variables in a single declaration
can lead to subtle errors.
int[] a, b, c;
or
int a[], b, c;
Arrays using initializer

• Use initializer list


• Items enclosed in braces ({})
• Items in list separated by commas
int n[] = { 10, 20, 30, 40, 50 };
• Creates a five-element array
• Index values of 0, 1, 2, 3, 4
• Do not need keyword new
Constants

• Constant variables also are called named constants or


read-only variables.
• more readable programs as compared to literal values
e.g. ARRAY_LENGTH
• Assigning a value to a constant after the variable has
been initialized is a compilation error.
• Attempting to use a constant before it is initialized is a
compilation error.
Challenge

Twenty students were asked to rate on a scale


of 1 to 5 the quality of the food in the student
cafeteria, with 1 being “awful” and 5 being
“excellent.” Place the 20 responses in an
integer array and determine the frequency of
each rating.
Error prevention tips

When writing code to loop through an array, ensure that the


array index is always greater than or equal to 0 and less
than the length of the array. The loop-continuation condition
should prevent the accessing of elements outside this
range.
An exception indicates that an error has occurred in a
program. A programmer often can write code to recover
from an exception and continue program execution, rather
than abnormally terminating the program. When a program
attempts to access an element outside the array bounds, an
ArrayIndexOutOfBoundsException occurs.
Enhanced for loop statement

Allows iterates through elements of an array or a collection


without using a counter
Avoiding the possibility of “stepping outside” the array
Syntax
for (parameter : arrayName)
statement
where parameter has a type and an identifier.
type of the parameter must be consistent with the type of
the elements in the array
Enhanced for loop statement

Lines 12-13 are equivalent to


for (int counter = 0; counter < array.length;
counter++) total += array[ counter ];
Usage Limitations
• Can access array elements
• Cannot modify array elements
• Cannot access the counter indicating the index
Enhanced for loop practice

Consider the following array and print


each element using enhanced for
loop
String[] strAr2 = {"Ani", "Sam", " Joe“,
“Saad”, “Sara”, “Ahmed”, “faiz”};
Enhanced for loop practice

Consider the following array and


calculate cgpa/average using
enhanced for loop. Print the output at
the end
double[] gpa = {3.5, 2.8, 3.8, 3.2};
Enhanced for loop practice

Now consider the same array and


find the max gpa achieved
double[] gpa = {3.5, 2.8, 3.8, 3.2};
Passing Arrays to Methods

To pass array argument to a method


Specify array name without brackets
Array hourlyTemperatures is declared as
int hourlyTemperatures[] = new int[ 24 ];
The method call
modifyArray( hourlyTemperatures );
Passes array hourlyTemperatures to method
modifyArray
Passing Arrays to Methods

Pass-by-value Pass-by-reference
• Caller gives called method
• Copy of argument’s direct access to caller’s data
value is passed to
called method • Called method can
manipulate this data
• In Java, every primitive • Improved performance over
In is pass-by-value
Java, arrays are pass-by-value
objects
Therefore, arrays are • In Java, every object is pass-
passed to methods by by-reference
reference
Passing Arrays to Methods

Write a program to pass an array of size 10 to


a function which doubles the value of each
element. Display the array from main method
Multidimensional Arrays

Tables with rows and columns


˃Two-dimensional array
˃m-by-n array
>Java does not support
multidimensional arrays
directly
Multidimensional Arrays
• Arrays of one-dimensional arrays Grouped by rows

• Declaring two-dimensional array b[2][2]


• int b[][] = { { 1, 2 }, { 3, 4 } };
• –1 and 2 initialize b[0][0] and b[0][1]
• –3 and 4 initialize b[1][0] and b[1][1]

• int b[][] = { { 1, 2 }, { 3, 4, 5 } }; int[][] b ={{1,2},



{3,4,5}}
row 0 contains elements 1 and 2
• row 1 contains elements 3, 4 and 5
• Lengths of rows in array are not required to be the same!
Multidimensional Arrays
• Creating two-dimensional arrays with array-creation expressions
• Can be created dynamically
• 3-by-4 array

• int b[][]; b = new int[ 3 ][ 4 ];


• Rows can have different number of columns

• int b[][];
• b = new int[ 2 ][ ]; // create 2 rows
• b[ 0 ] = new int[ 5 ]; // create 5 cols for row 0
• b[ 1 ] = new int[ 3 ]; // create 3 cols for row 1
Multidimensional Arrays

Declare a two-dimensional array in


java with 3 rows and 4, 5, &7
columns each
Multidimensional Arrays

Write a method Add() which adds


all the elements of a two-
dimensional array
Variable-length argument lists
• Unspecified number of arguments
• Use ellipsis (…) in method’s parameter list
• Can occur only once in parameter list
• Must be placed at the end of parameter list
• Treated as an array whose elements are all of the
same type
Variable-length argument lists
Variable-length argument lists
Common Programming Error
• Placing an ellipsis in the middle of a method
parameter list is a syntax error. An ellipsis may be
placed only at the end of the parameter list.
Command-line Arguments
• Pass arguments from the command line
String args[]
• Appear after the class name in the java command
java MyClass a b //arguments are separated by white spaces not
commas

• Number of arguments passed in from command line


args.length
• First command-line argument
• args[ 0 ]
Command-line Arguments
• Pass arguments from the command line
String args[]
• Appear after the class name in the java command
java MyClass a b
• Number of arguments passed in from command line
args.length
• First command-line argument
• args[ 0 ]
Command line arguments
• Write a program that takes size of an array as
specified by the first command line argument. If no
command line argument is provided use 10 as the
default size
Class Arrays
• import java.util.Arrays;
• Built in functions
• sort
• binarySearch
• Equals
• fill
ArrayLists
• Java ArrayList is a part of collections framework, and it
is a class of java.util package.
• It provides us with dynamic arrays in Java.
• It may be slower than standard arrays but can be
helpful in programs where lots of manipulation in array
is required.
Syntax of ArrayLists
ArrayList<T>
ArrayList<String> list;
• Only nonprimitive types can be used to declare
variables and create objects of generic classes.
• However, Java provides a mechanism—known as
boxing—that allows primitive values to be wrapped
as objects for use with generic classes.
ArrayList<Integer> integers;
Methods of ArrayList
Question/
Answers

You might also like