Java 10 – Using var with Arrays and Different Ways to Iterate
Arrays are the most fundamental data structure in Java. Java 10's var keyword works with array declarations too, though with one important nuance: the inferred type will be an array type, not a collection. This tutorial shows you how to declare arrays using var and walks through four standard iteration techniques with practical examples.
Declaring Arrays with var
When you use var with arrays, the compiler infers the full array type — including the element type and the array dimension:
// var infers String[] from new String[]{"a","b","c"}
var names = new String[]{"Laptop", "Smartphone", "Tablet"};
// var infers int[] from new int[]{1, 2, 3}
var prices = new int[]{1000, 2500, 750};
// var infers double[][]
var matrix = new double[][]{{1.0, 2.0}, {3.0, 4.0}};
Important: var names = {"Laptop", "Smartphone"}; does NOT compile because the array initializer shorthand without new Type[] provides insufficient type information for inference. You must use the explicit new String[]{} form.
Complete Example: Four Ways to Iterate an Array
package com.java9r;
import java.util.Arrays;
/**
* Java 10 – Arrays declared with var, iterated four ways.
*/
public class Java10ArraysWithVar {
public static void main(String[] args) {
// Declare a String array with var
var products = new String[]{"Laptop", "Smartphone", "Tablet", "Monitor", "Keyboard"};
// Declare an int array with var
var prices = new int[]{75000, 25000, 35000, 15000, 2500};
System.out.println("Total items: " + products.length);
System.out.println();
// -------------------------------------------------------
// Method 1 : Classic index-based for loop
// Best when you need both index and value simultaneously
// -------------------------------------------------------
System.out.println("1) Index-based for loop (with prices):");
for (var i = 0; i < products.length; i++) {
System.out.printf(" %-12s : Rs. %,d%n", products[i], prices[i]);
}
// -------------------------------------------------------
// Method 2 : Enhanced for-each loop
// Simplest syntax; use when you don't need the index
// -------------------------------------------------------
System.out.println("\n2) Enhanced for-each:");
for (var product : products) {
System.out.println(" " + product);
}
// -------------------------------------------------------
// Method 3 : Arrays.stream() – Stream API
// Best for filtering, mapping, and collecting results
// -------------------------------------------------------
System.out.println("\n3) Arrays.stream() – items containing 't':");
Arrays.stream(products)
.filter(p -> p.toLowerCase().contains("t"))
.sorted()
.forEach(p -> System.out.println(" " + p));
// -------------------------------------------------------
// Method 4 : Arrays.asList() + forEach lambda
// Converts array to List, then iterates with lambda
// -------------------------------------------------------
System.out.println("\n4) Arrays.asList().forEach():");
Arrays.asList(products)
.forEach(p -> System.out.println(" " + p.toUpperCase()));
// Bonus: sorting an array with var
System.out.println("\nSorted product names:");
var sorted = products.clone(); // clone to avoid modifying original
Arrays.sort(sorted);
System.out.println(Arrays.toString(sorted));
// Bonus: IntStream over a primitive int array
System.out.println("\nTotal inventory value (sum of prices):");
var total = Arrays.stream(prices).sum();
System.out.println("Rs. " + String.format("%,d", total));
}
}
Expected Output
Total items: 5
1) Index-based for loop (with prices):
Laptop : Rs. 75,000
Smartphone : Rs. 25,000
Tablet : Rs. 35,000
Monitor : Rs. 15,000
Keyboard : Rs. 2,500
2) Enhanced for-each:
Laptop
Smartphone
Tablet
Monitor
Keyboard
3) Arrays.stream() – items containing 't':
Keyboard (note: contains no 't'... filtered out)
Smartphone
Tablet
4) Arrays.asList().forEach():
LAPTOP
SMARTPHONE
TABLET
MONITOR
KEYBOARD
Sorted product names:
[Keyboard, Laptop, Monitor, Smartphone, Tablet]
Total inventory value (sum of prices):
Rs. 1,52,500
2D Array with var
package com.java9r;
public class Java10TwoDArrayVar {
public static void main(String[] args) {
// var infers int[][]
var grid = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println("3x3 Grid:");
for (var row : grid) {
for (var cell : row) {
System.out.printf("%3d", cell);
}
System.out.println();
}
}
}
Arrays vs ArrayList – When to Use Each
| Feature | Array | ArrayList |
|---|---|---|
| Fixed size | Yes | No (dynamic) |
| Primitives | Yes (int[], double[]) | No (Integer, Double) |
| Add/Remove | Not supported | Supported |
| Performance | Faster for fixed data | Overhead from resizing |
| Stream support | Arrays.stream() | .stream() |
Summary
Java 10's var works with array declarations as long as you use the explicit new Type[]{} initializer form. For simple sequential reads, the enhanced for-each loop is the most readable. Use index-based loops when you need the position, Arrays.stream() for filtering/mapping, and Arrays.sort() with Arrays.toString() for common utility operations. Arrays remain the best choice for fixed-size, performance-sensitive, primitive data — use ArrayList when you need dynamic sizing or richer collection APIs.
Comments