>
Arrays in Java: (Part 1)
Introduction:
- So far, we have only used simple variables to store values of different data types. However, in certain situations, it will be easier to write programs that uses list type structure to store similar type of data.
- For example, if we want to record the student marks for a class of 60 students, we have to create variables like student_1, student_2, student_3… student_60. (Similarly, if we are to store the details like Student_Name, Student_Email of N number of students, its hard to store information in variables) This is tedious and it increases the complexity and length (number of Lines Of Code: LOC of programs).
- This problem can be simplified by using arrays that uses a common name with a subscript representing the index of each element. If we use array for storing marks of 60 students, it will go like this: student[1], student[2], student[3]… student[60].
- An array is an ordered sequence of finite data items of the same data type that shares a common name. It is a collection of similar kind of data type (or it hold values of homogeneous type). Each individual data item of array is known as element of array. These elements are stored in the subsequent memory location starting from the first memory block.
- Index of array is the position of array element. The index (or location) of array starts from zero always (0). So we can say that the first element of array is at position 0 in array. That is if I want to refer to the first student, it will be at location 0 (e.g, student[0]=first element of array, student[1] = second element of array, etc..). And the last index of array is always size-1. If the size of array is 60, the last element will be at position 59. That is student[59] = last element of array.
- An array can be one dimensional or two dimensional or even multi-dimensional. One dimensional array uses a single index and two dimensional array uses two indexes and so on. One dimensional array has rank “one”, two dimensional array has rank “two” and so on.
Creating arrays (any dimension):
- An array must be created before using its elements in a program (Just like our simple variables). Creating an array involves following steps:
- Declaration
- Initialization
- Assigning values
Comments
Post a Comment