0% found this document useful (0 votes)
52 views

JAVA Arrays

This document covers various aspects of arrays in Java like declaration, definition,

Uploaded by

bt5112 Kareena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

JAVA Arrays

This document covers various aspects of arrays in Java like declaration, definition,

Uploaded by

bt5112 Kareena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Arrays in JAVA

Declaring an Array Variable

◼ Do not have to create an array while


declaring array variable
– <type> [] variable_name;
– int [] prime;
– int prime[];
◼ Both syntaxes are equivalent
◼ No memory allocation at this point
Defining an Array

◼ Define an array as follows:


– variable_name=new <type>[N];
– primes=new int[10];
◼ Declaring and defining in the same
statement:
– int[] primes=new int[10];
◼ In JAVA, int is of 4 bytes, total
space=4*10=40 bytes
What happens if …
◼ We define
– int[] prime=new long[20];
MorePrimes.java:5: incompatible types
found: long[]
required: int[]
int[] primes = new long[20];
^
◼ The right hand side defines an array, and
thus the array variable should refer to the
same type of array
What happens if …

◼ Valid code:
int k=7;
long[] primes = new long[k];

◼ Invalid Code:
int k;
long[] primes =new long[k];
Compilation Output:
MorePrimes.java:6: variable k might not have been initialized
long[] primes = new long[k];
^
Question

Q1: Read the size of an array from the


user and create an array.
Q2: Create an array of integers (without
initialization) of size 20 and print the
value of 2nd element.
Default Initialization

◼ When array is created, array elements


are initialized
– Numeric values (int, double, etc.) to 0
– Boolean values to false
– Char values to ‘\u0000’ (unicode for blank
character)
– Class types to null
Questions

Q1: Create an array with 30 elements and


access the 50th element. Observe the
output.

Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: 30
at demo.main(demo.java:7)
Validating Indexes

◼ JAVA checks whether the index values


are valid at runtime
– If index is negative or greater than the size
of the array then an
IndexOutOfBoundException will be thrown
– Program will normally be terminated unless
handled in the try {} catch {}
Initializing Arrays

◼ Initialize and specify size of array while


declaring an array variable
int[] primes={2,3,5,7,11,13,17}; //7 elements
◼ You can initialize array with an existing array
int[] even={2,4,6,8,10};
int[] value=even;
– One array but two array variables!
– Both array variables refer to the same array
– Array can be accessed through either variable
name
Array Length

◼ Refer to array length using length


– A data member of array object
– array_variable_name.length
– for(int k=0; k<primes.length;k++)
….
◼ Sample Code:
long[] primes = new long[20];
System.out.println(primes.length);

◼ Output: 20
Arrays of Arrays

◼ Two-Dimensional arrays
– float[][] temperature=new float[10][365];
– 10 arrays each having 365 elements
– First index: specifies array (row)
– Second Index: specifies element in that
array (column)
– In JAVA float is 4 bytes, total
Size=4*10*365=14,600 bytes
Initializing Array of Arrays

int[][] array2D = { {99, 42,


74, 83, 100}, {90, 91, 72,
88, 95}, {88, 61, 74, 89,
96}, {61, 89, 82, 98, 93},
{93, 73, 75, 78, 99}, {50,
65, 92, 87, 94}, {43, 98, 78,
56, 99} };
//5 arrays with 5 elements each
Arrays of Arrays of Varying Length

◼ All arrays do not have to be of the same


