1. A class Collection contains an array of 100 integers. Using the following class description, create an array with common elements from two integer arrays. Some of the members of the class are given below: Class name : Collection Data members : ar[] : integer array of 100 elements len : length of the array Member methods : Collection() : default constructor Collection(int ) : parameterized constructor to assign the length of the array void input() : reads array elements Collection common(Collection): return the Collection containing the common Elements of current Collection and the collection object passed as parameter. void display() : displays the array Collection elements Write the main() method to generate the necessary output.
Answers
Answer:
Array means collection. In Java also, an array is a collection of similar things. eg.- an array of int will contain only integers, an array of double will contain only doubles, etc.
Why array?
Suppose you want to store the marks of 100 students. Obviously, you need a better approach over defining 100 different variables and using them. Here the role of array comes in.
Declaration of array
int[] z = new int[10];
It looks similar to defining a variable and actually it is. Here we are declaring 10 variables at one go.
Let's understand this
int[] z is representing that 'z' is an array of type integer ( as [ ] represents array ) and 'new int[10]' is representing that is it an array of 10 integers. In other words, we can say that 'z' is a collection of 10 integers.
Now, a question comes to mind, how to use these 10 variables?
The pictorial view is like this.
Each array has some array elements. In the above array example, there are 10 array elements.
0,1,2....8,9 are indices. It is like, these are the identities of 10 different array elements. Index starts from 0. So, the first element of the array has index 0, the second element has index 1 and so on.
Index of an array starts with 0.
element 2 3 15 8 48 13
index 0 1 2 3 4 5
array in java
Normally, we declare and assign a value to a variable as follows.
int x;
x = 50;
For an array, we do the same as follows.
int[] z = new int[10];
z[0] = 50;
int[] z = new int[10]; - This line will make an array of 10 integers.
z[0] = 50; - z[0] represents the first element of the array 'z' and a value of 50 is assigned to it. So, the first element (z[0]) of the array has value 50.