In a jLabel component, say I have this codes,
JLabel jLabel = new JLabel();
jLabel.setText( 123 ) ;
It generates error. But writing this,
jLabel.setText( 123 + "" ) ;
force to int part to be a string. But I don't think w开发者_JS百科riting int like that way is a good idea! Does this method has any overloaded siblings grasping not a String?
Not much you can do here, setText
only takes a String
parameter. Alternatively, you could do jLabel.setText(Integer.toString(123))
, if you find this more readable.
As for 123 + ""
part, whenever you add some variables and at least one of them is a String
, the compiler will automatically call toString
on the others and will concatenate all the strings. somevar + ""
(empty string) is a quick way of calling somevar.toString()
.
The compiler is correct. You are passing a number to a method that wants the string. The reason the second method works is that the jvm is taking the number and the string, and adding them together, which returns a string, which is why it works. Your other option is to do something Integer.toString(123);
精彩评论