0% found this document useful (0 votes)
3 views14 pages

JavaNotes Unit1 Chap6

Chapter 6 discusses arrays in Java, explaining that they are collections of similar types stored in contiguous memory locations. It covers the advantages and disadvantages of arrays, how to create and initialize them, and the different types, including single-dimensional and multi-dimensional arrays. The chapter also highlights key points about arrays, methods for manipulating them, and how to pass arrays to methods.

Uploaded by

Divya Shree
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

JavaNotes Unit1 Chap6

Chapter 6 discusses arrays in Java, explaining that they are collections of similar types stored in contiguous memory locations. It covers the advantages and disadvantages of arrays, how to create and initialize them, and the different types, including single-dimensional and multi-dimensional arrays. The chapter also highlights key points about arrays, methods for manipulating them, and how to pass arrays to methods.

Uploaded by

Divya Shree
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter-6

Arrays
An array is a collection of similar type of elements, which
has contiguous memory location.

Java array is an object, which contains elements of a similar data


type. Additionally, the elements of an array are stored in a contiguous
memory location. It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
For primitive arrays, elements are stored in a contiguous memory
location. For non-primitive arrays, references are stored at contiguous
locations, but the actual objects may be at different locations in memory.

Array in Java is index-based, the first element of the array is stored


at the 0th index, 2nd element is stored on 1st index and so on.

Advantages
o Code Optimization: It makes the code optimized; we can
retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.

.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the
array. It does not grow its size at runtime. To solve this problem,
collection framework is used in Java, which grows
automatically.
o

To Create an Array in Java, we use three steps;


1. Declare a variable to hold array.
2. Create a new array object and assign it to the array variable.
3. Initialize or assign values to the array elements.

1. Array Declaration

To declare an array in Java, use the following syntax:

type[] arrayName;
• type: The data type of the array elements (e.g., int, String).
• arrayName: The name of the array.

Note: The array is not yet initialized.

2. Create an Array

To create an array, you need to allocate memory for it using


the new keyword:
// Creating an array of 5 integers
int[] numbers = new int[5];
This statement initializes the numbers array to hold 5 integers. The default
value for each element is 0.

3. Initializing Arrays
Arrays can either have all of their elements initialized at the time of
declaration or the elements can be individually initialized after declaration.

.
Example :
Initialization after declaration
int[] myIntArray= new int[3];
myIntArray[0] = 10;
myIntArray[1]=20;
myIntArray[1]=30;
Initialization at the time of declaration:
int[] numbers = {10,20,30,40,50};

How to Access an Element of an Array


We can access any array elements directly using their array index, which starts
from 0:
// Setting the first element of the array
numbers[0] = 10;
// Accessing the first element
int firstElement = numbers[0];
The first line sets the value of the first element to 10. The second line retrieves the
value of the first element.

Anonymous Array:
Its is perfectly legal to create an anonymous array using the following

New <type>[]{ <list of values>};

Example: new int[]{1,2,3};

Above creates a nameless array and initializes it. Here, neither name nor size is
specified.

Types of Array in java


There are two types of arrays.
1. Single Dimensional Array
2. Multidimensional Array

.
SINGLE DIMENSIONAL ARRAY (one dimensional array):
• A list of items can be given one variable name using only
one subscript and such a variable is called one dimensional
array.
• One dimensional array is a list of variables of same type
that are accessed by a common name.
• An individual variable in the array is called an array element.

Declaration of one-dimensional arrays:


• To declare an array below is a general form or syntax.
Datatype arrayName [ ];
Where, Datatype is valid data type in java and arrayName is a name of an
array.
Example : int physics [ ];
physics = new int[10];

Above statement will create an integer of an array with ten elements that can
be accessed by physics physics[0]
physics[1]

Example Program: physics[2]

class Testarray physics[3]


physics[4]
{
physics[5]
public static void main (String args[])
physics[6]
{
physics[7]
int a[]=new int[5];//declare and create
physics[8]
a[0]=10;//initialization
physics[9]
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
.
for(int i=0;i<[Link];i++)
[Link](a[i]);

}
Output:
10
20
70
40
50

Example for Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation
and initialization Let's see the simple example to print this
array.
class Testarray1
{
public static void main (String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<[Link];i++)//length is the
property of array [Link](a[i]);
}
}

.
OutPut:
33
3
4
5

Arrays of Object References


An array of objects is created like an array of primitive-type data items
by specifying the object type and the size of the object in the following
way.
Syntax:
Method 1:
ObjectType[] arrName;
Method 2:
ObjectType arrName[];
Example of Arrays of Objects
Example 1: Here we are taking a student class and creating an array of
Student with five Student objects stored in the array. The Student objects
have to be instantiated using the constructor of the Student class, and
their references should be assigned to the array elements.

