You are on page 1of 10

COMSATS University Islamabad

Wah Campus
ALGORITHMS AND DATA STRUCTURES

Assignment / Arrays in JAVA


SOLUTION
Total Marks: 50

Q1. CLO2, PLO(a)-1


Q2. CLO1, PLO(b)-1
Q3. CLO1, PLO(a)-1
Q4. CLO2, PLO(b)-1
Q5. CLO2, PLO(a)-1
Q6. CLO2, PLO(b)-1
Q7. CLO1, PLO(b)-1
Q8. CLO1, PLO(b)-1
Q9. CLO2, PLO(1)-1
Q10. CLO2, PLO(a)-1
Q5. CLO2, PLO(a)-1
Q6. CLO1, PLO(a)-1
Q7. CLO2, PLO(b)-1
Q8. CLO1, PLO(b)-1
Q9. CLO2, PLO(1)-1
Q10. CLO2, PLO(a)-1

NOTE: Whichever book/material you follow to answer the following questions, copying is
strictly not allowed and will result in negative marking. All answers should be written in your
own words. Similarly codes are also not allowed to copy, they should be used as a help to write
your own example codes.

Q1. Arrays in Java work differently than they do in other languages. Clear this with the help of a
one dimensional example program in Java.

A one-dimensional array is a list of like-typed variables. To create an array, first must create an
array variable of the desired type. The general form of a one dimensional array declaration is
type var-name[ ];
Here, type declares the base type of the array. Thus, the base type for the array determines what
type of data the array will hold. For example, the following declares an array named
month_days with the type “array of int”:
int month_days[];
Although this declaration establishes the fact that month_days is an array variable, no array
actually exists. In fact, the value of month_days is set to null, which represents an array with no
value. To link month_days with an actual, physical array of integers, must allocate one using
new and assign it to month_days. new is a special operator that allocates memory. The general
form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type[size];
Here, type specifies the type of data being allocated, size specifies the number of elements in the
array, and array-var is the array variable that is linked to the array. That is, to use new to allocate
an array, you must specify the type and number of elements to allocate.
The elements in the array allocated by new will automatically be initialized to zero.
This example allocates a 12-element array of integers and links them to month_days.
month_days = new int[12];

Arrays can be initialized when they are declared. An array initializer is a list of comma-
separated expressions surrounded by curly braces. The array will automatically be created large
enough to hold the number of elements specified in the array initializer. There is no need to use
new. For example, to store the number of days in each month, the following code creates an
initialized array of integers:
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
Java strictly checks to make sure not to store or reference values outside of the range of the
array. The Java run-time system will check to be sure that all array indexes are in the correct
range. (In this regard, Java is fundamentally different from C/C++, which provide no run-time
boundary checks.) For example, the run-time system will check the value of each index into
month_days to make sure that it is between 0 and 11 inclusive. If you try to access elements
outside the range of the array (negative numbers or numbers greater than the length of the array),
you will cause a run-time error.
Here is one more example that uses a one-dimensional array. It finds the average of
a set of numbers.
// Average an array of values.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}

Q2. Multidimensional arrays are arrays. Give a conceptual view of 4 by 5 two dimensional array.
Also give an example program in Java to manipulate this array.
In Java, multidimensional arrays are actually arrays of arrays. These look and act like regular
multidimensional arrays. However, there are a couple of subtle differences. To declare a
multidimensional array variable, specify each additional index using another set of square
brackets. For example, the following declares a two-dimensional array variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an
array of arrays of int. Conceptually, this array will look like the one shown in Figure.

Figure. A conceptual view of a 4 by 5, two-dimensional array


The following program numbers each element in the array from left to right, top to bottom, and
then displays these values:
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19

Q3. Two dimensional arrays can be given different dimensions. Give a conceptual view of this
concept along with an example program in Java.
While allocating memory for a multidimensional array, it needs only to specify the memory for
the first (leftmost) dimension. Remaining dimensions can be allocated separately. For example,
this following code allocates memory for the first dimension of twoD when it is declared. It
allocates the second dimension manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];

While there is no advantage to individually allocating the second dimension arrays in this
situation, there may be in others. For example, while allocating dimensions manually, there is no
need to allocate the same number of elements for each dimension. For example, the following
program creates a two dimensional array in which the sizes of the second dimension are unequal.

class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0
12
345
6789
The array created by this program looks like this:

THE JAVA LANGUAGE


Q4. Explain how a three dimensional array is implemented in Java.

Same rules are followed to implement a three dimensional array in Java as using two
dimensional arrays. It is necessary to initialize the first dimension, rest can be given different.
The following program creates a 3 by 4 by 5, three-dimensional array. It then loads each element
with the product of its indexes. Finally, it displays these products.

class threeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
This program generates the following output:
00000
00000
00000
00000

00000
01234
02468
0 3 6 9 12

00000
02468
0 4 8 12 16
Q5. Array in Java can be implemented as object. Because of this, a special array attribute length
can be used to give size of array. Show the use of this attribute with the help of an example
program in Java.

Arrays are implemented as objects. Because of this, there is a special array attribute to take
advantage of. Specifically, the size of an array—that is, the number of elements that an array can
hold—is found in its length instance variable. All arrays have this variable, and it will always
hold the size of the array. Here is a program that demonstrates this property:

