String Array
Make an array of words.
1import java.util.Arrays;
2
3public static void main(String[] args) {
4 String[] arr = {"hello", "world", "!"};
5 System.out.println(Arrays.toString(arr));
6}
$ javac Main.java
$ java Main
[hello, world, !]
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.
String[] arr = {"hello", "world", "!"};- String[] declares an array of text values. Each String still needs its own double quotes. arr[0] is "hello", arr[1] is "world" and arr[2] is "!".
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 }.