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

Array

Arrays allow storing multiple values of the same type together in memory. An array is declared with a type followed by brackets, such as int[] or String[]. Individual elements in an array are accessed via an index, with the first element at index 0. Multidimensional arrays can represent tables or matrices by using arrays of arrays. Arrays can be initialized with values between curly braces or by manually assigning values after allocation. The length property returns the size of an array.

Uploaded by

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

Array

Arrays allow storing multiple values of the same type together in memory. An array is declared with a type followed by brackets, such as int[] or String[]. Individual elements in an array are accessed via an index, with the first element at index 0. Multidimensional arrays can represent tables or matrices by using arrays of arrays. Arrays can be initialized with values between curly braces or by manually assigning values after allocation. The length property returns the size of an array.

Uploaded by

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

Programming in Java

Arrays
Array
• Definition:
An array is a group/collection of variables of the
same type that are referred to by a common name.
• Arrays of any type can be created and may have one
or more dimensions.
• A specific element in an array is accessed by its index
(subscript).
• Examples:
• Collection of numbers
• Collection of names
• Collection of suffixes
Examples
Array of numbers:
10 23 863 8 229

Array of names:

Sam Shanu Riya

Array of suffixes:
ment tion ness ves
One-Dimensional Arrays
• A one-dimensional array is a list of variables of same
type.
• The general form of a one-dimensional array
declaration is:

type var-name[ ];
array-var = new type[size];

or, type var-name[ ] = new type[size];


Example:
int num [] = new int [10];
Syntax
Declaration of array variable:
data-type variable-name[];
eg. int marks[];

This will declare an array named ‘marks’ of type ‘int’. But no memory is
allocated to the array.

Allocation of memory:
variable-name = new data-type[size];
eg. marks = new int[5];

This will allocate memory of 5 integers to the array ‘marks’ and it can store upto
5 integers in it. ‘new’ is a special operator that allocates memory.
Accessing elements in the array:
•Element in the array is accessed by specifying name of
the array followed by the index of the element.
• All array indexes in Java start at zero.
variable-name[index] = value;
Example:
marks[0] = 110;
This will assign the value 110 to the 1st element in the array.

marks[2] = 163;
This will assign the value 163 to the 3rd element in the array.
Example
STEP 1 : (Declaration)
int marks[];
marks → null
STEP 2: (Memory Allocation)
marks = new int[5];
marks → 0 0 0 0 0
marks[0] marks[1] marks[2] marks[3] marks[4]

STEP 3: (Accessing Elements)


marks[0] = 10;
marks → 10 0 0 0 0
marks[0] marks[1] marks[2] marks[3] marks[4]
• Size of an array can’t be changed after the array is created.

• Default values:
– zero (0) for numeric data types,
– false for boolean types

• Length of an array can be obtained as:


array_ref_var.length
Example
class Demo_Array
{
public static void main(String args[])
{
int marks[];
marks = new int[3];
marks[0] = 10;
marks[1] = 35;
marks[2] = 84;
System.out.println(“Marks of 2nd student=” + marks[1]);
}
}
Note
• Arrays can store elements of the same data type. Hence an
int array CAN NOT store an element which is not an int.
• Though an element of a compatible type can be converted
to int and stored into the int array.

eg. marks[2] = (int) 22.5;


This will convert ‘22.5’ into the int part ‘22’ and store it into the 3rd place
in the int array ‘marks’.

• Array indexes start from zero. Hence ‘marks[index]’ refers


to the (index+1)th element in the array and ‘marks[size-1]
refers to last element in the array.
Array Initialization
1. data Type [] array_ref_var = {value0, value1, …, value n};

2. data Type [] array_ref_var;


array_ref_var = {value0, value1, …,value n};

3. data Type [] array_ref_var = new data Type [n+1];


array_ref_var [0] = value 0;
array_ref_var [1] = value 1;

array_ref_var [n] = value n;

4. data Type [] array_ref_var = new data Type [] {val 0,val 1..val n};
Example
int[] v = new int[10];
int i = 7;
int j = 2;
int k = 4;
v[0] = 1;
v[i] = 5;
v[j] = v[i] + 3;
v[j+1] = v[i] + v[0];
v[v[j]] = 12;
System.out.println(v[2]);
v 0 0 0 0 0 0 0 0 0 0

