Java explicit casting on list.get(0) (incompatible types: java.lang.Object cannot be converted to java.lang.String)

The following code is mentioned in the Java Tutorials :-(https://docs.oracle.com/javase/tutorial/java/generics/why.html)

List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);

The casting in the last line suggests that list.get(0) does not return a String. Now, since list was not declared with any data type, it can take in any object. So I assumed that list.get(0) returns an Object type.

But when I check list.get(0) instanceof String --> it returns true.

Why is then the explicit casting required. Please explain.


So I assumed that list.get(0) returns an Object type.

Yes it does.

But when I check list.get(0) instanceof String --> it returns true.

Yes, it should return true because the item at index 0 of the list is a String.

Why is then the explicit casting required.

it's required simply because the list contains Objects and not every Object from the list is guaranteed to be a String. The explicit cast is required so that you can assign the reference of list.get(0) to s (a variable of type String).

On Java 8, And although you cannot create an actual array object that holds generics, you the non-generified type and cast it: // arrays/ArrayOfGenerics.java import java.util. new List[10]; ls = (List<String>[])la; // Unchecked cast ls[0] = new ArrayList<>(); incompatible types: ArrayList<Integer>// cannot be converted to List<String>//  Type Casting in Java is nothing but converting a primitive or interface or class in Java into other type. There is a rule in Java Language that classes or interface which shares the same type hierrachy only can be typecasted. If there is no relationship between then Java will throw ClassCastException. Type casting are of two types they are


The casting in the last line suggests that list.get(0) does not return a String.

That's inaccurate. If the returned object wasn't a String, then casting wouldn't have been possible. In other words, you can only cast something to String if that something is a String. Try casting something else, you'll see:

Object i = Integer.valueOf(5);
String j = (String)i; //Exception!

The cast is needed in your code because list.get(0) returns an Object type, but we want to assign it to a String s. We as the programmers know that the Object returned from the list is in fact a String, but the compiler doesn't. The compiler just sees this:

Object l = list.get(0);
String s = l;

The second line cannot compile without an explicit cast to String.

And just for clarification.. you'll never see such code in the real world unless you're working on something seriously old. Java has generics since Java 5 (2004), so 15 years now. At this point you really shouldn't see List without it being List<SomeType> (e.g. List<String>)

Code compiles in java8 but not in java9 : "incompatible types: java , Error:(20, 113) java: incompatible types: java.lang.Object cannot be converted to /​package name here/.Base ERROR MESSAGES/STACK  java.lang.ClassCastException: com.baeldung.casting.Dog cannot be cast to com.baeldung.casting.Cat This means that we are trying to convert an object which is an instance of Dog into a Cat instance. ClassCastException' s always thrown at runtime if the type we downcast to doesn't match the type of the real object.


The List list = new ArrayList(); is an unparameterized type (which you want to avoid), meaning it can take any Object.

Since your list contains any Objects, list.get(0); can only know that it's returning an Object and doesn't know that the element at 0 is actually a String. Since it doesn't know that it's really a String the compiler warns you that you're doing an unchecked cast from Object to String.

list.get(0) instanceof String returns true because it's a runtime check that the element at 0 is in fact a String.

How to fix java.lang.classcastexception cannot be cast to in Java, ClassCastException in Java by using Generics and writing type-safe parameterized If you see closely we were trying to cast an String object into an Integer to provide type-safety. look for all places where you have used cast java.lang.classcastexception ljava.lang.object cannot be cast to java.util.list operator < cannot be applied to java.lang.Object,java.lang.Object This often happens when the Java code tries to use a type string in a calculation. To fix it, the string needs to be converted to


error: incompatible types: Object cannot be converted to · Issue , I have defined in my root XML data class an element an annotated it with @​element . error: incompatible types: Object cannot be converted to . Synchronization Found: java.lang.Object. In the TypeAdapter of the main XML file there and it looks like there is no cast to Synchronization object like in a list. Type conversion in Java with Examples When you assign value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and if not then they need to be casted or converted explicitly.


Java Tutorials, Runtime exception - cannot be cast // Integer e2 = li2.get(0); // o.println(" First you will get: Testing: <T> List<T> singletonList(T o) Class name of ls: java.util. type of the type parameter, T, should be String based on the input object. types: inference variable T has incompatible bounds List<String> ls1 = Collections. Java Type Casting. Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size byte-> short-> char-> int-> long-> float-> double; Narrowing Casting (manually) - converting a larger type to a smaller


Java Programming, However, unless you have overridden the toStri ng () method within a class, the St Collections.sort(students); To use this method, you must import the java. util . drawbacks: 0 You cannot use an ArrayLi st to store primitive types such as int, a cast with Ar rayLi st objects by specifying the type that an Ar rayLi st can hold. C:JavaInterestCalculator.java:49: error: incompatible types: String cannot be converted to double rate = formatter.format(rate); ^ C:JavaInterestCalculator.java:52: error: incompatible types: String cannot be converted to double totalInterest = formatter.format(totalInterest); ^ 3 errors Tool completed with exit code 1 And here is my code