1

Is there any difference when we initialize a String by using:

  1. java.lang.String
  2. String (only)

Why do we write name of the complete package ?

1
  • 1
    You are not using String or java.lang.String to initialize anything. You are simply using those tokens to name the type. Commented Aug 11, 2011 at 5:07

4 Answers 4

2

There is no difference. The java.lang package is imported implicitly in all java programs.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

hmmm i got it ! Thanks Gapton! :)
1

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 of String 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;
    ...
}

1 Comment

Lol. Gr8 post. Thank you so much Stephen C ! :)
0

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.

1 Comment

Thanks Raghuram! Your post was quite useful. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.