The reason you get [Ljava.lang.String;@1ca6218
on output is because an object's default string representation is its bytecode representation in the JVM.
Since there is no way in the Java language to override array's toString()
, you can create a utility method to make a more appropriate string.
Here is an example for you:
public static String arrayToString(String[] array) {
StringBuilder builder = new StringBuilder();
for (String s : array) builder.append(s).append(" ");
String result = builder.toString();
return result.substring(0, result.length() - 1);
}
You can also use Java's built-in array to string via the Arrays
utility class:
Arrays.toString(myArray)
The reason you get a null pointer or index out of bounds is because your array variable reference is either null
or not to an appropriately sized array.
In your problem, you will need an array of 2 elements, thus new String[2]
You can then use normal assignment and it should work, along with the above method to print out the string.
String[] myArray = new String[2];
myArray[0] = "Hello";
myArray[1] = "there.";
System.out.println(Arrays.toString(myArray));