C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: We loop through the Object array with a for-loop. We pass each Object to System.out.println.
Tip: The println can display these Objects because each Object has a toString method. Println uses String.valueOf to call this.
PrintlnJava program that uses Object array
public class Program {
public static void main(String[] args) {
// Add different objects to an Object array.
Object[] elements = new Object[4];
elements[0] = "cat";
elements[1] = 100;
elements[2] = new StringBuilder("abc");
elements[3] = 1.2;
// Print the objects in a for-loop.
for (Object e : elements) {
System.out.println(e);
}
}
}
Output
cat
100
abc
1.2
Then: We can test the "Class extends object" variable in an if-statement. We access each "class" member from the possible types.
IfTests: We test against String.class. Next we try Integer.class, StringBuilder.class and Double.class.
Java program that uses Object array, getClass
public class Program {
static void display(Object[] array) {
for (Object v : array) {
// Get the class object for the element.
Class<? extends Object> c = v.getClass();
// Test the class against known classes.
if (c == String.class) {
System.out.println("Found String: " + v);
} else if (c == Integer.class) {
System.out.println("Found Integer: " + v);
} else if (c == StringBuilder.class) {
System.out.println("Found StringBuilder: " + v);
} else if (c == Double.class) {
System.out.println("Found Double: " + v);
}
}
}
public static void main(String[] args) {
Object[] elements = new Object[4];
elements[0] = "spark";
elements[1] = 500;
elements[2] = new StringBuilder("therapeutics");
elements[3] = 63.5;
// Pass our object array to the display method.
display(elements);
}
}
Output
Found String: spark
Found Integer: 500
Found StringBuilder: therapeutics
Found Double: 63.5
Java program that uses invalid cast, causes error
public class Program {
public static void main(String[] args) {
Object[] elements = new Object[2];
elements[0] = "cat";
elements[1] = "bird";
// This statement causes an error.
String[] values = (String[]) elements;
for (String v : values) {
System.out.println(v);
}
}
}
Output
Exception in thread "main" java.lang.ClassCastException:
[Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at Program.main(Program.java:8)
Warning: This often makes further operations on the array more difficult. But it is sometimes required to pass the data as an argument.
Java program that casts to Object array
public class Program {
public static void main(String[] args) {
String[] codes = new String[2];
codes[0] = "ABC10";
codes[1] = "DEF20";
// We can cast a String array to an Object array safely.
Object[] values = (Object[]) codes;
for (Object v : values) {
System.out.println(v);
}
}
}
Output
ABC10
DEF20