Java (String) - what does it do?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 08:08:34

问题


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.


回答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";



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/23594026/java-string-what-does-it-do

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!