Java Programming I on YouTube:
https://www.youtube.com/playlist?list=PLLIqcoGpl73iaXAtS_-V_Xdx3mhTzPwb5
The syntax for declaring and instantiating an array:
There are two ways to declare an array,
type[] arrayName; type arrayName[];
How to instantiate an array
arrayName = new type[length];
How to declare and instantiate an array in one statement
type[] arrayName = new type[length];
Code that declares an array of five ints
int[] num = new int[5];
Code that declares an array of doubles
double[] prices;
Code that instantiates an array of doubles
prices = new double[4];
Code that declares and instantiates an array of doubles in one statement
double[] prices = new double[4];
An array of String objects
String[] nameList = new String[5]; nameList[0] = "Amanda Green"; nameList[1] = "Vijay Arora"; nameList[2] = "Sheila Mann"; nameList[3] = "Rohit Sharma"; nameList[4] = "Mandy Johnson";
An array of Product objects
Product[] products = new Product[5];
Code that uses a constant to specify the array length
final int TITLE_COUNT = 100; // size set at compile time String[] titles = new String[TITLE_COUNT];
Code that uses a variable to specify the array length
Scanner sc = new Scanner(System.in); int titleCount = sc.nextInt(); // size set at runtime String[] titles = new String[titleCount];
The syntax for referring to an element of an array
arrayName[index]
Code that assigns values to an array of double types
double[] prices = new double[4]; prices[0] = 14.95; prices[1] = 12.95; prices[2] = 11.95; prices[3] = 9.95; //prices[4] = 8.95; // this would throw // ArrayIndexOutOfBoundsException
Code that assigns values to an array of String types
String[] names = new String[3]; names[0] = "Ted Lewis"; names[1] = "Sue Jones"; names[2] = "Ray Thomas";
int[] num = new int[10];
num[3] = 10; num[6] = 35; num[5] = num[3] + num[6];
Code that assigns objects to an array of Product objects
Product[] products = new Product[2]; products[0] = new Product("java"); products[1] = new Product("jsps");
The syntax for creating an array and assigning values in one statement
type[] arrayName = {value1, value2, value3, ...};
Examples that create an array and assign values in one statement
double[] prices = {14.95, 12.95, 11.95, 9.95}; String[] names = { "Ted Lewis", "Sue Jones", "Ray Thomas"}; Product[] products = { new Product("java"), new Product("jsps")};
When declaring and initializing arrays, the size of the array is determined by the number of initial values within the braces
If an array is declared and initialized simultaneously, do not use the operator new to instantiate the array object
The syntax for getting the length of an array
arrayName.length
Code that puts the numbers 0 through 9 in an array
int[] values = new int[10]; for (int i = 0; i < values.length; i++) { values[i] = i; }
The field variable length contains the size of the array
The field variable length can be directly accessed in a program using the array name and the dot operator
It is a common practice for a program to keep track of the number of filled elements in an array
Code that prints an array of prices to the console
double[] prices = {14.95, 12.95, 11.95, 9.95}; for (int i = 0; i < prices.length; i++) { System.out.println(prices[i]); }
The console output
14.95 12.95 11.95 9.95
Code that computes the average of the array of prices
double sum = 0.0; for (int i = 0; i < prices.length; i++) { sum += prices[i]; } double average = sum/prices.length;
Another way to compute the average in a for loop
double sum = 0.0; for (int i = 0; i < prices.length; sum += prices[i++]); average = sum / prices.length;
The syntax of the enhanced for loop
for ( type variableName : arrayName )
{
statements
}
Code that prints an array of prices to the console
double[] prices = {14.95, 12.95, 11.95, 9.95}; for (double price : prices) { System.out.println(price); }
The console output
14.95 12.95 11.95 9.95
Enhanced for loop is also known as foreach loop.
The syntax to use "foreach" loop to process the elements of an array is:
for (dataType identifier : arrayName) { statements }
Here, the identifier is a variable, and the data type of identifier is the same as the data type of the array elements
Code that computes the average of the array of prices
double sum = 0.0; for (double price : prices) { sum += price; } double average = sum / prices.length;
java.util.Arrays
A few static methods of the Arrays class:
fill( arrayName, value ) fill( arrayName, index1, index2, value ) equals( arrayName1, arrayName2 ) copyOf( arrayName, length ) copyOfRange( arrayName, index1, index2 ) sort( arrayName ) sort( arrayName, index1, index2 ) binarySearch( arrayName, value )
Code that uses the fill method
int[] quantities = new int[5]; Arrays.fill(quantities, 1); // all elements are set to 1
Code that uses the fill method to fill 3 elements in an array
int[] quantities = new int[5]; Arrays.fill(quantities, 1, 4, 100); // elements 1, 2, and // 3 are set to 100
The expression (array1 == array2) determines if the determines whether array1 and array2 refer to the same array in memory:
if ( array1 == array2 ) { //... }
To determine whether arrays contain the same elements, you can compare them element by element
You can write a method that returns true if two int arrays contain the same elements
Code that uses the equals method
String[] titles1 = { "War and Peace", "Gone With the Wind"}; String[] titles2 = { "War and Peace", "Gone With the Wind"}; if (titles1 == titles2) System.out.println("titles1 == titles2 is true"); else System.out.println("titles1 == titles2 is false"); if (Arrays.equals(titles1, titles2)) System.out.println( "Arrays.equals(titles1, titles2) is true"); else System.out.println( "Arrays.equals(titles1, titles2) is false");
The console output
titles1 == titles2 is false Arrays.equals(titles1, titles2) is true
Code that uses the sort method
int[] numbers = {2,6,4,1,8,5,9,3,7,0}; Arrays.sort(numbers); for (int num : numbers) { System.out.print(num + " "); }
The console output
0 1 2 3 4 5 6 7 8 9
Code that uses the sort and binarySearch methods
String[] productCodes = {"mcbl", "jsps", "java"}; Arrays.sort(productCodes); int index = Arrays.binarySearch(productCodes, "mcbl"); // sets index to 2
// sequential search for an item inside array: public static int seqSearch( int[] list, int searchItem ) { int idx = 0; while ( idx < list.length ) { if ( list[ idx ] == searchItem ) { return idx; } } return -1; }//seqSearch
The Comparable interface is defined in the Java API as follows:
public interface Comparable { int compareTo(Object obj); }
An Item class that implements the Comparable interface:
public class Item implements Comparable {
private int number;
private String description;
public Item(int number, String description) {
this.number = number;
this.description = description;
}
public int getNumber() {
return number;
}
public String getDescription() {
return description;
}
// NOTE: @Override indicates programmer's intention to
// override a method declared in an interface or a superclass:
@Override
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getNumber() < i.getNumber())
return -1;
if (this.getNumber() > i.getNumber())
return 1;
return 0;
}
}//class Item
Code that sorts an array of Item objects
Item[] items = new Item[3]; items[0] = new Item(102, "Duct Tape"); items[1] = new Item(103, "Bailing Wire"); items[2] = new Item(101, "Chewing Gum"); Arrays.sort(items); for (Item i : items) System.out.println(i.getNumber() + ": " + i.getDescription());
The console output
101: Chewing Gum 102: Duct Tape 103: Bailing Wire
Code that creates a reference to an array
double[] grades = {92.3, 88.0, 95.2, 90.5}; double[] percentages = grades; percentages[1] = 70.2; // changes grades[1] too System.out.println("grades[1]=" + grades[1]); // prints 70.2
Code that reuses an array variable
double[] grades = new double[5]; grades = new double[20]
public static void arraysAsFormalParameter( int[] arr_first, double[] arr_second, int num ) { //... } public static void demo() { int[] intList = new int[10]; double[] doubleNumList = new double[15]; int number; // make a call: arraysAsFormalParameter(intList, doubleNumList, number); }
Code that copies the values of an array with JDK 1.6 or later:
double[] grades = {92.3, 88.0, 95.2, 90.5}; double[] percentages = Arrays.copyOf( grades, grades.length); percentages[1] = 70.2; // doesn't change grades[1] System.out.println("grades[1]=" + grades[1]); // prints 88.0
Code that copies part of one array into another array
double[] grades = {92.3, 88.0, 95.2, 90.5}; Arrays.sort(grades); double[] lowestGrades = Arrays.copyOfRange(grades, 0, 2); double[] highestGrades = Arrays.copyOfRange( grades, 2, 4);
The syntax of the arraycopy method of the System class
System.arraycopy( fromArray, intFromIndex, toArray, intToIndex, intLength);
Code that copies the values of an array
double[] grades = {92.3, 88.0, 95.2, 90.5}; double[] percentages = new double[grades.length]; System.arraycopy( grades, 0, percentages, 0, grades.length); percentages[1] = 70.2; // doesn't change grades[1] System.out.println("grades[1]=" + grades[1]); // prints 88.0
Code that copies part of one array into another array
double[] grades = {92.3, 88.0, 95.2, 90.5}; Arrays.sort(grades); double[] lowestGrades = new double[2]; System.arraycopy(grades, 0, lowestGrades, 0, 2); double[] highestGrades = new double[2]; System.arraycopy(grades, 2, highestGrades, 0, 2);
The syntax for creating a rectangular array
type[][] arrayName = new type[rowCount][columnCount];
A statement that creates a 3x2 array
int[][] numbers = new int[3][2];
|
|
The syntax for referring to an element of a rectangular array
arrayName[rowIndex][columnIndex]
The indexes for a 3x2 array
[0][0] [0][1] [1][0] [1][1] [2][0] [2][1]
Code that assigns values to the array
numbers[0][0] = 1; numbers[0][1] = 2; numbers[1][0] = 3; numbers[1][1] = 4; numbers[2][0] = 5; numbers[2][1] = 6;
Statement
int[][] matrix = new int[20][15];
declares and instantiates a two-dimensional array matrix of 20 rows and 15 columns
Each row of matrix is a one-dimensional array:
matrix.length // returns 20, the number of rows matrix[0] // refers to the first row matrix[0].length // returns 15, the number of columns in the first row matrix[1].length // returns 15, the number of columns in the second row matrix[2].length // and so on.
Code that creates a 3x2 array and initializes it in one statement
int[][] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
To initialize a two-dimensional array when it is declared:
The elements of each row are enclosed within braces and separated by commas
All rows are enclosed within braces
Initialization of irregularly-shaped arrays is also permitted:
int[][] numbers = { { 1, 2, 5 }, { 3 }, { 5, 6, 8, 2, 4 } };
Code that processes a rectangular array with nested for loops
int[][] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; for (int i = 0; i < numbers.length; i++) { for (int j = 0; j < numbers[i].length; j++) { System.out.print(numbers[i][j] + " "); } System.out.print("\n"); }
The console output
1 2 3 4 5 6
The syntax for creating a jagged array
type[][] arrayName = new type[rowCount][];
Code that creates a jagged array of integers
int[][] numbers = new int[3][]; numbers[0] = new int[10]; numbers[1] = new int[15]; numbers[2] = new int[20];
Code that creates and initializes a jagged array of strings
String[][] titles = {{"War and Peace", "Wuthering Heights", "1984"}, {"Casablanca", "Wizard of Oz", "Star Wars", "Birdy"}, {"Blue Suede Shoes", "Yellow Submarine"}};
Code that creates and initializes a jagged array of integers
int number = 0; int[][] pyramid = new int[4][]; for (int i = 0; i < pyramid.length; i++) { pyramid[i] = new int[i+1]; for (int j = 0; j < pyramid[i].length; j++) pyramid[i][j] = number++; }
Code that prints the contents of the jagged array of integers
int[][] pyramid = new int[4][]; //... for (int i = 0; i < pyramid.length; i++) { for (int j = 0; j < pyramid[i].length; j++) { System.out.print(pyramid[i][j] + " "); } System.out.print("\n"); }
The console output
0 1 2 3 4 5 6 7 8 9
Code that uses nested foreach loops to print a jagged array
int[][] pyramid = new int[4][]; //... for (int[] row : pyramid) { for (int col : row) { System.out.print(col + " "); } System.out.print("\n"); }
The console output
0 1 2 3 4 5 6 7 8 9