Saturday 3 August 2013

13:array

Learning Objectives
After completing this session, you will be able to:
‰  Define an array
‰  Declare an array
‰  Instantiatiate an array
‰  Access array element
‰  Identify array length, array of multiple dimension, and Enum
Introduction to Arrays
Suppose you 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 inorder 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 you can apply one
variable to store a list of data and manipulate them more efficiently. This type of variable is called
an array.
An array stores multiple data items of the same data type, in a contiguous block of memory,
divided into a number of slots.
Declaring Arrays
To declare an array, write the data type, followed by a set of square brackets[], followed by the
identifier name.
For example,
int []ages;
or
int ages[];
Array Instantiation
After declaring, you must create the array and specify its length with a constructor statement.
Definitions:
Instantiation: In Java, this means creation
Constructor:
In order to instantiate an object, you need to use a constructor for this. A constructor is a method
that is called to create a certain object.
You will cover more about instantiatingobjects and constructors later.
To instantiate (or create) an array, write the new keyword, followed by the square brackets
containing the number of elements you want the array to have.
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];
Sample diagram illustrating array instantiation
You can also instantiate an array by directly initializing it with data.
For example,
int arr[] = {1, 2, 3, 4, 5};
This statement declares and instantiates an array ofintegers with five elements (initialized to the
values 1, 2, 3, 4, and 5).
Sample Program
1 //creates an array of boolean variables with identifier
2 //results. This array contains 4 elements that are
3 //initialized to values {true, false, true, false}
4
5 boolean results[] = { true, false, true, false };
6
7 //creates an array of 4 double variables initialized
8 //to the values {100, 90, 80, 75};
9
10 double []grades = {100, 90, 80, 75};
11
12 //creates an array of Strings with identifier days and
13 //initialized. This array contains 7 elements
14
15 String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”};
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.
Index number or subscript:
Assigned to each member of the array, to allow the program to access an individual member of the
array
Begins with zero and progress sequentially by whole numbers to the end of the array
Note:Elements inside your array are from zero to (sizeOfArray-1).
For example, in the given array you have declared a while ago (see slide 10), you 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]);
Note: Once an array is declared and constructed, the stored value of each member of the array
will be initialized to zero for number data.
For reference data types such as Strings, they 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 your code is shorter.
1 public class ArraySample{
2 public static void main( String[] args ){
3 int[] ages = new int[100];
4 for( int i=0; i<100; i++ ){
5 System.out.print( ages[i] );
6 }
7 }
8 }
Coding Guidelines
It is usually better to initialize orinstantiate 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];
The elements of an n-element array have indexes fromzero to n-1. Note that there is no array
element arr[n]! This will result in an array-index-out-of-bounds exception.
Remember you cannot resize an array.
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 ofthe array. It can be applied by writing,
arrayName.length
1 public class ArraySample {
2 public static void main( String[] args ){
3 int[] ages = new int[100];
4
5 for( int i=0; i<ages.length; i++ ){
6 System.out.print( ages[i] );
7 }
8 }
9 }
Coding Guidelines
‰  When creating for loops to process the elements of an array, use the length field of the
array object in the condition statement of the for loop. This will allow the loop to adjust
automatically for different-sized arrays.
‰  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];
Multidimensional Arrays
‰  Multidimensional arrays are implemented as arrays of arrays.
‰  Multidimensional arrays are declared byappending 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 an
one dimensional array.
For example, to access the first element in the first row of the array dogs, you write,
System.out.print( dogs[0][0] );
This will print the String "terry" on the screen.
Enum
‰  An enum type is a type whose fields consist of a fixed set of constants.
‰  Common examples include compass directions (values of NORTH, SOUTH, EAST,
and WEST) and the days of the week.
‰  As they are constants, the names of the fields of an enum type are in uppercase
letters.
enum Keyword
‰  In the Java programming language, you define an enum type by using the enum
keyword.
‰  For example, you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
enum Type
‰  You should use enum types any time you need to represent a fixed set of constants,
which includes natural enum types such as the planets in your solar system and data
sets where you know all possible values at compile time
‰  For example, the choices on a menu, command line flags, and so on
‰  Java programming language enum types are much more powerful than their
counterparts in other languages.
‰  The enum declaration defines a class (called an enum type).
‰  The enum class body can include methods and other fields.
‰  The compiler automatically adds some special methods when it creates an enum.
‰  For example, they have a static values method that returns an array containing all of
the values of the enum in the order they are declared. This method is commonly used
in combination with the for-each construct to iterate over the values of an enum type.
Example: enum in for Loop
For example, the following code iterates over all the planets in the solar system.
for (Planet p : Planet.values()) {
System.out.println(“Your weight on ” + p + “ is : ”,
+ p.surfaceWeight(mass));
}
Key Points on enum and its Constructor
‰  All enums implicitly extend java.lang.Enum.
‰  As Java does not support multiple inheritance, an enum cannot extend anything else.
‰  The constructor for an enum type must be package-private or private access.
‰  It automatically creates the constants thatare defined at the beginning of the enum
body.
‰  You cannot invoke an enum constructor on yourself.
Detailed Example
Here is some code that shows you how to apply the Day enum defined earlier:
public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}
Output
The output is:
Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.
Try It Out
Problem Statement:
Consider the following :
Bird myBird = new Bird();
myBird.name = “Parrot”;
From the preceding code, you have created a Bird object and used the dot operator on the
reference variable myBird to access the name variable. You can further use the myBird reference
to get the bird to sing() or fly()as given below:
cuckoo.sing();
cuckoo.fly();
What happens if the Bird is in a Bird array? You can access the instance variables of Bird and
methods using the dot operator, but on what?
Code:
class Bird {
String name;
public void sing() { };
public static void main(String[] args) {
Bird[] myBirds = new Bird[3];
myBirds[0] = new Bird();
myBirds[0].name = “Parrot”;
myBirds[0].sing();
}
}
Refer File Name: Bird.javato obtain soft copy of the program code
How It Works:
‰  When the Bird is in an array, you do not have an actual variable name (like “myBird”).
‰  Instead, you apply array notation and the dotoperator on an object at a particular
index (position) in the array.
‰  For example myBirds[0].name = “Parrot”;
Tips and Tricks:
Can a method declare multiple return values? Or is there some way to return more than one
value?
Solution:A method can declare only one return value, but, if you want to return, say, three int
values, then the declared return type can be an int array. Stuff those ints into the array, and pass it
on back.
Summary
‰  Arrays can hold primitives or objects, but the array itself is always an object.
‰  When you declare a array, the square brackets can be placed left side or right side of
its name.
‰  You must include the size of an array when you construct it (using new) unless you
are creating an anonymous array.
‰  You’ll get a NullPointerException if you try to use an array element in an object array,
if that element does not refer to a real object.
‰  Arrays are indexed beginning with zero.
‰  An ArrayIndexOutOfBoundsException occurs if you use a bad index value.
‰  The last index you can access is always one less than the length of the array.
‰  Multidimensional arrays are just arrays of arrays.
‰  The dimensions in a multidimensionalarray can have different lengths.
Test Your Understanding
1.Which one of the following is true?
a)All elements of an array should be of the same type.
b)The ‘for’ loop shall be used to initialize the elements of an array.
c)You cannot create a larger array and supply fewer values.
d)All the earlier options are true.
2.Which one of the following is true?
a)A two-dimensional array is stored internally as a one-dimensional array.
b)The range of an array index is checked in Java.
c)More than two dimensions are allowed in Java.
d)All the earlier options are true.

No comments:

Post a Comment