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

java - In JDK 1.6, can String equals operation can be replaced with ==?

As I study the source code of some open source products, I find code like:

if (a=="cluser")

a is a String variable. Can a String equals operation be replaced with ==?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You should almost never use == and almost always use equals(). It will only work with == if both strings reference the same object. There's an intern() method on String to return the same reference for a given string value. String literals are implicitly interned. Only if you have a very good reason should you use == for string comparison, and even then you need to be very careful.

The only good reason is performance, and very rarely will it matter. Only optimize once you know for sure that you need to do so. It's otherwise normally not worth the hassle. If you're looking at some open source code, they might have a case whereby the comparison is in a very tight loop or called very frequently and the optimization can help. Or it was just prematurely optimized and maybe seemed safe.


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

...