class Length {
public static void main(String args[]) {
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}
This program displays the following output:
length of a1 is 10
length of a2 is 8
length of a3 is 4
Size of each array is displayed. The value of length has nothing to do with the number of
elements that are actually in use. It only reflects the number of elements that the array is
designed to hold.

Q6. ArrayList class supports dynamic arrays that can grow as needed. Discuss the class and its
constructors. Also show the use of this class with an example program in Java.

ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a
fixed length. After arrays are created, they cannot grow or shrink, which means that it must be
known in advance how many elements an array will hold. But, sometimes, it is not known until
run time precisely how large of an array is needed. To handle this situation, ArrayList is a
variable-length array of object references. That is, an ArrayList can dynamically increase or
decrease in size. Array lists are created with an initial size. When this size is exceeded, the
collection is automatically enlarged. When objects are removed, the array may be shrunk.
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)
The first constructor builds an empty array list. The second constructor builds an array list that is
initialized with the elements of the collection c. The third constructor builds an array list that has
the specified initial capacity. The capacity is the size of the underlying array that is used to store
the elements. The capacity grows automatically as elements are added to an array list.
THE JAVA LIBRARY
The following program shows a simple use of ArrayList. An array list is created, and then
objects of type String are added to it. The list is then displayed. Some of the elements are
removed and the list is displayed again.

import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " +al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}
The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Notice that a1 starts out empty and grows as elements are added to it. When elements
are removed, its size is reduced.

Q7. Show with the use of a Java example program that an actual array can be obtained from
ArrayList class. Also list the reasons for it.

When working with ArrayList, sometimes it is required to obtain an actual array that contains
the contents of the list. This can be done by calling toArray( ).
Several reasons exist to convert a collection into an array such as:
■ To obtain faster processing times for certain operations.
■ To pass an array to a method that is not overloaded to accept a collection.
■ To integrate the newer, collection-based code with legacy code that does not understand
collections.

Whatever the reason, converting an ArrayList to an array is a trivial matter, as the following
program shows:

import java.util.*;
class ArrayListToArray {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// Add elements to the array list
al.add(new Integer(1));
al.add(new Integer(2));
al.add(new Integer(3));
al.add(new Integer(4));
System.out.println("Contents of al: " + al);
// get array
Object ia[] = al.toArray();
int sum = 0;
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}
The output from the program is shown here:
Contents of al: [1, 2, 3, 4]
Sum is: 10

Q8. List down at least ten methods of Arrays class. Only prototypes and two to three lines
description of each method is required to be written.

The binarySearch( ) method uses a binary search to find a specified value. This method must be
applied to sorted arrays. It has the following forms:
static int binarySearch(byte[ ] array, byte value)
static int binarySearch(char[ ] array, char value)
static int binarySearch(double[ ] array, double value)
static int binarySearch(float[ ] array, float value)
static int binarySearch(int[ ] array, int value)

Here, array is the array to be searched and value is the value to be located.

The equals( ) method returns true if two arrays are equivalent. Otherwise, it returns false. The
equals( ) method has the following forms:
static boolean equals(boolean array1[ ], boolean array2[ ])
static boolean equals(byte array1[ ], byte array2[ ])
static boolean equals(char array1[ ], char array2[ ])
static boolean equals(double array1[ ], double array2[ ])
static boolean equals(float array1[ ], float array2[ ])

Here, array1 and array2 are the two arrays that are compared for equality.
Q9. Explain the use of some methods of Arrays class with the help of a Java program along with
its output.

The following program explains how to use some of the methods of the Arrays class:
import java.util.*;
class ArraysDemo {
public static void main(String args[]) {
// allocate and initialize array
int array[] = new int[10];
for(int i = 0; i < 10; i++)
array[i] = -3 * i;
// display, sort, display
System.out.print("Original contents: ");
display(array);
Arrays.sort(array);
System.out.print("Sorted: ");
display(array);
// fill and display
Arrays.fill(array, 2, 6, -1);
System.out.print("After fill(): ");
display(array);
// sort and display
Arrays.sort(array);
System.out.print("After sorting again: ");
display(array);
// binary search for -9
System.out.print("The value -9 is at location ");
int index =
Arrays.binarySearch(array, -9);
System.out.println(index);
}
static void display(int array[]) {
for(int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println("");
}
}
The following is the output from this program:
Original contents: 0 -3 -6 -9 -12 -15 -18 -21 -24 -27
Sorted: -27 -24 -21 -18 -15 -12 -9 -6 -3 0
After fill(): -27 -24 -1 -1 -1 -1 -9 -6 -3 0
After sorting again: -27 -24 -9 -6 -3 -1 -1 -1 -1 0
The value -9 is at location 2

Q10. There are a number of C++ features that Java does not support. Discuss them in bullets.

 Java does not include structures or unions. These were felt to be redundant since the class
encompasses them.
■ Java does not support operator overloading. Operator overloading is sometimes a source of
ambiguity in a C++ program, and the Java design team felt that it causes more trouble than
benefit.
■ Java does not include a preprocessor nor does it support the preprocessor directives. The
preprocessor plays a less important role in C++ than it does in C. The designers of Java felt that
it was time to eliminate it entirely.
■ Java does not perform any automatic type conversions that result in a loss of precision. For
example, a conversion from long integer to integer must be explicitly cast.
■ All the code in a Java program is encapsulated within one or more classes. Therefore, Java
does not have what you normally think of as global variables or global functions.
■ Java does not allow default arguments. In C++, you may specify a value that a parameter will
have when there is no argument corresponding to that parameter when the function is invoked.
This is not allowed in Java.
■ Java does not support the inheritance of multiple super classes by a subclass.
■ Although Java supports constructors, it does not have destructors. It does, however, add the
finalize( ) function.
■ Java does not support typedef.
■ It is not possible to declare unsigned integers in Java.
■ Java does not allow the goto.
■ Java does not have the delete operator.
■ The << and >> in Java are not overloaded for I/O operations.
■ In Java, objects are passed by reference only. In C++, objects may be passed by value or by
reference.

You might also like