12 - Arrays

Get an introduction to or review of arrays in Java programming.

Code HuntJava
1.0x

12 - Arrays

Created 3 years ago

Duration 0:10:28
lesson view count 69
Get an introduction to or review of arrays in Java programming.
Select the file type you wish to download
Slide Content
Tags: Code Hunt Java
  1. Arrays

    Slide 2 - Arrays

  2. Arrays

    Slide 3 - Arrays

    • An array is a collection of values stored as a single unit.
    • All array elements must be of the same type.
    • The type and number of elements must be declared when the array is created.
    • The element type and size of an array cannot be changed.
    • Arrays can be created in two ways:
    • <type>[] <name> = {<value>, <value>, …, <value>};
    • <type>[] <name> = new <type>[<size>];
    • If no values are given, elements are default-initialized
    • 0, '\0', false, or null
    • An entire array can be used as a parameter or return value as a single unit.
    • Specify the name of the array, but no brackets.
  3. Accessing Array Elements

    Slide 4 - Accessing Array Elements

    • Individual elements of an array can be accessed using an indexer.
    • New values can be assigned or old values referenced.
    • <name>[<position>] = <value>;
    • System.out.println(<name>[<position>]);
    • Indexes begin at 0.
    • The last element is at <name>[<name>.length – 1]
  4. Array Examples

    Slide 5 - Array Examples

    • int[] nums = new int[5];
    • String[] words = new String[2];
    • int[] primes = {2, 3, 5, 7, 11, 13};
    • String[] pets = {"cat", "dog", "hamster", "parakeet"};
    • nums[2] = 4;System.out.println(nums[2]);System.out.println(nums[3]);nums[1] = 3.14;
    • System.out.println(pets[0]);pets[0] = "hedgehog";System.out.println(pets[0]);System.out.println(pets[4]);
  5. Traversing Arrays

    Slide 6 - Traversing Arrays

    • When working with arrays, it is common to go through each element one by one and perform some operation. This is called traversing the array.
    • int[] nums = new int[6];
    • for (int i = 0; i < nums.length; i++) {
    • System.out.println(nums[i]);
    • }
    • Remember to start at 0.
    • Notice the use of length in the for loop test.
  6. Traversal Examples

    Slide 7 - Traversal Examples

    • String[] fruit = {"apple", "orange", "watermelon", "strawberry"};
    • for (int i = 0; i < fruit.length; i++) { System.out.println(fruit[i].charAt(0));}
    • int[] nums = new int[6];
    • for (int i = 0; i < nums.length; i++) { nums[i] = 5 * i;}
    • int[] values = {3, 6, 9, 12, 15, 18};int sum = 0;
    • for (int i = 0; i < values.length; i++) { sum += values[i];}
    • System.out.println(sum);
    • String[] vehicles = {"car", "truck", "van"};
    • for (int i = vehicles.length – 1; i >= 0; i--) { System.out.println(vehicles[i]);}