Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

java - Implicit cast to string - toString and int + ""

Why when i use this:

int a = 1;
methodWithParamString(a + "");

a is cast to String, bu i can't use toString() on integer?

int a = 1;
methodWithParamString(a.toString());

Doesn't this: a+"" works like: a.toString() + "" ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, it works like String.valueOf( a ) + "", which in turn behaves like new StringBuilder( String.valueOf( a ) ).append( "" ).toString().

The important thing to know is that it's all just done by the compiler, in other words it's syntactic sugar. This is why adding strings together in a loop isn't a good idea for example. (Although modern VMs might have some mechanism to reduce the performance overhead.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...