0% found this document useful (0 votes)
14 views8 pages

Understanding Java Arrays Basics

An array is a data structure that holds multiple values of the same type. Arrays use zero-based indexing and their syntax involves specifying the element type, name, and length. Arrays can be initialized, traversed using for loops or foreach loops, and accessed via indexes. The Arrays class provides useful methods for printing, comparing, reversing arrays. Multidimensional arrays store arrays of arrays to represent grids. Jagged arrays allow rows to have varying numbers of columns.

Uploaded by

RohanLaur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Understanding Java Arrays Basics

An array is a data structure that holds multiple values of the same type. Arrays use zero-based indexing and their syntax involves specifying the element type, name, and length. Arrays can be initialized, traversed using for loops or foreach loops, and accessed via indexes. The Arrays class provides useful methods for printing, comparing, reversing arrays. Multidimensional arrays store arrays of arrays to represent grids. Jagged arrays allow rows to have varying numbers of columns.

Uploaded by

RohanLaur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Chapter 7 Arrays

Array
An indexed structure that holds multiple values of the same type.
The values stored in the array are called elements
Like Strings, arrays use zero based indexing
Array Syntax
<element type>[] <name> = new <element type>[length]
Exp)
int[] numbers = new int[10]; //array of 10 ints
String[] names = new String [100]; //array of 100 Strings
Color[] colors = new Color[50]; //array of 50 colors
double[] temp = new double[3];
temp |_| --> |0.0|0.0|0.0|
0 1 2
As you can see, the variable temp is not itself an array. Instead it stores a re
ference to the array.
When an array is constructed, each element is initialized to a default value.
Type
int
double
char
boolean
objects

Value
0
0.0
'\0'
false
null

Initialize an Array
temp[0] = 74.3;
temp[1] = 68.4;
temp[2] = 70.3;
Exp)
for(int=0; i<[Link];i++){
temp[i] = [Link]();
}
Remember with Strings you asked for length by [Link](). With arrays, you do no
t use ().
Array Traversal
Processing each array element sequentially from the first to the last.
for(int i=0; <array>.length; i++){
<do something with array[i]>;
}

An array can provide random access.

Random Access
Manipulating values in any order to allow quick access to each value.
Exp)
[Link]("#1384 = " + temp[1383]);
If you attempt to access an array element that does not exist, Java will halt yo
ur program with an
ArrayIndexOutOfBounds Exception.
Arrays and Methods
Methods can alter the contents of arrays that are passed to them as para
meters
Exp)
int[] list = new int[5];
fillWithOdds(list);
public static void fillWithOdds(int[] data){
for(int i = 0; i<[Link]; i++){
data[i] = 2*i+1;
}
}
The For-Each Loop
Java has a loop construct that simplifies certain array loops (The foreach loop).
Exp)
for(int i = 0; i < [Link]; i++){
if(temps[i]>average){
above++;
}
}
We can rewrite as a for-each loop
for(int n: temps){
if(n>average)
above++;
}
}
There's nothing special about the variable n as long as you keep it consisten wi
thin the body of the loop
You cannot use a for-each loop to change the values of an array or add/remove el
ements from the array
Initializing Arrays
Java has a special syntax for intiializing an array when you know exactl
y what you want to put in.
Exp)
String[] days = new String[7];
days[0] = "Monday";
days[1] = "Tuesday";
.
.
.

Can be written as
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"};
The Arrays Class
Arrays have some limitations. The [Link] package has the Arrays class
, which has some useful methods.
Limitations of
1. You
2. You
s
3. You

Arrays
cannot change the size of an array.
cannot just print the array using the print() or println() method
cannot compare arrays for equality using ==

