System.out.println(marks[0]); // Output: 88
System.out.println(marks[2]); // Output: 91
public class MainApp1
{
public static void main(String[] args)
{
// 1. Declare and create an array of size 6
int[] marks = new int[6];
// 2. Initialize array elements
marks[0] = 88;
marks[1] = 74;
marks[2] = 91;
marks[3] = 82;
marks[4] = 68;
marks[5] = 94;
// 3. Access and print array elements using normal for loop (Way 1)
System.out.print("Way 1: ");
for (int i = 0; i < marks.length; i++)
{
System.out.print(marks[i] + " ");
}
System.out.println(); // Move to next line
// 4. Access and print array elements using for-each loop (Way 2)
System.out.print("Way 2: ");
for (int no : marks)
{
System.out.print(no + " ");
}
System.out.println(); // Move to next line
}
}
Way 1: 88 74 91 82 68 94 Way 2: 88 74 91 82 68 94
public class MainApp2
{
public static void main(String[] args)
{
// 1. Declare and create an array using shorthand notation
// This automatically initializes the array with the given values
int[] marks = {88, 74, 91, 82, 68, 94};
// 2. Access and print array elements using a for-each loop
// The variable 'no' takes the value of each element sequentially
System.out.print("Marks are: ");
for (int no : marks)
{
System.out.print(no + " "); // Print each element
}
}
}
Marks are: 88 74 91 82 68 94
When we create arrays in Java, they are handled in memory in a specific way. Let's understand the key memory concepts behind arrays:
new
keyword.
int[] numbers = new int[3];
numbers
in the below code) is stored in the stack memory, and it points to the array object in the heap.
int[] numbers = new int[3];
numbers
(reference) β
int[] numbers = {10, 20, 30};
String[] names = {"amit", "deepak", "rahul"};
int[] numbers = {10, 20, 30};
int[][] matrix = {{1,2}, {3,4}};
int[][] jagged = {{1,2,3}, {4,5}, {6}};
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.