KEMBAR78
Core Java Programming Language (JSE) : Chapter V - Arrays | PDF
Java Programming Language SE – 6
Module 5 : Arrays
www.webstackacademy.com
Objectives
● Declare and create arrays of primitive, class, or array types
● Explain why elements of an array are initialized
● Explain how to initialize the elements of an array
● Determine the number of elements in an array
● Create a multidimensional array
● Write code to copy array values from one array to another
www.webstackacademy.com
Creating Arrays
Use the new keyword to create an array object.
For example, a primitive (char) array:
public char[] createArray() {
char[] s;
s = new char[26];
for ( int i=0; i<26; i++ ) {
s[i] = (char) (’A’ + i);
}
return s;
}
www.webstackacademy.com
Creating an Array of
Character Primitives
www.webstackacademy.com
Creating Reference Arrays
Another example, an object array:
public Point[] createArray() {
Point[] p;
p = new Point[10];
for ( int i=0; i<10; i++ ) {
p[i] = new Point(i, i+1);
}
return p;
}
www.webstackacademy.com
Initializing Arrays
● Initialize an array element.
● Create an array with initial values.
String[] names;
names = new String[3];
names[0] = "Georgianna";
names[1] = "Jen";
names[2] = "Simon";
www.webstackacademy.com
Multidimensional Arrays
● Arrays of arrays:
int[][] twoDim = new int[4][];
twoDim[0] = new int[5];
twoDim[1] = new int[5];
int[][] twoDim = new int[][4]; // illegal
● Array of four arrays of five integers each:
int[][] twoDim = new int[4][5];
www.webstackacademy.com
Array Bounds
All array subscripts begin at 0:
public void printElements(int[] list) {
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
}
www.webstackacademy.com
Using the Enhanced
for Loop
● Java 2 Platform, Standard Edition (J2SETM) version 5.0 introduced
an enhanced for loop for iterating over arrays:
public void printElements(int[] list) {
for ( int element : list ) {
System.out.println(element);
}
}
www.webstackacademy.com
Array Resizing
● You cannot resize an array.
● You can use the same reference variable to refer to an entirely new
array, such as:
int[] myArray = new int[6];
myArray = new int[10];
www.webstackacademy.com
Copying Arrays
The System.arraycopy() method to copy arrays is:
//original array
int[] myArray = { 1, 2, 3, 4, 5, 6 };
// new larger array
int[] hold = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
// copy all of the myArray array to the hold
// array, starting with the 0th index
System.arraycopy(myArray, 0, hold, 0, myArray.length);
www.webstackacademy.com
Web Stack Academy (P) Ltd
#83, Farah Towers,
1st floor,MG Road,
Bangalore – 560001
M: +91-80-4128 9576
T: +91-98862 69112
E: info@www.webstackacademy.com

Core Java Programming Language (JSE) : Chapter V - Arrays