L6 Array
L6 Array
Arrays
By
Arvind Kumar
Asst. Professor, LPU
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:
Array of suffixes:
type var-name[ ];
array-var = new type[size];
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]
• Default values:
– zero (0) for numeric data types,
– false for boolean types
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;
8 is displayed
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]
Let’s Do It
• Create an application containing an array that stores eight
integers. The application should
• (1) display all the integers,
• (2) display all the integers in reverse order,
• (3) display the sum of the eight integers,
• (4) display all values less than 5,
• (5) display the lowest value,
• (6) display the highest value,
• (7) calculate and display the average, and
• (8) display all values that are higher than the calculated
average value.
• Save the file as NumberListDemo.java .
Multi-Dimensional Array
• Multidimensional arrays are arrays of arrays.
• Example:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
• 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) – 4 CAs, Data
Structure(3) – 3 CAs, English (2) – 3 CAs) and consider best n-1
CAs for final CGPI. Your program should be user interactive.
• 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
Let’s Do It
• A personal phone directory contains room for first names and
phone numbers for 30 people.
• Assign names and phone numbers for the first 10 people.
Prompt the user for a name, and if the name is found in the
list, display the corresponding phone number.
• If the name is not found in the list, prompt the user for a phone
number, and add the new name and phone number to the list.
Continue to prompt the user for names until the user enters “
quit” .
• After the arrays are full (containing 30 names), do not allow
the user to add new entries. Save the file as
PhoneNumbers.java.
Let’s Do It
• Write an application that accepts up to 20 Strings. Divide them
into two lists— one for short String s that are five characters
or fewer, and the other for long Strings. After data entry is
complete, prompt the user to enter which type of String to
display, and then output the correct list. If there are no String s
in a requested list, then output an appropriate message. Save
the file as DivideStrings.java.
Let’s Do It
• Create a class named Salesperson . Data fields for Salesperson
include an integer ID number and a double annual sales
amount. Methods include a constructor that requires values for
both data fields, as well as get and set methods for each of the
data fields. Write an application named DemoSalesperson that
declares an array of 10 Salesperson objects. Set each ID
number to 9999 and each sales value to zero. Display the 10
Salesperson objects. Save the files as Salesperson.java and
DemoSalesperson.java .
• Modify the DemoSalesperson application so each Salesperson
has a successive ID number from 111 through 120 and a sales
value that ranges from $25,000 to $70,000, increasing by
$5,000 for each successive Salesperson . Save the file as
DemoSalesperson2.java .
Let’s Do It