Arrays - PowerPoint PPT Presentation

About This Presentation
Title:

Arrays

Description:

chars the value '' Strings and other object the value null ... By doing row = new char[]; you only get an address in the computer's memory... – PowerPoint PPT presentation

Number of Views:23
Avg rating:3.0/5.0
Slides: 11
Provided by: SUPE106
Category:
Tags: arrays | chap1 | chars

less

Transcript and Presenter's Notes

Title: Arrays


1
Arrays
  • Lists, matrices and more

2
Arrays
  • Arrays are objects, like Strings
  • You must declare, create and initialize
  • Ex char row
  • row new char5
  • row0 'A'
  • row1 'B'
  • row2 'C'
  • row3 'D'
  • row4 'E'

3
Arrays
  • Or you can declare, create and initialise in one
    line
  • Ex char row 'A', 'B', 'C', 'D', 'E'
  • Note the Java compiler will initialize an array
    for you in case you forget, bad habit!
  • ints and doubles will have the value 0
  • booleans the value false
  • chars the value ''
  • Strings and other object the value null

4
  • If you try to print it, this is what happens
  • System.out.println("Here is the row " row)
  • You cannot print it because row is only a memory
    address!!!

5
  • Here how it works
  • By doing row new char you only get an
    address in the computers memory
  • To access the elements of the row, you must
    specify which one using the and an index Ex
    row1
  • The index starts at 0
  • instead if you try
  • System.out.println("Here is 1st element "
    row0)
  • then you would get

6
Result
7
Looping with Arrays
  • To access all the elements, you can use a loop!
  • Ex
  • for (i 0 i lt 5 i)
  • System.out.println("Here is the " i "
    element " rowi)

8
Result
9
Assignment 3
  • Write a program that uses an array containing all
    the months of the year. Using a for loop,
    display all the months on the console
  • Hint you want to create an array of Strings,
    which are also objects

10
Expected result
Write a Comment
User Comments (0)
About PowerShow.com