v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9]
Example
int[] v = new int[10];
int i = 7;
int j = 2;
int k = 4;
v[0] = 1;
v[i] = 5;
v[j] = v[i] + 3;
v[j+1] = v[i] + v[0];
v[v[j]] = 12;
System.out.println(v[2]);
v 1 0 0 0 0 0 0 0 0 0

v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9]
Example
int[] v = new int[10];
int i = 7;
int j = 2;
int k = 4;
v[0] = 1;
v[i] = 5;
v[j] = v[i] + 3;
v[j+1] = v[i] + v[0];
v[v[j]] = 12;
System.out.println(v[2]);
v 1 0 0 0 0 0 0 5 0 0

v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9]
Example
int[] v = new int[10];
int i = 7;
int j = 2;
int k = 4;
v[0] = 1;
v[i] = 5;
v[j] = v[i] + 3;
v[j+1] = v[i] + v[0];
v[v[j]] = 12;
System.out.println(v[2]);
v 1 0 8 0 0 0 0 5 0 0

v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9]
Example
int[] v = new int[10];
int i = 7;
int j = 2;
int k = 4;
v[0] = 1;
v[i] = 5;
v[j] = v[i] + 3;
v[j+1] = v[i] + v[0];
v[v[j]] = 12;
System.out.println(v[2]);
v 1 0 8 6 0 0 0 5 0 0

v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9]
Example
int[] v = new int[10];
int i = 7;
int j = 2;
int k = 4;
v[0] = 1;
v[i] = 5;
v[j] = v[i] + 3;
v[j+1] = v[i] + v[0];
v[v[j]] = 12;
System.out.println(v[2]);
v 1 0 8 6 0 0 0 5 12 0

v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9]
Example
int[] v = new int[10];
int i = 7;
int j = 2;
int k = 4;
v[0] = 1;
v[i] = 5; 8 is displayed
v[j] = v[i] + 3;
v[j+1] = v[i] + v[0];
v[v[j]] = 12;
System.out.println(v[2]);
v 1 0 8 6 0 0 0 5 12 0

v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9]
Multi-Dimensional Array
• Multidimensional arrays are arrays of arrays.

• Two-Dimensional arrays are used to represent a table or a


matrix.

• Creating Two-Dimensional Array:


int twoD[][] = new int[4][5];
Conceptual View of 2-Dimensional Array
class TwoDimArr
{
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();
}
}
}
• When we allocate memory for a multidimensional
array, we need only specify the memory for the first
(leftmost) dimension.

int twoD[][] = new int[4][];

• The other dimensions can be assigned manually.


// Manually allocate differing size second dimensions.
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();
}
}
}
Initializing Multi-Dimensional Array
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0, 0, 0, 0 },
{ 0, 1, 1, 1 },
{ 0, 2, 2, 2 },
{ 0, 3, 3, 3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
Alternative Array Declaration
type[ ] var-name;

• Example:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];

• This alternative declaration form offers convenience


when declaring several arrays at the same time.

• Example: int[] nums, nums2, nums3;


Array Cloning
class Demo
{
public static void main(String arv[])
{ int a[] = new int[5];
for(int i=0; i <5 ; i++)
{ a[i] = i+1; }
int b[] = a;
a[2] = 20 ;
for(int i=0; i<5; i++)
System.out.println(b[i]);
}}
Array Cloning
• To create another array with its own values, Java
provides the clone() method.

• arr2 = arr1; (assignment)


is not equivalent to
arr2 = arr1.clone(); (cloning)
Let’s Do It
• WAP to convert double array into int array by using user
defined method with following signature:

public static int [] doubleToInt(double d[])


Variable-Length Argument Lists
• A variable number of arguments of the same type can be
passed to a method and treated as an array.
typeName... parameterName
• Only one variable-length parameter may be specified in a
method, and this parameter must be the last parameter.

