Java for Everyone... Arrays

Java for Everyone... Arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Declaring a Variable to Refer to an Array

// declares an array of integers

int[] MyFirstArray;

·?????? An array declaration has two components: the array's type and the array's name.

·?????? An array's type is written as type[], where type is the data type of the contained elements

·?????? The brackets are special symbols indicating that this variable holds an array.

·?????? The size of the array is not part of its type (which is why the brackets are empty).

·?????? An array's name can be anything you want as per convention , please refer to this official link.

·?????? Please note that the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.

Similarly, you can declare arrays of other types:

byte[] anArrayOfBytes;

short[] anArrayOfShorts;

long[] anArrayOfLongs;

You can also place the brackets after the array's name:

float anArrayOfFloats[];// this form is discouraged

  1. Declaration and Initialization Together

int[] numbers = {11, 10, 19, 87};// Integer array

String[] names = {"Mr Arjun ", "Mr. Mandal", "Mr Jai L"};// String array

double[] prices = {99.89, 49.99, 9.99};//// Double array

2. Declaration and Initialization Separately

You can declare the array first, then initialize it later, please refer below-

int[] numbers;??????? // Declaration

numbers = new int[3];? // Initialization with size 5

// Assigning values

numbers[0] = 11;

numbers[1] = 10;

numbers[2] = 19;

numbers[3] = 87;

// Accessing elements

System.out.println(numbers[0]); // Output: 11

A Basic Program
public static void main(String[] args) {
		// 1D array
		int[] numbers = { 11, 10, 19, 87 };
		System.out.println("Print My first 1D array");
		for (int i = 0; i < numbers.length; i++) {
			System.out.println("Element at index " + i + "" + numbers[i]);
		}
		// 2D array
		int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
		System.out.println("\n Print My first 2D array:");
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				System.out.print(matrix[i][j] + " ");
			}
			System.out.println();
		}
	} 
output
Print My first 1D array
Element at index 011
Element at index 110
Element at index 219
Element at index 387

 Print My first 2D array:
1 2 3 
4 5 6 
7 8 9         

3. Using the new Keyword with Explicit Values

This is a hybrid approach where you declare and initialize using the new keyword and provide values.

int[] numbers = new int[] {10, 20, 30, 40, 50};

int[][] matrix = new int[3][3]; // 3x3 matrix

// Assigning values

matrix[0][0] = 1;

matrix[0][1] = 2;

matrix[0][2] = 3;

4. Default Initialization

If you only declare and initialize an array without assigning values, it gets initialized with default values based on its type.

int[] numbers = new int[5]; // Default values: [0, 0, 0, 0, 0]

boolean[] flags = new boolean[3]; // Default values: [false, false, false]

String[] names = new String[4]; // Default values: [null, null, null, null]

5. Using a Loop for Initialization

int[] numbers = new int[5];

for (int i = 0; i < numbers.length; i++) {

??? numbers[i] = i * 11; // Assign multiples of 11

}

// Output the values

for (int number : numbers) {

??? System.out.println(number);

}

6. Array Inside a Method

In Java, arrays can be passed as method arguments to allow the method to work with multiple values. Arrays are passed by reference, meaning the method receives a reference to the actual array, not a copy of it. This allows the method to modify the contents of the original array if needed

You define a method that takes an array as an argument like this:

returnType methodName(dataType[] arrayName) { // method body }

  public static void main(String[] args) {
        int[] numbers = {11,10,19,87};
        // Call the method
        modifyArray(numbers);
        // Print the modified array
        for (int num : numbers) {
            System.out.println(num);
        }
    }
    // Method to modify array elements
    public static void modifyArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * 41;  // Multiply each element by *41
        }
    }        

Loops in Array

In Java, the iteration loop and for loop generally refer to the different ways to iterate over elements or execute a block of code multiple times. However, they can be used interchangeably depending on the context. Let’s break down the differences and usage scenarios for each:

  1. for Loop (Traditional For Loop)

The for loop is a general-purpose loop that gives you full control over initialization, condition checking, and iteration.

Syntax-

for (initialization; condition; increment/decrement) {

??// Code to execute

}

Initialization: Defines a variable (usually a counter) and sets it to a starting value.

Condition: Specifies the condition for the loop to run. The loop continues as long as the condition is true.

Increment/Decrement: Modifies the counter variable after each iteration.

// Print numbers 1 to 9

for (int i = 1; i <= 9; i++) {

??? System.out.println(i);

}

Explanations- Starts with i = 1, continues while i <= 9, and increments i after each iteration until i becomes 10.

2. Enhanced For Loop (aka For-Each Loop)

Syntax

for (datatype element : array_or_collection) {

??? // Code to execute using 'element'

}

datatype: The type of each element in the array/collection (e.g., int, String, etc.).

element: A variable that holds the current element of the array or collection during each iteration.

