0
Java string
Hello, I have been doing a problem in hackarrank and there was an arraylist of objects in it. Those objects contain integers as well as string. Solve element = new Solve(); System.out.print((String)element); Solve was the name of class and this above code was printing the string value available at that object. My question is that what is the purpose of this (String)element I know element is object name but what is the use of (String) here.
4 Answers
+ 1
It's type casting. You don't need to cast it implicitly. The "toString" method of the class will be called either way, with or without "(String)".
+ 1
Thanks for help
+ 1
I assume that it is a situation where
The String is stored as its superclass Object
int is also stored as Object
but before use, it must be cast (converted) back to its original type
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<>();
list.add( "element 0");
list.add( 100);
Object element = list.get(0);
System.out.print( (String) element);
}
}
0
zemiak yes you are right . It is stored as object. Thanks for help.