int[] marks = {88, 74, 91, 82, 68, 94};
int
, float
, String
, etc.).
dataType[] arrayName;
int[] marks;
String[] names;
dataType arrayName[];
dataType []arrayName;
int marks[];
int []marks;
new
keyword in Java.
arrayName = new dataType[size];
marks = new int[6];
names = new String[6];
dataType[] arrayName = new dataType[size];
int[] marks = new marks[6];
String[] names = new String[6];
0
for int
, 0.0
for float
, null
for objects).
arrayName[index] = value;
marks[0] = 88;
marks[1] = 74;
marks[2] = 91;
marks[3] = 82;
marks[4] = 68;
marks[5] = 94;
dataType[] arrayName = {value1, value2, value3, ...};
int[] marks = {88, 74, 9182, 68, 94};
int[] marks = new int[]{88, 74, 9182, 68, 94};
0
and the last element is at index array.length - 1
.
System.out.println(marks[0]); // Output : 88
System.out.println(marks[3]); // Output : 82
for(int i = 0; i < numbers.length; i++) {
System.out.println(marks[i]);
}
for(int num : marks) {
System.out.println(num);
}
Arrays.toString()
(for displaying entire array):
System.out.println(Arrays.toString(numbers)); // Output: [10, 20, 30, 40, 50]
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
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.