array_or_collection: The array or collection being iterated.

Examples-

Ex1-
// Iterate through an array using enhanced for loop
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
} 
Ex2-
String[] colors = {"Red", "Green", "Blue"};
for (String color : colors) {
    System.out.println(color); // Access each element directly
}        

Use the Traditional for Loop:

·??? When you need to access the index of elements.

·????When iterating with a non-array or collection, or when the loop's starting index or termination condition is non-trivial.

·???When working with multi-dimensional arrays or complex iteration patterns.

Use the Enhanced for Loop:

·????When iterating over collections or arrays and you don’t need to manipulate the index.

·??? For simpler, more readable code where you just need to process each element.

Key features of arrays in Java

  1. Fixed Size -Once an array is created, its size cannot be changed.
  2. Homogeneous Elements-An array can store only elements of the same type.
  3. Zero-Based Indexing-The first element of an array is accessed using index 0 & last one using index length -1.
  4. Continuous Memory Allocation-This ensures efficient random access using an index.
  5. Default Values-Arrays are automatically initialized with default values, refer Numeric types (int, float, etc.) → 0, Boolean → false, Reference types (String, objects) → null, int[] nums = new int[3]; // Default values: [0, 0, 0].
  6. Multi-Dimensional Arrays-Arrays can have more than one dimension, such as 2D or 3D arrays
  7. Supports Primitive and Object Types-Arrays can store both primitive types (int, char, etc.) and objects (String, custom classes), String[] names = {"Arjun", "Mandal"};
  8. Length Property-Every array has a built-in length property that provides its size.
  9. Random Access-Array elements can be accessed directly using their index.
  10. Cloneable and Serializable-Arrays in Java are cloneable, allowing them to be duplicated.
  11. Mutable-While the size of an array is fixed, the elements of the array can be modified.
  12. Type Safety-Arrays are type-safe, meaning you cannot store elements of a different type in an array-int[] numbers = new int[5] // numbers[0] = "Hello"; // Compile-time error
  13. Supports Iteration-Arrays can be iterated using loops (e.g., for, while, enhanced for loop).
  14. Performance-Arrays provide fast access to elements due to their contiguous memory layout and random access feature.
  15. Backward Compatibility-Arrays have been part of Java since its inception, making them a fundamental and widely used data structure.

Also note-

Size Specification-You cannot resize an array after it is initialized. For dynamic resizing, use collections like ArrayList.

Default Values: Primitive types (int, float, etc.) are initialized to 0.

Boolean arrays are initialized to false.

Reference types (e.g., String, Integer) are initialized to null.

Out-of-Bounds Error:Accessing an index outside the array bounds will throw an ArrayIndexOutOfBoundsException.

/*

This is article is based on JDK 8, any changes on features, enhancement or deprecated options can be referred to official release notes-

https://www.oracle.com/java/technologies/javase/jdk-relnotes-index.html

https://dev.java/learn/

*/



要查看或添加评论,请登录

Arjun K.的更多文章

  • Java OOPs...Encapsulation!

    Java OOPs...Encapsulation!

    Consider a real-life example of your bank account, your account balance is private—you wouldn’t want anyone to directly…

  • Little’s Law in Performance Testing

    Little’s Law in Performance Testing

    In 1954, John Little published a paper in which he described the queueing theory by a new law. Later, it is named…

  • Performance Metrics- Throughput, latency and response time!

    Performance Metrics- Throughput, latency and response time!

    Throughput Throughput serves as a crucial performance metric for assessing system efficiency, identifying bottlenecks…

  • Application Performance Improvement using CAST SQG formerly AIP.

    Application Performance Improvement using CAST SQG formerly AIP.

    ??What is CAST Structural Quality Gate (SQG) formerly AIP ? CAST SQG draws on CAST’s extensive experience in deep…

  • Performance Test-An Overview!

    Performance Test-An Overview!

    Performance testing is a type of software testing that focuses on how well an application performs under various…

  • Software Performance Test - An Overview!

    Software Performance Test - An Overview!

    Performance testing is a type of software testing that focuses on how well an application performs under various…

  • Compile-time & Runtime Errors in Java..

    Compile-time & Runtime Errors in Java..

    Compile-time A compile-time error in Java refers to an error that occurs during the compilation phase, when the Java…

  • Java for Everyone...Encapsulation.

    Java for Everyone...Encapsulation.

    Consider a real-life example of your bank account. Your account balance is private—you wouldn’t want anyone to directly…

  • Java Collection Framework in Selenium

    Java Collection Framework in Selenium

    In Selenium WebDriver, Java collections play a crucial role in managing and manipulating data such as lists of web…

  • Java for Everyone... StringBuilder & StringBuffer

    Java for Everyone... StringBuilder & StringBuffer

    StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated…

社区洞察

其他会员也浏览了