CSCI206 Lab7
CSCI206 Lab7
Arrays
2. Defining an array
Arrays are defined in terms of the type of data they hold, and the number of
elements they contain. For example, we can define a String array of size 12, or an int
array of size 1000, etc. The length should be always strictly positive (>0).
Java uses integers for indexing arrays, meaning you cannot have an array of size 4.5.
This also means the maximum size − of an array should be 231= 2147483647, which
is Integer.MAX VALUE, although if you need to store this many data, you should
probably be using a different storage method.
You should also be aware that once the size of an array is set, it cannot be changed;
the array’s length is immutable.
As in most programming languages, Java arrays are zero-indexed. This means that
the first item in any array is the 0th item, and the second is the 1st, and so on.
3. Using an array
There are several ways we can declare and initialize arrays. We need to specify the
type of data that we are going to store, and we need to give our array a name.
The main difference between declaring a Java variable and a Java array, is that we
must use brackets to specify that we are talking about an array.
// declaring an integer array, called
"nums" int[] nums;
We can also decide whether to just declare the array, as in the above example, and
initialize it later, or to do both at once, in the same way that we can with variables
(see below).
// creating an empty integer array of length 10
int[] nums = new int[10];
The keyword new means to allocate enough space in its memory for 10 integers.
You can do the same thing with other data types, using the same basic format:
// creating an empty String array of length 256
String[] strings = new String[256];
Once the array is created, it will be empty array, which means each element of the
array needs to also be initialized to some value. Modern Java will silently set each
value to be 0 for the integer array, and null for the String array.
So now we want to be able to set the values of the elements in our arrays, and to do that, we
need to know how to access the elements.
4. Array elements
Each element of an array is like a variable: it has a type, a name, and contains a
value. The type is defined when we declare the array (so an integer array will only
contain integers, a boolean array will only contain booleans, etc.). Here is how we
modify an element of an array:
// Create an array of Strings of length 3
String[] strings = new String[3];
// Set the first element of the array
strings[0] = "First String";
// Set the second element
strings[1] = "This is the second element"
// Set the last element
strings[2] = "Final";
In the case of the String array, we can use all the String methods from the previous
lab on any element of the array.
We can get the array length using name_array.length, for example:
// a String array
String[] s = new String[15];
// print the length of the whole array
System.out.println(s.length);
Getting the length of an array is useful especially when we use a for loop to process
every element of the array. Here is an example where we enter the number from 1
to 12 to an array:
// an integer array int[]
array = new int[12];
// use a for-loop to initialize the elements for
(int i = 0; i < array.length; i++)
{
// initialise each element to be its index plus one
intArray[i] = i + 1;
}
Putting the iteration variable (the int i in the above example) into the square
brackets allows us to iterate through the array, and initialize every element in a
procedural way, rather than having to initialize them all individually. Notice that we
used intArray.length instead of just writing 12 as the upper limit of the for-
loop – this means that, if the requirements for the program change later, we don’t
have to go through all of our code looking for so-called “magic numbers”
Direct initialization
If you know exactly what elements are going to go into your array, Java provides us
with a shorthand way of creating and initialising an array all in one step, by using
curly braces:
// directly initialised int array
int[] arr1 = {10, 4, 327, -11, 0, 5};
// directly initialised String array
String[] arr2 = {"This", "is", "an", "array", "of",
"words"};
You cannot declare an array, and then later initialize it this way – you must do it all
in one step to take advantage of this way of creating your array.
Certain methods will also return an array of items, which you can also use to initialize
an array. For example, String has a method called split(separator) which
will take a String, find every instance of separator in it, and return an array of
Strings after splitting it up based on those instances:
// Some splittable strings
String spaceStr = "This can be split";
String commaStr = "This,can,as,well";
String otherStr = "Any string, really";
Task 1
Write a java program that asks the user to input three numbers and print the sum,
the 1st number, the 2nd number, and then the 3rd number.
If the user enters 10, 20, 30, the program will output: 60, 10,20, 30
Task 2
Write a java program that asks the user to enter 10 number, then reads an index
value between 0 and 9 (which represents an index of the array) and prints out the
value inside the element in the array at this index value. For example, for an array d,
if the user enter5, the program will output the value inside d[5].
Task 3
Write a java program that asks the user to enter 10 number and print them in the
reverse order.
Task4
Write a java program that asks the user to enter 10 number and prints the first odd
number in the array.
Task 5
Write a java program that asks the user to enter 10 number and print out the first
even number.
Task6
A palindrome is a word that is spelled the same forwards and backwards.
For example, “racecar”, “level”, “kayak”.
• Create a Java program called palindrome.java
• Ask the user to supply three palindromes in one line – Hint: look at
Scanner’s nextLine() method
• Check each word individually to see if it is a palindrome – if
you find one, print it to the screen
– Hint: look at String’s toCharArray() method
• Keep asking the user until they have supplied a set of words
containing at least one palindrome.
If you are finding it difficult, apply computer science principles: break the
problem down into smaller, achievable sub-problems. It is probably easiest
to begin by writing the code that will test whether a String is a palindrome
or not, and then adding the other parts of the program after that.