Professional Documents
Culture Documents
Arrays in Java
Problem Statement: Create and initialize 1-d array. Swap the elements of the array i.e. { a[0]
Theory:
An array is used to store a collection of data, but it is often more useful to think of an array
as a collection of variables of the same type. Instead of declaring individual variables, such
as number0,number1, ..., and number99, you declare one array variable such as numbers
and use numbers[0],numbers[1], and ..., numbers[99] to represent individual variables.
To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference. Here is the syntax for declaring an
array variable −
Syntax
or
Example
or
The above declaration establishes the fact that “num” is an array variable, no actual array
exists. It merely tells the compiler that this variable (num) will hold an array of the integer
type. To link “num” with an actual, physical array of integers, you must allocate one using
new and assign it to num .
When an array is declared, only a reference of array is created. To actually create or give
memory
to array, you create an array like this; The general form of new as it applies to one-
dimensional arrays appears as follows:
Example:
OR
NOTE:
1. The elements in the array allocated by new will automatically be initialized to zero (for
2. Obtaining an array is a two-step process. First, you must declare a variable of the desired
array type. Second, you must allocate the memory that will hold the array, using new, and
assign it to the array variable. Thus, in Java all arrays are dynamically allocated.
Array Literal
In a situation, where the size of the array and variables of array are already known, array
literals can be used.
The size of this array determines the length of the created array.
There is no need to write the new int[] part in the latest versions of Java
Each element in the array is accessed via its index. The index begins with 0 and ends at (total
array
size)-1. All the elements of array can be accessed using Java for Loop.
}
CODE:(User input)
import java.util.*;
int n, temp,i;
n = s.nextInt();
array[i] = s.nextInt();
temp=array[i];
array[i]=array[n-1];
array[n-1]=temp;
System.out.print(array[i]+" ");
}
OUTPUTS:
CODE:(INITIALIZED,NO USER INPUT)
int i, b, t;
t = array[i];
array[n - i - 1] = t;
System.out.println(array[b]);
reverse(arr, arr.length);
}
OUTPUT:
*****
EXPERIMENT 6b
Problem Statement: Create and initialize 2-D array. Calculate the sum of each column and
display
it separately
Theory:
In multi-dimensional array, Data is stored in row and column based index (also known as
matrix
form).
dataType []arrayRefVar[];
CODE:
//Initialize matrix a
int a[][] = {
{1, 2, 3},
{6, 5, 4},
{7, 8, 9}
};
col = a[0].length;
sumRow = 0;
sumCol = 0;
}
OUTPUT:
Viva questions: