Core Java
core8ArraysDemo
- Path
- pkg1core/core8ArraysDemo.java
- Package
- pkg1core
- Study order
- 7
- Run
- Single-file source launch
- Command
- java pkg1core/core8ArraysDemo.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core8ArraysDemo.java5 * ---------------6 * 1D and 2D arrays, initialization, iteration, and java.util.Arrays utilities.7 *8 * EXPLANATION:9 * - Arrays are fixed-size, zero-indexed, and store one type.10 * - `arr.length` is a field (not a method).11 * - java.util.Arrays provides sort, binarySearch, fill, copyOf, toString, etc.12 */13import java.util.Arrays;14 15public class core8ArraysDemo {16 public static void main(String[] args) {17 // Declaration + initialization18 int[] a = {5, 3, 8, 1, 9, 2};19 int[] b = new int[3]; // defaults to all zeros20 b[0] = 10; b[1] = 20; b[2] = 30;21 22 System.out.println("a = " + Arrays.toString(a));23 System.out.println("b = " + Arrays.toString(b) + " (length " + b.length + ")");24 25 // Sorting + binary search (array must be sorted for search)26 int[] sorted = a.clone();27 Arrays.sort(sorted);28 System.out.println("sorted = " + Arrays.toString(sorted));29 System.out.println("index of 8 = " + Arrays.binarySearch(sorted, 8));30 31 // Fill and copy32 int[] filled = new int[4];33 Arrays.fill(filled, 7);34 System.out.println("filled = " + Arrays.toString(filled));35 System.out.println("copyOf(a,3) = " + Arrays.toString(Arrays.copyOf(a, 3)));36 37 // 2D array (array of arrays)38 int[][] grid = {39 {1, 2, 3},40 {4, 5, 6}41 };42 System.out.println("2D grid:");43 for (int[] row : grid) {44 System.out.println(" " + Arrays.toString(row));45 }46 System.out.println("grid[1][2] = " + grid[1][2]);47 48 // Manual reverse in place49 for (int i = 0, j = a.length - 1; i < j; i++, j--) {50 int t = a[i]; a[i] = a[j]; a[j] = t;51 }52 System.out.println("reversed a = " + Arrays.toString(a));53 }54}