Printing Array Elements
Basic Printing Methods
Using Simple For Loop
public class ArrayPrinting {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Traditional for loop
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
Enhanced For Loop (For-Each)
public class EnhancedPrinting {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Cherry"};
// Enhanced for loop
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Advanced Printing Techniques
Using Arrays.toString() Method
import java.util.Arrays;
public class ArrayUtilPrinting {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Prints entire array in a single line
System.out.println(Arrays.toString(numbers));
}
}
Printing Multidimensional Arrays
2D Array Printing
public class MultiDimensionalPrinting {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Nested loop printing
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println(); // New line after each row
}
}
}
Printing Techniques Comparison
| Method |
Pros |
Cons |
| Traditional For Loop |
Full control |
More verbose |
| Enhanced For Loop |
Cleaner syntax |
Cannot modify array |
| Arrays.toString() |
Quick and simple |
Limited formatting |
Special Printing Scenarios
graph TD
A[Array Printing Methods] --> B[Basic Printing]
A --> C[Formatted Printing]
A --> D[Conditional Printing]
B --> E[Simple output]
C --> F[Aligned columns]
D --> G[Filtered elements]
public class FormattedPrinting {
public static void main(String[] args) {
double[] measurements = {10.5, 20.3, 15.7, 30.2};
// Custom formatting
for (double value : measurements) {
System.out.printf("Measurement: %.2f\n", value);
}
}
}
Error Handling in Array Printing
public class SafePrinting {
public static void printArray(int[] arr) {
if (arr == null) {
System.out.println("Array is null");
return;
}
for (int value : arr) {
System.out.print(value + " ");
}
}
}
Learning with LabEx
Practice these array printing techniques in the LabEx Java programming environment to enhance your understanding of array manipulation and output strategies.