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.

30th Jul 2022, 3:22 PM
Adnan Ur Rehman
Adnan Ur Rehman - avatar
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)".
30th Jul 2022, 3:37 PM
Mustafa A
Mustafa A - avatar
+ 1
Thanks for help
30th Jul 2022, 3:52 PM
Adnan Ur Rehman
Adnan Ur Rehman - avatar
+ 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); } }
30th Jul 2022, 4:20 PM
zemiak
0
zemiak yes you are right . It is stored as object. Thanks for help.
30th Jul 2022, 4:26 PM
Adnan Ur Rehman
Adnan Ur Rehman - avatar