Domanda

I was doing some past papers on my exam and I came accross this question :

What does (String) do on line 5 and what is this type of expression called?

Here is line 5 : String str = (String) D.dequeue ();

My guess is that it's veryfing if the value we get from D.dequeue() is a String though I am not sure.

È stato utile?

Soluzione

This is called Casting. The value returned by the Dequeue method is cast to a String type.

Essentially this operation forces the value to take the type of String so that you can assign it to a variable which is also of type String. You should note however that casting from one type to another may not always succeed.

For example, this will give you a compile-time error:

int a = (int)"123";

Altri suggerimenti

String str = (String) D.dequeue ();

It's called typecasting. Since you are not using generics you are required to typecast the Object before using it as String.

It's actually making an explicit cast of the object returned by D.dequeue() to String (i.e. transforming it into a String instance). Take a look at this explanation: Casting objects in Java

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top