Core Java
Lesson 5—Creating and Using Array
© Simplilearn. All rights reserved.
Learning Objectives
At the end of this lesson, you should be able to:
Declare, initialize, and use a one-dimensional array
Declare, initialize, and use multi-dimensional arrays
Java Operators and Decision Constructs
Topic 1—One-dimensional Array
Declaring One-dimensional Array
An array is a data structure that stores elements of similar data types.
Arrays can be declared using square brackets after variable name:
char[] s;
Point[] p; //where Point is a class
One-dimensional array
Array in Java is index based; the first element of the array is stored at
0 index.
Initializing One-dimensional Array
Initializing all variables, including elements of arrays, is essential to secure the system.
Initialization Example:
String[] names = String[] names;
{ names = new String [3];
“John”, This code is equal to: names [0] = “John”;
“James”, names [1] = “James”;
“Simon” names [2] = “Simon”;
};
Creating One-dimensional Array
You can create arrays using a new keyword.
S = new char[26];
Execution Stack
We have created an array ‘S’ with 26 char values.
s
CreateArray
this
main
Creating One-dimensional Array (Contd.)
Now that we have created a One-dimensional array, let us fill the array using an example.
Example
Execution Stack
Heap Memory
public char[] CreateArray ()
{ char[]
char[] S;
A
S= new char[26];
for (int i=0; i<26; i++) B
{
S[i] = (char) (‘A’ + i); C
}
Z
return S;
}
s
CreateArray
this
main
Creating One-dimensional Array (Contd.)
Example
p = new Point[10];
Execution Stack Heap Memory
public Point[] CreateArray ()
{
Point[] p;
Point
p= new Point[10]; Point[] 0
for (int i=0; i<10; i++)
{ 1
p[i] = new Point (i, i+1);
}
Point
return p;
} 1
p 2
CreateArray
this
main
Declare, Instantiate, Initialize, and Print Array—Example
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=60;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
Output:
}}
10
20
60
40
50
Creating an Array Using New Keyword
// Declaration of allocating memory to an array
int iarr[] = new int[3];
// Initializing elements
iarr[0] = 1;
iarr[1] = 2;
iarr[2] = 3;
//Display array elements
System.out.println(iarr[0]);
System.out.println(iarr[1]);
System.out.println(iarr[2]);
// Or Use for loop to display elements
for (int i = 0; i < iarr.length; i = i + 1)
{
System.out.print(iarr[i]);
System.out.print(" "); Output:
} 10
20
60
40
50
Delete an Element from an Array—Example
import java.util.Scanner; else
public class Delete {
{ flag = 0;
public static void main(String[] args) }
{ }
int n, x, flag = 1, loc = 0; if(flag == 1)
Scanner s = new Scanner(System.in); {
System.out.print("Enter no. of elements you want in array:"); for(int i = loc+1; i < n; i++)
n = s.nextInt(); {
int a[] = new int[n]; a[i-1] = a[i];
System.out.println("Enter all the elements:"); }
for (int i = 0; i < n; i++) System.out.print("After Deleting:");
{ for (int i = 0; i < n-2; i++)
a[i] = s.nextInt(); {
} System.out.print(a[i]+",");
System.out.print("Enter the element you want to delete:"); }
x = s.nextInt(); System.out.print(a[n-2]);
for (int i = 0; i < n; i++) }
{ else
if(a[i] == x) {
{ System.out.println("Element not found");
flag =1; }
loc = i; }
break; }
}
Delete an Element from an Array—Example (Contd.)
$ javac Delete.java
$ java Delete
Enter number of elements you want in array: 5
Enter all the elements: 3 5 8 1 4
Enter the element you want to delete: 5
After Deleting: 3 8 1 4
Core Java
Topic 2—Multi-dimensional Array
Creating Multi-dimensional Array Using New Keyword
Data is stored in a row- and column-based index—also known as matrix form.
Two-dimensional array
Creating Multi-dimensional Array Using New Keyword (Contd.)
Let us now understand initialization with an example.
int [] [] twoDim = new int [4] [5];
twoDim [0] = new int [5];
twoDim [1] = new int [5];
int [] [] twoDim = new int [4] [5];
Initialization involves creating a two-dimensional array of four arrays of five integers.
Initializing Multi-dimensional Array Using New Keyword
Let us now understand initializing multi-dimensional array with an example.
int iarr[][] = new int[2][3];
iarr[0][0] = 1; // Initializing elements
iarr[0][1] = 2;
iarr[0][2] = 3;
iarr[1][0] = 4;
iarr[1][1] = 5;
iarr[1][2] = 6;
System.out.println(iarr[0][0]); //Display array elements
System.out.println(iarr[0][1]);
System.out.println(iarr[0][2]);
System.out.println(iarr[1][0]);
System.out.println(iarr[1][1]);
System.out.println(iarr[1][2]);
for (int i = 0; i < iarr.length; i = i + 1)
{
for(int j=0; j < iarr[i].length; j = j + 1)
{
System.out.print(iarr[i][j]);
System.out.print(" ");
}
}
Declaring Multi-dimensional Array
Multi-dimensional arrays in Java are different from those in other languages.
In Java, you can create an array, arrays of arrays, and so on.
Syntax:
dataType[][] arrayRefVar;
Primitive Array
When we create a primitive array, default values will be assigned, but object references will be
null.
In Java 8, you can use the Stream APIs to do the boxing and conversion.
Example:
List<Integer> list = Arrays.stream(number).boxed().collect(Collectors.toList());
Examples of declaring variables that are arrays of primitives (lines 1 through 3) and objects
(lines 4 and 5):
1. int counts[] ;
2. int[] counts ; // 1 and 2 are equivalent
3. boolean flags [ ] ; // extra spaces are not significant
4. String names[] ;
5. MyClass[][] things ; // a two-dimensional array of objects
Primitive Array to List
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ArrayExample2
{
public static void main(String[] args)
{
int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//List<Integer> list = IntStream.of(number).boxed().collect(Collectors.toList());
List<Integer> list = Arrays.stream(number).boxed().collect(Collectors.toList());
System.out.println("list : " + list);
}
} Output:
list : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
java.util.Arrays Class
java.util.Arrays is a static class that allows arrays to be viewed as lists.
It contains various methods for manipulating arrays (such as sorting and searching).
The methods in this class throw a NullPointerException if the specified
array reference is null.
java.util.Arrays Class
Some of the key methods in java.util.Arrays class are:
Method Name Description
binarySearch (array, value) returns the index of the given value in a sorted array (or < 0 if not found)
binarySearch (array, minIndex, returns index of given value in a sorted array between indexes min/max –
maxIndex, value) 1 (< 0 if not found)
copyOf (array, length) returns a new resized copy of an array
equals (array1, array2) returns true if the two arrays contain the same elements in the same
order
fill (array, value) sets every element to the given value
sort (array) arranges the elements into sorted order
toString (array) returns a string representing the array, such as
“[10, 30, -25, 17]”
Syntax:
Arrays.methodName (parameters)
Key Takeaways
Array is a data structure that stores elements of similar data types.
Arrays can be declared using square brackets after variable name.
Initializing all variables, including elements of arrays, is essential to secure the system.
You can create arrays using a new keyword.
In multi-dimensional arrays, data is stored in row- and column-based index.
When we create a primitive array, default values will be assigned, but object references
will be null.
java.util.Arrays is a static class that allows arrays to be viewed as lists.
Quiz
int ar[]=new int[100];
QUIZ ar[0]=12;
ar[1]=13;
1
ar[5]=100; Pick the matching stuff from below regarding the above snippet.
a. Compiler error
b. Run time error
c. ar.length will print 100
d. ar.length will print 3
int ar[]=new int[100];
QUIZ ar[0]=12;
ar[1]=13;
1
ar[5]=100; Pick the matching stuff from below regarding the above snippet.
a. Compiler error
b. Run time error
c. ar.length will print 100
d. ar.length will print 3
The correct answer is c.
ar.length points to the total size of array, which is 100.
Employee e[]=newEmployee[1];
QUIZ
System.out.println(e[0]);
2
What is the output of the above snippet?
a. Run time error
b. Compile time error
c. 0
d. Null
Employee e[]=newEmployee[1];
QUIZ
System.out.println(e[0]);
2
What is the output of the above snippet?
a. Run time error
b. Compile time error
c. 0
d. Null
The correct answer is d. Null
Objects get a default value of null.
Thank You