.
MULTI -DIMENSIONAL ARRAY
A multidimensional array in Java is an array of array references that is
array containing other arrays as its elements. The most commonly used
type is the 2D array (matrix), but Java also supports arrays with more
than two dimensions.

.
TWO-DIMENSIONAL ARRAY:

Declaration of Two Dimensional Array in Java


Following the format of declaration of two-
dimensional array in Java Programming Language:

DataType ArrayName[][];
ArrayName = new DataType[][];
(or)

DataType ArrayName[][] = new DataType[][];

Syntax:
Data_type:
• This will decide the type of elements it will accept.
• For example, If we want to store integer values then, the Data
Type will be declared as int, If we want to store Float values
then, the Data Type will be float etc.
Array_Name:
• This is the name you want to give it to array.
For example, Car, students, age, marks, department

Creating of Two-Dimensional Array in java


int[][] a = new int[3][4];

.
examples
int[][] a = {{1, 2, 3 ,4}, {4, 5, 6, 9}, {2,4,5,7}}

Here, a is a two-dimensional
array. The array can hold
maximum of 12 elements of
type int.
Java uses zero-based indexing,
that is, indexing of arrays in
Java starts with 0 and not 1.

.
Intialization of Array:
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};

Example:
class MultidimensionalArray
{
public static void main(String[] args)
{
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
[Link]("Length of row 1: " + a[0].length);
[Link]("Length of row 2: " + a[1].length);
[Link]("Length of row 3: " + a[2].length);
}
}
Output:
Length of row 1: 3
Length of row 2: 4

.
Length of row 3: 1

Regular vs. Non-Regular (Jagged) Multidimensional Arrays in Java


In Java, multidimensional arrays can be categorized as Regular (Rectangular)
and Non-Regular (Jagged).
1. Regular Multidimensional Array (Rectangular)
A regular (rectangular) array has the same number of columns in each row.
This is similar to a matrix.
Declaration and Initialization
int[][] regularArray = new int[3][3]; // 3x3 matrix (3 rows, 3 columns)

or

int[][] regularArray = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

[Link]-Regular Multidimensional Array (Jagged)


A non-regular (jagged) array has different numbers of columns in each row.
This is useful when data structure needs vary per row.
Declaration and Initialization
int[][] jaggedArray = new int[3][]; // Only specify rows

// Assign different column sizes to each row


jaggedArray[0] = new int[2]; // Row 0 has 2 columns
jaggedArray [1] = new int[3]; // Row 1 has 3 columns
jaggedArray [2] = new int[1]; // Row 2 has 1 column
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6} };

.
Key Points about Array:
• Array is a fixed Sized ordered grouping of either primitive or
object references or other arrays.
• Elements must be of same type.
• Must be declared, created and initialized.
• Is a SubClass of java. [Link] and understands all the
methods of that class.
• Array elements can be accessed by index, or positions. Index
starts at 0.
• Array. Length tells the size of the array. Multidimensional arrays
are array of arrays. Each sub-array may be of different size.
• Arrays size may not be required during declaration, but must be
specified at the time of its construction.
• Arrays are automatically initialized at the time of construction
with new Keyword. Each element is initialized to default value.
• Arrays can also be explicitly initialized at the time of their
construction with curly brackets.

Array Methods in Java


Java provides various built-in methods to manipulate and perform operations on
arrays. These methods are mainly available in the java. util. Arrays class.
To use these methods, you need to import:
import [Link];

Method Description
[Link](array) Converts an array to a readable string format.

[Link](array) Sorts the array in ascending order.

[Link](original, start, end) Copies a specific range from the original array.

.
Method Description
[Link](arr1, arr2) Compares two arrays for equality.

Refer text book for more details about above Array methods

How to find the length of an array?


We know that if an array element is referred greater than or equal to the size of the
array, Java throws an exception called
[Link]. ArraylndexOutofBoundsException.
To find out the length of an array, we can use the length instance variable-it’s
available for all array objects, regardless of type:
int[] numbersunew int[10]:
[Link]
How to pass arrays to methods and How methods return arrays?
We can pass arrays to methods similar to how we pass primitive type values to
methods.
Example:
int[] numbers = {10 , 20, 30} ;
printArray (numbers); // This will call below method.

public static void printArray (int[] array) {


for (int i = 0; i < array. length; 1++) {
[Link]. print (array [i] + " ");
}
}

A method may also return an array.

.
Example: method shown below returns an array that is the reversal of another array:
public static int [] reverse (int [] 11st) (
int[] result new int[list. length];
for (1nt J0, 1 result. length-1; 1 > 0; 1--, j++){
result[j] list[1];
}

return result;
}

You might also like