Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default package in which my classes are put if I don't specify it?

Let's assume I have a file named Main.java with the following code:

public class Main {     public static void main(String[] args) {         System.out.println("Hello world");     } } 

Is it put in a specific package, in (maybe?) an unnamed package?

Thanks

like image 848
devoured elysium Avatar asked Feb 25 '10 15:02

devoured elysium


People also ask

What is the default package and default class in Java?

lang Package. Java compiler imports java. lang package internally by default.

Which package is default package?

The default package is a collection of java classes whose source files do not contain and package declarations. These packages act as the default package for such classes. It provides the ease of creating small applications when the development of any project or application has just begun.

Which package is the default package in Java?

java. lang. The package in which the current class is located (in the case of the above code, this is ostensibly the default package, from which you can't otherwise import explicitly).

What is the default package in Eclipse?

If you've been using Eclipse already, you'll probably notice that new classes you create don't simply appear. They appear under a node in the hierarchy called "default package". This is because if you don't specify a package for your class, it will be grouped with all other non-packaged classes in this default package.


2 Answers

A class that is not in a named package is in an unnamed package. Thus the full class name is Main.

Such classes cannot be used from a named package, except via reflection.

The JLS says that:

Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development.

like image 112
Lachlan Roche Avatar answered Oct 12 '22 11:10

Lachlan Roche


Java does not have namespaces, it has packages. And yes, classes with no package declarations are implicitly part of an "unnamed package", often also called "default package". However, since it's not possible to import classes from an unnamed package and since the language spec explicitly allows implementations to have different rules about whether and how classes in unnamed packages are visible to each other, it's generally a good idea to put all classes in named packages except for experimental code.

like image 34
Michael Borgwardt Avatar answered Oct 12 '22 13:10

Michael Borgwardt