Array Traversal
Use a for loop or a for-each loop. Remember that you cannot change the c
ontents of an array using a for-each loop.
Printing an Array
int[] list = {17, -3, 42, 8, 12,2};
[Link](list); //[Ie6caf43]
To print an array you must use a for loop, a for-each loop, or toString
method of the Arrays class.
Exp)
[Link]([Link](list));
Testing for Equality
Because arrays are objects, testing for equality is more complex.
Two arrays are equivalent if they have the same length and store the sam
e sequence of values.
The [Link]() method performs this test.
Reversing an Array
public static void reverse(int[] list){
for(int i = 0; i < [Link]/2; i++){
int j = [Link]-i-1;
swap(list,i,j);
}
public static void swap(int[] list, int i, int j){
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
String Traversal Algorithms
In Java we often think of a String as a chunk of text, but you can also
think of it as a sequence of characters.
A String is a lot like an Array.
For Arrays
for(int i = 0; i < <array>.length; i++){
<do something with array[i]>;
}

For Strings
for(int i = 0; i < <String>.length(); i++){
<do something with <String>.charAt()>;
}
To Reverse a String, use the following method
public static String reverse(String text){
String result = "";
for(int i = 0; i< [Link](); i++){
result = [Link](i) + result;
}
}
Reference Semantics
In Java, Arrays are objects. With primitive types, the variable stores t
he actual data. With objects, the variable
stores a reference to the location at which the object is stored.
Primitive Types
int x = 8;
x=>8
Objects
int[] list = new int[3];
list=>AC3F (reference to |0|0|0|
In this case, we say that list refers to the array.
Value Semantics (Value Types)
A system in which values are stored directly and copying is achieved by
creating independent copies of values.
Exp)
public static void main(String[] args){
int x = 8;
foo(x);
[Link](x); //8
}
public static void foo(int z){
z++;
}
Reference Semantics (Reference Types)
A system in which references to values are stored and copying is achieve
d by copying the references.
It will take a while to explore all the implications of this difference.
The key to remember is that when you
are working with objects, you are always working with references to data
rather than the data itself.
The benefits of Objects and Reference Semantics
Efficiency
Objects can be complex and use a lot of space in memory.
If we made copies of these objects, we would run out of memory.
So, we make copies of references instead.
Sharing
Refrence Semantics allow yoou to have many references to a singl
e object.

Multiple Objects
Let's delve deeper into the implications of reference semantics.
Consider the following code:
int[] list = new int[5];
int[] list2 = new int[5];
for(int i = 0; i< [Link]; i++){
list1[i] = 2*i+1;
list2[i] = 2*i+1;
}
int[] list 3 = list2;
list1===> |1|3|5|7|9|
list2===> |1|3|5|7|9|
list3-------^
list2 and list3 are both equally ablbe to modify the array to which they
refer.
list2[2]++ and list3[2]++ will have the same effect.
Since both variables (list2 and list3) refer to sthe same object, you ca
n access/modify the array through either one.
The variables list2 and list3 both refer to the same object.
Thus,
list2==list3 is true, however,
list1==list2 is false, even though they have the same values. Therefore
do not use == to compare objects.
To see if two Arrays are equal, use the [Link] method.
Advanced Array Techniques
Shifting Array elements to the left
Suppose you want to shift the following elements
list---> |3|8|9|7|5| to

list---> |5|9|7|5|3|

Use the following method


public static void rotateLeft(int[] list){
int first = list[0];
for(int i = 0; i< [Link]-1; i++){
list[i] = list[i+1];
}
list[[Link]-1] = first;
}
Shifting Array elements to the right
Suppose you want to shift the following elements
list--> |3|8|9|2|5| to

list--> |5|3|8|9|7|
Use the following method
public static void rotateRight(int[] list){
int last = list[[Link]-1]
for(int i = ([Link]-1); i>=1; i--){
list[i] = list[i-1];
}
int[0] = last;
Arrays of Objects
Arrays of objects behave slightly different than primitive types because
objects are stored as references.
You need to construct the array and the individual objects.
As an example, Java has a point class as part of its [Link].
Each point object is used for Storing an (x,y) coordinate.
To construct an array of Point objects.
Point[] points = new Point[3];
Using the new keyword to construct the array doesn't construct any actua
l (??)
When Java constructs the array, it auto-initializes these array elements
to the zero-equivalent for the type.
Remember, for reference types (objects) this is null.
points--->|null|null|null|
The actual point objects must be constructed separately with the new key
word
Point[] points = new Point[3];
points[0] = new Point(3,7);
points[1] = new Point(4,5);
points[2] = new Point(6,2);
What to know for the FINAL
1) integer division
2) mod
3) order of operations
4) logical AND (OR)
5) String functions
length
substring
charAt
indexOf
6) post/preincrement (++x, x++, --y, y++)
7) trace through code
8) for Loops
9) Conversions: hexidecimal, binary, octal
10) DeMorgan's law
11) if, if else
12) know all primitive types (including boolean)
13) Arrays (10-15 problems)

Declare
Multidimensinal Arrays
An array of arrays, the elements of which are accessed with multiple int
eger indexes.
You might need to store a two-dimensional grid of data that has both rows and co
lumns.
You can form arrays of arbitrarily many dimensions.
double[]
double[][]
double[][][]

one-dimensional array
two-dimensional array
three-dimensional array

Exp)
double[][] temps = new double[2][3]
temps--->|0.0|0.0|0.0|
|0.0|0.0|0.0|
temps[0][2] = 98.3;
temps[1][1] = 99.6;
temps--->|0.0|0.0 |98.3|
|0.0|99.6|0.0 |
To print a two dimensional Array, use the following method.
public static void printArray(double[][] grid){
for(int i = 0; i < [Link]; i++){
for(int j = 0; j < grid[i].length; j++){
[Link](grid[i][j] + " ");
}
[Link]();
}
}
Notice that to ask for the number of rows, you ask for [Link]. To a
sk for the number
of columns you ask for grid[i].length.
The [Link]() method mentioend earlier does not work on multidim
ensional arrays.
Use the following method to print multidimensional Arrays:
[Link]([Link](temps);
Arrays can have as many dimensions as you want. For example, if you want
a three-dimensional
4 by 4 by 4 cube of integers, you would write the following line of code
:
int[][][] cube = new int[4][4][4];
Jagged Arrays
The previous examples have involved rectangular grids that have a fixed
number of rows and columns
It is also possible to creat a Jagged array in which the number of colum

ns varies from row to row.


Divide the construction of Jagged arrays into two steps:
1. Construct the array for holding the rows first
2. Then construct each individual row for the number of columns
that you want
Exp)
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[3];

You might also like