Java String Casting Program
The Cast2 program provides an example of String casting. The String "abc" is created and assigned to the s variable. This object is then added to Vector v.
The object is retrieved from v, (implicitly) cast as a reference to an Object object, and assigned to the o variable. The object is then cast back to a String and assigned to the t variable.
The result displayed by the program is "abc". If you think that casting is not needed in this example, try to compile the program without the (String) cast operator, and you will receive a compilation error.
Cast2
import java.util.*;
public class Cast2 {
public static void main(String[] args) {
String s = "abc";
Vector v = new Vector();
v.addElement(s);
Object o = v.elementAt(0);
String t = (String)o;
System.out.println(t);
}
}