Arrays and strings
An array holds a fixed number of values of one type. Strings are Java's text type, with a rich set of methods. Both show up in nearly every program.
Arrays
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] scores = {70, 92, 55, 88}; // create with values
String[] names = new String[3]; // create empty: 3 slots, all null
names[0] = "Asha";
names[1] = "Rahul";
names[2] = "Priya";
System.out.println(scores[0]); // indexes start at 0
System.out.println(scores[scores.length - 1]);
System.out.println(scores.length);
System.out.println(Arrays.toString(names));
scores[2] = 60;
System.out.println(Arrays.toString(scores));
}
}70 88 4 [Asha, Rahul, Priya] [70, 92, 60, 88]
An array's size is fixed when it's created. If you need a list that grows, use an ArrayList (see the Collections lesson).
Going outside the array is a run-time error:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]);
}
}Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at Main.main(Main.java:4)
Read stack traces from the top: the exception type, the message, then where it happened (Main.java:4).
Looping over arrays
public class Main {
public static void main(String[] args) {
double[] prices = {899, 59.99, 45.5, 8.99};
double total = 0;
double max = prices[0];
for (double p : prices) {
total += p;
if (p > max) max = p;
}
System.out.printf("Total %.2f, average %.2f, max %.2f%n", total, total / prices.length, max);
for (int i = 0; i < prices.length; i++) { // when you need the index
System.out.println(i + ": " + prices[i]);
}
}
}Total 1013.48, average 253.37, max 899.00 0: 899.0 1: 59.99 2: 45.5 3: 8.99
The Arrays helper class
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {42, 7, 19, 3, 25};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.binarySearch(nums, 19)); // index of 19 (array must be sorted)
int[] copy = Arrays.copyOf(nums, 3);
System.out.println(Arrays.toString(copy));
int[] zeros = new int[5];
Arrays.fill(zeros, 7);
System.out.println(Arrays.toString(zeros));
System.out.println(Arrays.stream(nums).sum() + " " + Arrays.stream(nums).max().getAsInt());
}
}[3, 7, 19, 25, 42] 2 [3, 7, 19] [7, 7, 7, 7, 7] 96 42
2D arrays
public class Main {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
System.out.println(grid[1][2]); // row 1, column 2
for (int[] row : grid) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}6 1 2 3 4 5 6 7 8 9
Strings in depth
Strings are immutable: methods like toUpperCase() return a new string and leave the original unchanged.
public class Main {
public static void main(String[] args) {
String s = " Hello, World! ";
String t = s.trim();
System.out.println("[" + t + "]");
System.out.println(t.length());
System.out.println(t.toLowerCase());
System.out.println(t.substring(7)); // from index 7 to the end
System.out.println(t.substring(0, 5)); // from 0 up to (not including) 5
System.out.println(t.indexOf("World"));
System.out.println(t.replace("World", "Java"));
System.out.println(t.startsWith("Hello") + " " + t.endsWith("?"));
System.out.println("ab".repeat(3));
System.out.println("".isEmpty() + " " + " ".isBlank());
System.out.println(s); // unchanged
}
}[Hello, World!] 13 hello, world! World! Hello 7 Hello, Java! true false ababab true true Hello, World!
Splitting, joining and comparing
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String csv = "Asha,31,Bengaluru";
String[] parts = csv.split(",");
System.out.println(Arrays.toString(parts));
System.out.println(parts[0] + " lives in " + parts[2]);
System.out.println(String.join(" | ", "Java", "Python", "Go"));
System.out.println("apple".equals("Apple"));
System.out.println("apple".equalsIgnoreCase("Apple"));
System.out.println("apple".compareTo("banana") < 0); // alphabetical order
for (char c : "Java".toCharArray()) {
System.out.print(c + "-");
}
System.out.println();
System.out.println(String.format("%-8s|%5.1f|", "Total", 9.5));
}
}[Asha, 31, Bengaluru] Asha lives in Bengaluru Java | Python | Go false true true J-a-v-a- Total | 9.5|
StringBuilder for building strings
Because strings are immutable, += in a loop creates a new string every time, which is slow for thousands of iterations. Use a StringBuilder:
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i);
if (i < 5) sb.append(", ");
}
System.out.println(sb);
System.out.println(sb.reverse());
System.out.println(new StringBuilder("racecar").reverse().toString().equals("racecar"));
}
}1, 2, 3, 4, 5 5 ,4 ,3 ,2 ,1 true
Text blocks
Java 15+ supports multi-line text blocks with triple quotes, which are handy for JSON, SQL and HTML:
public class Main {
public static void main(String[] args) {
String json = """
{
"name": "Asha",
"skills": ["Java", "SQL"]
}
""";
System.out.print(json);
}
}{
"name": "Asha",
"skills": ["Java", "SQL"]
}The common indentation is removed automatically.
Practice
- Find the second-largest number in an
int[]without sorting it. - Count the vowels in a sentence.
- Check whether a word is a palindrome, ignoring case.
- Reverse the order of words in
"Java is really fun"→"fun really is Java".
1.What's the index of the last element of an array a?
2.What does "hello".toUpperCase() do to the original string?
3.Why use StringBuilder when building a string in a loop?