0% found this document useful (0 votes)
135 views5 pages

Notes5 Java Arrays

This document discusses Java arrays. It defines arrays as variables that can store multiple values of the same data type. The key points covered include: - Declaring and initializing arrays using syntax such as int[] array = new int[size]; - Accessing array elements using indexes from 0 to length-1 - Finding the length of an array using arrayName.length - Storing multi-dimensional data in arrays of arrays - Examples of iterating through arrays using for loops The document provides examples and best practices for working with one and multi-dimensional arrays in Java. Exercises are also included to reinforce concepts like printing array values, finding maximum values, and accessing elements in multi-dimensional arrays.

Uploaded by

seniorhigh LIS
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
135 views5 pages

Notes5 Java Arrays

This document discusses Java arrays. It defines arrays as variables that can store multiple values of the same data type. The key points covered include: - Declaring and initializing arrays using syntax such as int[] array = new int[size]; - Accessing array elements using indexes from 0 to length-1 - Finding the length of an array using arrayName.length - Storing multi-dimensional data in arrays of arrays - Examples of iterating through arrays using for loops The document provides examples and best practices for working with one and multi-dimensional arrays in Java. Exercises are also included to reinforce concepts like printing array values, finding maximum values, and accessing elements in multi-dimensional arrays.

Uploaded by

seniorhigh LIS
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 5

J.E.D.I.

Java Arrays
1 Objectives
In this section, we will be discussing about Java Arrays. First, we are going to define what arrays are,
and then we are going to discuss on how to declare and use them.

At the end of the lesson, the student should be able to:


 Declare and create arrays

 Access array elements


 Determine the number of elements in an array
 Declare and create multidimensional arrays

2 Introduction to arrays
In the previous sections, we have discussed on how to declare different variables using the primitive
data types. In declaring variables, we often use a unique identifier or name and a datatype. In order to
use the variable, we call it by its identifier name.

For example, we have here three variables of type int with different identifiers for each variable.

int number1;
int number2;
int number3;

number1 = 1;
number2 = 2;
number3 = 3;

As you can see, it seems like a tedious task in order to just initialize and use the variables especially if
they are used for the same purpose. In Java and other programming languages, there is one capability
wherein we can use one variable to store a list of data and manipulate them more efficiently. This type
of variable is called an array.

Figure 1: Example of an Integer Array


An array stores multiple data items of the same datatype, in a contiguous block of memory, divided
into a number of slots. Think of an array as a stretched variable – a location that still has one identifier
name, but can hold more than one value.

3 Declaring Arrays
Arrays must be declared like all variables. When declaring an array, you list the data type, followed by
a set of square brackets[], followed by the identifier name. For example,

int []ages;

or you can place the brackets after the identifier. For example,

int ages[];

After declaring, we must create the array and specify its length with a constructor statement. This
process in Java is called instantiation (the Java word for creates). In order to instantiate an object,
we need to use a constructor for this. We will cover more about instantiating objects and constructors

Introduction to Programming III theboi 1


J.E.D.I.
later. Take note, that the size of an array cannot be changed once you've initialized it. For example,

//declaration
int ages[];

//instantiate object
ages = new int[100];

or, can also be written as,

//declare and instantiate object


int ages[] = new int[100];

In the example, the declaration tells the Java Compiler that the identifier ages will be used as the
name of an array containing integers, and to create or instantiate a new array containing 100
elements.

Instead of using the new keyword to instantiate an array, you can also automatically declare, construct
and assign values at once.

Figure 2: Instantiating Arrays

Examples are,

//creates an array of boolean variables with ientifier


//results. This array contains 4 elements that are
//initialized to values {true, false, true, false}
boolean results[] ={ true, false, true, false };

//creates an array of 4 double variables initialized


//to the values {100, 90, 80, 75};
double []grades = {100, 90, 80, 75};

//creates an array of Strings with identifier days and


//initialized. This array contains 7 elements
String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”};

Introduction to Programming III theboi 2


J.E.D.I.

4 Accessing an array element


To access an array element, or a part of the array, you use a number called an index or a subscript.

An index number or subscript is assigned to each member of the array, allowing the program and
the programmer to access individual values when necessary. Index numbers are always integers.
They begin with zero and progress sequentially by whole numbers to the end of the array .
Take note that the elements inside your array is from 0 to (sizeOfArray-1).

For example, given the array we declared a while ago, we have

//assigns 10 to the first element in the array


