You are on page 1of 10

VAIBHAVI WELIS SECMPNB

ROLL NO.:245 192123


EXPERIMENT NO.:6(a&b)
EXPERIMENT 6a

Arrays in Java

Aim: WAP to reverse 1-d array without using second array

Problem Statement: Create and initialize 1-d array. Swap the elements of the array i.e. { a[0]

is swapped with a[n-1], and so on..], to get the resultant array

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.

Declaring Array 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

dataType[] array_name; // preferred way.

or

dataType array_name[]; // works but not preferred way.

Example

double[] num; // preferred way.

or

double num[]; // works but not preferred way.

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 .

Instantiating an Array in Java

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:

var-name = new type [size];


Here, type specifies the type of data being allocated, size specifies the number of elements
in the array, and var-name is the name of 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.

Example:

int num[]; //declaring array

num = new int[20]; // allocating memory to array

OR

int[] num = new int[20]; // combining both statements in one

NOTE:

1. The elements in the array allocated by new will automatically be initialized to zero (for

numeric types), false (for boolean), or null (for reference types).

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.

int[] num = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; // Declaring array literal

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

Accessing Java Array Elements using for Loop

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.

Example: Accessing the elements of the specified array

for (int i = 0; i < arr.length; i++)

System.out.println("Element at index " + i + ": "+ arr[i]);

}
CODE:(User input)

import java.util.*;

public class Rev

public static void main(String[] args)

int n, temp,i;

Scanner s = new Scanner(System.in);

System.out.print("Enter number of elements in the array:");

n = s.nextInt();

int array[] = new int[n];

System.out.println("Enter "+n+" elements ");

for( i=0; i < n; i++)

array[i] = s.nextInt();

for( i=0;i<n ; i++,n--)

temp=array[i];

array[i]=array[n-1];

array[n-1]=temp;

System.out.println("Reverse of an array is :");

for( i=0; i < array.length; i++)

System.out.print(array[i]+" ");

}
OUTPUTS:
CODE:(INITIALIZED,NO USER INPUT)

/* Program that reverses array in less number of swaps*/

public class Revers {

/*function swaps the array's first element with last element,

second element with last second element and so on*/

static void reverse(int array[], int n)

int i, b, t;

for (i = 0; i < n/2 ; i++) {

t = array[i];

array[i] = array[n - i - 1];

array[n - i - 1] = t;

/*printing the reversed array*/

System.out.println("Reversed array is: \n");

for (b = 0; b < n; b++) {

System.out.println(array[b]);

public static void main(String[] args)

int [] arr = {100, 270, 360, 450, 540};

reverse(arr, arr.length);

}
OUTPUT:

*****
EXPERIMENT 6b

Aim: To calculate sum of column elements for 2-D array

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).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)

dataType [][]arrayRefVar; (or)

dataType arrayRefVar[][]; (or)

dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

CODE:

public class Sum

public static void main(String[] args) {

int row, col, sumRow, sumCol;

//Initialize matrix a

int a[][] = {

{1, 2, 3},

{6, 5, 4},

{7, 8, 9}

};

//Calculates number of rows and columns present in given matrix


row = a.length;

col = a[0].length;

//Calculates sum of each row of given matrix

for(int i = 0; i < row; i++){

sumRow = 0;

for(int j = 0; j < col; j++){

sumRow = sumRow + a[i][j];

System.out.println("Sum of " + (i+1) +" row: " + sumRow);

//Calculates sum of each column of given matrix

for(int i = 0; i < col; i++){

sumCol = 0;

for(int j = 0; j < row; j++){

sumCol = sumCol + a[j][i];

System.out.println("Sum of " + (i+1) +" column: " + sumCol);

}
OUTPUT:

Viva questions:

1. What is the default value of Array for different data types?


By default, when we create an array of something in Java all entries will have its default
value. For primitive types like int , long , float the default value are zero ( 0 or 0.0 ). For
reference types (anything that holds an object in it) will have null as the default value.
For boolean variable it will be false .

2. Can you change size of Array in java after creation?


If you create an array by initializing its values directly, the size will be the number of
elements in it. Thus the size of the array is determined at the time of its creation or,
initialization once it is done you cannot change the size of the array.

3. What error is encountered if we pass negative number in Array size?


you cannot use a negative integer as size, the size of an array represents the number of
elements in it, –ve number of elements in an array makes no sense.Still if you do so, the
program gets compiled without issues but, while executing it generates a runtime
exception of type NegativeArraySizeException.
On executing, it will generate a run time exception as shown below:
Exception in thread "main" java.lang.NegativeArraySizeException
at myPackage.Test.main(Test.java:6)

4. What is ArrayStoreException ? When this exception is thrown ?


ArrayStoreException in Java occurs whenever an attempt is made to store the wrong
type of object into an array of objects. The ArrayStoreException is a class which extends
RuntimeException, which means that it is an exception thrown at the runtime.

5. What are jagged arrays in java?


Jagged array is a multidimensional array where member arrays are of different size. For
example, we can create a 2D array where first array is of 3 elements, and is of 4
elements. Jagged arrays in java sometimes are also called as ragged arrays.
6. What are the different ways to copy one Array from another Array?
a) We might iterate each element of the given original array and copy one element
at a time. Using this method guarantees that any modifications to b, will not
alter the original array
// Copy elements of a[] to b[]
for (int i=0; i<a.length; i++)
b[i] = a[i];
b) We can use clone method in Java.
// Copy elements of a[] to b[]
int b[] = a.clone();
c) We can also use System.arraycopy() Method. System is present in java.lang
package.As:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int
length)
Where src denotes the source array, srcPos is the index from which copying
starts. Similarly, dest denotes the destination array, destPos is the index from
which the copied elements are placed in the destination array. length is the
length of subarray to be copied.
// Copy elements of a[] to b[]
System.arraycopy(a, 0, b, 0, 3);
************

You might also like