length
float[][] samples;
samples=new float[6][];//defines # of arrays
samples[2]=new float[6];
samples[5]=new float[101];
Initializing Varying Size Arrays
int[][] uneven = { { 1, 9, 4 }, { 0,
2}, { 0, 1, 2, 3, 4 } };
//Three arrays
//First array has 3 elements
//Second array has 2 elements
//Third array has 5 elements
Sample Program
class uneven3
{ public static void main(
String[] arg )
{
int[][] uneven = { { 1, 9, 4 },
{ 0, 2}, { 0, 1, 2, 3, 4 } };
for ( int row=0; row <
uneven.length; row++ ) {
System.out.print("Row " + row +
": ");
for ( int col=0; col <
uneven[row].length; col++ )
System.out.print(
Question

◼ What is the class name of java array?


◼ In java, array is an object.
◼ For array object, an proxy class is
created whose name can be obtained
by getClass().getName() method on the
object.
Output

Sample Program I

class demo{
public static void main(String args[]){
int arr[]={4,4,5};
Class c=arr.getClass();
String name=c.getName();
System.out.println(name);
}}
Copying a java array

◼ We can copy an array to another by the


arraycopy method of System class.

Syntax of arraycopy method


public static void arraycopy(
Object src, int srcPos,Object dest, int dest
Pos, int length )
Sample Program
class TestArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f',
'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo,
0, 7);
System.out.println(new String(copyTo));
}}
Output

Question B

Which of the following is FALSE about


arrays on Java
A. A java array is always an object
B. Length of array can be changed after
creation of array
C. Arrays in Java are always allocated on
heap
Output

Question Compilation
Error

class Test {
public static void main(String args[]) {
int arr[2];
System.out.println(arr[0]);
System.out.println(arr[1]);
}
}
Output

Question Not Same

class Test {
public static void main (String[] args) {
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
if (arr1 == arr2)
System.out.println("Same");
else
System.out.println("Not same"); } }
Output
Question Same

import java.util.Arrays;
class Test {
public static void main (String[] args) {
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
if (Arrays.equals(arr1, arr2))
System.out.println("Same");
else
System.out.println("Not same");}}
Output

Question Not same

class Test {
public static void main (String[] args) {
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
if (arr1.equals(arr2))
System.out.println("Same");
else
System.out.println("Not same"); }}
Output

Question 0

What is the result of compiling and


running the following code?

public class Test{


public static void main(String[] args){
int[] a = new int[0];
System.out.print(a.length);
}}
Output

Question 120 200 14

public class Test{


public static void main(String[] args){
int[] x = {120, 200, 016 };
for(int i = 0; i < x.length; i++)
System.out.print(x[i] + " ");
}
}
Output

Question Correct

int[] arr = new int[5];


arr = new int[6];
Output

Question 0

public class Test{


public static void main(String[] args){
int[] a = new int[4];
a[1] = 1;
a = new int[2];
System.out.println("a[1] is " + a[1]);
}
}
Output

Question 12

public class Test{


public static void main(String[] args){
int[] x = {1, 2, 3, 4};
int[] y = x;
x = new int[2];
for(int i = 0; i < x.length; i++)
System.out.print(y[i] + " ");
}}
Output

Question C

When you pass an array to a method, the


method receives ________ .

◼ A. A copy of the array.


◼ B. A copy of the first element.
◼ C. The reference of the array.
◼ D. The length of the array.
Output

Question 2.0

class Test{
public static void main(String[] args){
double[] x = new double[]{1, 2, 3};
System.out.println("Value is " +
x[1]);
}
}
Output

Question 1

What is the value of a[1] after the


following code is executed?

int[] a = {0, 2, 4, 1, 3};


for(int i = 0; i < a.length; i++)
a[i] = a[(a[i] + 3) % a.length];
[I@10dea4e
Question

◼ What will this code print?


int arr[] = new int [5];
System.out.print(arr);

Output

If we trying to print any reference variable internally,


toString() will be called which is implemented to return the
String in following form:
classname@hashcode in hexadecimal form
Practice Question

By passing entire array to function:


◼ Set up an array to hold the following values,
and in this order: 23, 6, 47, 35, 2, 14. Write a
program to get the average of all 6 numbers.
◼ Using the above values, have your program
print out the second largest number in the
array.
◼ Using the same array above, have your
program print out only the odd numbers.
Practice Question

❑ Q1: Create a 2D array with variable


number of elements in each row.
❑ Q2. Implement Fibonacci series using
arrays.
Practice Question

◼ WAP to multiply two matrices.


◼ WAP to find trace of a matrix.
◼ WAP to find if a matrix is symmetric or
skew-symmetric.
◼ WAP to find determinant of a 3x3
matrix.

You might also like