• Eg.
– void printMax(int a, double... numbers)
– …
– printMax(34, 3, 3, 2, 56.5)
– printMax(10, new double[]{1, 2, 3})
Let’s Do It
• WAP to calculate and display the CGPI of students by taking atleast
three subjects marks as input from the user. The number of CA
components in subjects can vary (eg: Java – 4 CAs, Data Structure –
3 CAs etc.) and consider best n-1 CAs for final CGPI. Your program
should be user interactive.

• Percentage → Grade→ Point


• 80<= P → A → 10
• 60<= P < 80 → B →8
• 50<= P < 60 → C →6
• 40<= P < 50 → D → 5
• P < 40 →F →0
Brainstorming Questions
• class Demo
• {
• public static void main(String[] args) {
• int[] a = new int[0];
• System.out.print(a.length);
• }
• }
• A) 0
• B) Compilation error, arrays cannot be initialized to zero size
• C) Compilation error, it is a.length() not a.length
• D) Runtime Error

• Ans-A
Brainstorming Questions
• class Demo {
• static void test(int[] a) {
• int[] b = new int[2];
• a = b;
• System.out.print(b.length);
• System.out.print(a.length);
• }
• public static void main(String[] args) {
• int[] a = new int[5];
• test(a);
• System.out.print(a.length); }}
• A) 225
• B) 255
• C) 200
• D) 222

• Ans-A
Brainstorming Questions
• class Demo {
• public static void main(String[] args) {
• String entries[] = {"entry1","entry2"};
• int count=0;
• while (entries [count++]!=null){
• System.out.println(count);
• }
• System.out.println(count);
• }
• }
• A) An Exception will be thrown
• B) 0 will be printed as part of the output
• C) 2 will be printed as part of the output
• D) 3 will be printed as part of the output

• Ans-A
Brainstorming Questions
• Which of the following declarations of an array is incorrect?

• A) int[] a[];
• B) int b[3];
• C) int []c[];
• D) int[] d[];

• Ans- B
Brainstorming Questions
• class Demo {
• final static int x[] = new int[5];
• public static void main(String[] args) {
• int x = new Demo().x[5];
• if (x <= 10)
• System.out.println("javachamp");
• }
• }
• A) Compilation error
• B) ArrayIndexOutOfBoundsException is thrown
• C) javachamp
• D) No output is produced

• Ans-B
Brainstorming Questions
• class Demo {
• public static void main(String[] args)
• {
• byte b1= 25;
• byte b2=45;
• byte b3= b1+b2;
• }}
• a) 70
• b) CompileError
• c) 25
• d) RunTimeException

• Ans- B
Array of Objects
• An array can hold objects as well as primitive type values.

Eg:
Circle[] circleArray = new Circle[10];

• To initialize circleArray, you can use a for loop like this one:
for (int i = 0; i < circleArray.length; i++)
{
circleArray[i] = new Circle();
}
Brainstorming Questions
• Consider the following command-line invocations?
• i. java Arrays
• ii. java Arrays 12
• iii. java Arrays 12 32
• class Arrays
• { public static void main(String [ ] args){
• for(int x=0;args.length>x++;){
• System.out.print(args[x]+ " ");
• } } }
• A. Only the invocation i will complete without throwing exceptions
• B. Only Invocation i will throw an exception.
• C. Invocation ii will produce he output 12.
• D. Invocation iii will produce he output 12 32.
• E. Invocations ii and iii will throw exceptions.

• Ans-A
Brainstorming Questions
• class Demo
• {public static void main(String[] args) {
• Object obj = new int[] { 1, 2, 3 };
• int[] someArray = (int[])obj;
• for (int i : someArray) System.out.print(i + " ");
• } }
• A) 1 2 3
• B) Compilation fails because of an error in line 12.
• C) Compilation fails because of an error in line 13.
• D) Compilation fails because of an error in line 14.
• E) A ClassCastException is thrown at runtime
• Ans- A
Brainstorming Questions
• What is the result of running the following code with "java
Demo debug":
• class Demo
• { public static void main(String [ ] args)
• { if (args.length == 1 | args[1].equals("debug"))
• { System.out.println(args[0]); }
• else { System.out.println("Release");
• } } }
• A) Debug
• B) Release
• C) Compilation fails
• D) An exception is thrown at run-time
• Ans-D

You might also like