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
291 views
in Technique[技术] by (71.8m points)

java - Integer as primitive type

Why there is primitive type for integer(int) even though we have an object for integer as Integer? But the same is not with String type. There is no such primitive type for String. Always String deals with object reference?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Speed. It's much faster for machine code to add two int's using native CPU instructions, rather than having to take two Integer objects, extract the int values from them, then add those, creating a new result Integer object to contain the result. (how JNI maps primitives)

Strings are complex, have many methods, and as such have no machine code counterpoint. They are promoted to a true Object. Also, a String shares state with other Strings created with the same value. No primitive value shares state with other primitive values like this. (immutable can be shared | primitive no sharing)


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

...