TLE-9-Lesson-5-Arrays-and-methods
TLE-9-Lesson-5-Arrays-and-methods
In programming, we often deal with multiple but related information, like quiz scores.
They are all numeric and are all categorized as individual values. If we have five quiz
scores, then we have to store the score values to different variables just to compute
their average, which is very impractical and tedious.
This is what arrays are for. Instead of having to separately store related information in
different variables (named memory locations), you can store them as a collection in just
one variable or array.
Declaring an Array
Below is the array syntax:
<data type> [] <array name>
Example:
int [ ] arrayNumbers;
String[ ] arrayNames;
char [ ] arrayLetters;
double[ ] arrayDouble;
float [ ]JarrayValue;
Initializing Arrays
Below is the syntax for creating an array of integers
int arrayNumbers [ ];
arrayNumbers = new int [5] ;
This indicates that arrayNumbers has a length of 5, meaning the array is capable
of holding or storing 5 integers.
The array index will always start with index of zero [0]. In this case, the elements of
array Numbers are 10, 120, 30, 80, and 100.
1
An array uses indexing to store and retrieve its elements. Each item in an array is called
element. Hence, if we want to display the 4th element of the array, we write:
The 4th element is at index 3 because the indexing begins with zero. Another way of
initializing an array;
The length of the array is determined by the number of values provided between braces
and separated by commas.
Example:
Always remember that array index begins with zero, so if the length of the array is 5, the
last index is 4.
Example program 1
Output
2
5.2 Methods
A method must be declared within a class. It is defined with the name of the method,
followed by parentheses (). Java provides some pre-defined methods, such
as System.out.println(), but you can also create your own methods to perform certain
actions:
Example Explained
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
In the following example, myMethod() is used to print a text (the action), when it is
called:
3
Output
The public keyword is an access modifier used for classes, attributes, methods and
constructors, making them accessible by any other class.
References:
Book:
Internet Links: