1

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.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
Bumblebee
  • 25
  • 5
  • 3
    The keyword is casting. Read the section Casting Objects: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html. Also it seems that you are using a raw collection. Don't if you can use generics. – Alexis C. May 11 '14 at 14:51

3 Answers3

1

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";
shree.pat18
  • 21,449
  • 3
  • 43
  • 63
0
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.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

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

Community
  • 1
  • 1
RedCH
  • 96
  • 1
  • 3