ages[0] = 10;

//prints the last element in the array


System.out.print(ages[99]);

Take note that once an array is declared and constructed, the stored value of each member of the
array will be initialized to zero for number data. However, reference data types such as Strings are not
initialized to blanks or an empty string “”. Therefore, you must populate the String arrays explicitly.

The following is a sample code on how to print all the elements in the array. This uses a for loop, so
our code is shorter.

public class ArraySample{


public static void main( String[] args ){

int[] ages = new int[100];

for( int i=0; i<100; i++ ){


System.out.print( ages[i] );
}
}
}

Coding Guidelines:

1. It is usually better to initialize or instantiate the array right away after you declare it. For example,
the declaration,
int []arr = new int[100];
is preferred over,
int []arr;
arr = new int[100];
2. The elements of an n-element array have indexes from 0 to n-1. Note that there is no array
element arr[n]! This will result in an array-index-out-of-bounds exception.
3. You cannot resize an array.

5 Array length
In order to get the number of elements in an array, you can use the length field of an array. The
length field of an array returns the size of the array. It can be used by writing,

arrayName.length

For example, given the previous example, we can re-write it as,

public class ArraySample


{
public static void main( String[] args ){

int[] ages = new int[100];

Introduction to Programming III theboi 3


J.E.D.I.

for( int i=0; i<ages.length; i++ ){


System.out.print( ages[i] );
}
}
}

Coding Guidelines:

1. When creating for loops to process the elements of an array, use the array object's length field in
the condition statement of the for loop. This will allow the loop to adjust automatically for different-
sized arrays.
2. Declare the sizes of arrays in a Java program using named constants to make them easy to change.
For example,
final int ARRAY_SIZE = 1000; //declare a constant
...
int[] ages = new int[ARRAY_SIZE];

6 Multidimensional Arrays
Multidimensional arrays are implemented as arrays of arrays. Multidimensional arrays are declared by
appending the appropriate number of bracket pairs after the array name. For example,

// integer array 512 x 128 elements


int[][] twoD = new int[512][128];

// character array 8 x 16 x 24
char[][][] threeD = new char[8][16][24];

// String array 4 rows x 2 columns


String[][] dogs = {{ "terry", "brown" },
{ "Kristin", "white" },
{ "toby", "gray"},
{ "fido", "black"}
};

To access an element in a multidimensional array is just the same as accessing the elements in a one
dimensional array. For example, to access the first element in the first row of the array dogs, we write,

System.out.print( dogs[0][0] );

This will print the String "terry" on the screen.

7 Exercises
7.1 Days of the Week
Create an array of Strings which are initialized to the 7 days of the week. For Example,

String days[] = {“Monday”, “Tuesday”….};

Using a while-loop, print all the contents of the array. (do the same for do-while and for-loop)

7.2 Greatest number(ASSIGNMENT)


Using BufferedReader or JOptionPane, ask for 10 numbers from the user. Use an array to store the
values of these 10 numbers. Output on the screen the number with the greatest value.

Introduction to Programming III theboi 4


J.E.D.I.
7.3 Addressbook Entries
Given the following multidimensional array that contains addressbook entries:

String entry = {{"Florence", "735-1234", "Manila"},


{"Joyce", "983-3333", "Quezon City"},
{"Becca", "456-3322", "Manila"}};
Print the following entries on screen in the following format:

Name : Florence
Tel. # : 735-1234
Address : Manila

Name : Joyce
Tel. # : 983-3333
Address : Quezon City

Name : Becca
Tel. # : 456-3322
Address : Manila

7.4 class OddRing(ASSIGNMENT)


Study the given code. Through its output determine what does the program do.
import java.io.*;

public class OddRing{


public static void main(String[] args){
BufferedReader inData = new BufferedReader (new InputStreamReader(System.in));
int arr[];
int input;
int i,j;
String key="";
System.out.println("Enter a positive even integer:");
try{
key=inData.readLine();
}catch(IOException e)
{
System.out.println("Error in getting input");
}
input = Integer.parseInt(key);
arr = new int[input];
for(i=0; i<arr.length; i++){
arr[i] = (int) (Math.random() * input);
for(j = 0; j < i; j++){
if(arr[i] == arr[j] || (arr[i] + arr[i-1]) % 2 ==0){
i--;
break;
}
}
}

for(i=0; i<arr.length; i++)


System.out.print(arr[i] + " ");

Introduction to Programming III theboi 5

You might also like