Coding for All
Lesson 16: Mixed Type Array
Mixed Type Array One array holding text, a number and a boolean.
1import java.util.Arrays;
2
3public static void main(String[] args) {
4 Object[] arr = {"hello", 2, false};
5 System.out.println(Arrays.toString(arr));
6}
Terminal
$ javac Main.java
$ java Main
[hello, 2, false]
Every line, explained
import java.util.Arrays;
import lines go at the very top of a Java file and bring in extra tools. java.util.Arrays is a helper class full of useful methods for working with arrays; we need it for Arrays.toString below.
public static void main(String[] args) {
Every Java program starts at the main method. When you run the program, Java looks for this exact line, public static void main(String[] args), and runs everything between its { and } from top to bottom.
Object[] arr = {"hello", 2, false};
Object is the most general type in Java: every other type (String, Integer, Boolean, ...) is also an Object. So an Object[] array can mix text, numbers and booleans. Usually you keep an array to one type, but this shows that everything in Java descends from Object.
System.out.println(Arrays.toString(arr));
Careful: printing an array directly, System.out.println(arr), does NOT show its contents in Java! It prints a strange code like [I@1b6d3586 (the exact letters depend on the array's type). Arrays.toString(arr) converts the array into readable text like [1, 2, 3] first, and that is what we print.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.