Arrays in Java
Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of memory management.
For primitive arrays, elements are stored in a contiguous memory location(TBD). For non-primitive arrays, references are stored at contiguous locations, but the actual objects may be at different locations in memory.
Example:
public class Main {
public static void main(String[] args)
{
// initializing array
int[] arr = { 1, 2, 3, 4, 5 };
// size of array
int n = arr.length;
// traversing array
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
Output
1 2 3 4 5
Basics of Arrays in Java
There are some basic operations we can start with as mentioned below:
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 6 integers
int[] numbers = new int[6];
This statement initializes the numbers array to hold 6 integers. The default value for each element is 0.
3. Access an Element of an Array
We can access array elements using their 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.
4. Change an Array Element
To change an element, assign a new value to a specific index:
// Changing the first element to 20
numbers[0] = 20;
5. Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int length = numbers.length;
Now, we have completed with basic operations so let us go through the in-depth concepts of Java Arrays, through the diagrams, examples, and explanations.
The default values for the primitive and non primitive data types in Java are as follows:
*byte: 0
short: 0
int: 0
long: 0L
float: 0.0f
double: 0.0d
char: ‘\u0000’ (null character)
boolean: false
String :null
User-Defined Type:null
*
Following are some important points about Java arrays.
Array Properties(TBD)
In Java, all arrays are dynamically allocated.
Arrays may be stored in contiguous memory [consecutive memory locations].
Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using size of.
A Java array variable can also be declared like other variables with [] after the data type.
The variables in the array are ordered, and each has an index beginning with 0.
Java array can also be used as a static field, a local variable, or a method parameter.
An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class, depending on the definition of the array. In the case of primitive data types, the actual values might be stored in contiguous memory locations (JVM does not guarantee this behavior). In the case of class objects, the actual objects are stored in a heap segment.
Creating, Initializing, and Accessing an Arrays in Java
For understanding the array we need to understand how it actually works. To understand this follow the flow mentioned below:
Declare
Initialize
Access
i. Declaring an Array
The general form of array declaration is
Method 1:
type var-name[];
Method 2:
type[] var-name;
The element type determines the data type of each element that comprises the array. Like an array of integers, we can also create an array of other primitive data types like char, float, double, etc., or user-defined data types (objects of a class).
Note: It is just how we can create is an array variable, no actual array exists. It merely tells the compiler that this variable (int Array) will hold an array of the integer type.
ii. Initialization an Array in Java
When an array is declared, only a reference of an array is created. The general form of new as it applies to one-dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the name of the array variable that is linked to the array. To use new to allocate an array, you must specify the type and number of elements to allocate.
Example:
// declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
iii. Accessing Java Array Elements using for Loop
Now , we have created an Array with or without the values stored in it. Access becomes an important part to operate over the values mentioned within the array indexes using the points mentioned below:
Each element in the array is accessed via its index.
The index begins with 0 and ends at (total array size)-1.
All the elements of array can be accessed using Java for Loop.
Let us check the syntax of basic for loop to traverse an array:
// Accessing the elements of the specified array
for (int i = 0;i < mark.length;i++) {
System.out.println(mark[i]);
total = total + mark[i];
Note: The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Do refer to default array values in Java.
Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.
Advantages(TBD)
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages(TBD)
Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.
Types of Array in java(TBD)
Single Dimensional Array
Multidimensional Array
Reference:https://www.tpointtech.com/array-in-java
Reference:https://www.geeksforgeeks.org/arrays-in-java/
PROGRAM:1
package afterfeb13;
public class mymark {
public static void main(String args[]) {
int[] mark = { 80, 86, 69, 98, 94 };
System.out.println("Array length = "+ mark.length);
float total = 0;
for (int i = 0; i < mark.length; i++) {
System.out.println(mark[i]);
total = total + mark[i];
}
System.out.println("Total = " + total);
System.out.println("Average = " + ((total / 500) * 100));
}
}
OuTPUT:
Array length = 5
80
86
69
98
94
Total = 427.0
Average = 85.399994
PROGRAM:2
package afterfeb13;
public class mark12 {
public static void main(String args[]) {
int[] mark = new int[6];
mark[0] = 163;
mark[1] = 147;
mark[2] = 185;
mark[3] = 150;
mark[4] = 180;
mark[5] = 161;
float total = 0;
for (int i = 0; i < mark.length; i++) {
System.out.println(mark[i]);
total = total + mark[i];
}
System.out.println("Total = " + total);
System.out.println("Average = " + ((total / 1200) * 100));
}
}
OUTPUT:
163
147
185
150
180
161
Total = 986.0
Average = 82.166664
PROGRAM:3
package afterfeb13;
public class my12mark {
public static void main(String args[])
{
int[]mark = {163,147,185,150,180,161};
float total=0;
for(int i=0;i<mark.length;i++)
{
System.out.println(mark[i]);
total=total+mark[i];
}
System.out.println("Total = "+total);
System.out.println("Average = "+((total/1200)*100));
}
}
OUTPUT:
163
147
185
150
180
161
Total = 986.0
Average = 82.166664
Top comments (0)