问题
Is there any difference when we initialize a String by using:
- java.lang.String
- String (only)
Why do we write name of the complete package ?
回答1:
There is no difference. The java.lang
package is imported implicitly in all java programs.
回答2:
There is no difference if there is no custom "String" class defined.
If you, however, defined you own "String" class. Then you would need the extra java.lang in order to identify the correct String class.
回答3:
Why do we write name of the complete package ?
In this case, you shouldn't need to.
As @Asaph states, java.lang
is implicitly imported into every class. This means that your code can refer to String
and other classes like Boolean
, System
and NullPointerException
by their simple class names.
The only cases where you would need to refer to String
by its fully qualified name (java.lang.String
) are:
if you are providing the class name as a String in some reflective API, or
if you have stupidly written a class of your own whose simple name is
String
; e.g.com.example.stupid.String
, and you have explicitly imported that version ofString
into some other class.
Best practice is to refer to classes in java.lang
by their simple names, and NOT to define your own classes with the same simple name in other packages.
In the general case, these two forms mean exactly the same thing, and will give you exactly the same compiled code:
// version 1
package com.example.bar;
import com.example.foo.Foo;
public class Bar {
private Foo myFool;
...
}
// version 2
package com.example.bar;
public class Bar {
private com.example.foo.Foo myFool;
...
}
回答4:
No difference
We write the package to distinguish it from a similarly named class, if any, in your project. For instance if your project also has a class named String
, java would not know which String class you want to use - yours or java's inbuilt one.
来源:https://stackoverflow.com/questions/7021027/initializing-a-string-in-java