I have one doubt. When we use ArrayList or HashMap in Java, we have to import java.util.ArrayList or java.util.HashMap. But when we use String, it doesn't require the import statement. Can anyone clarify, why?
String is present in package java.lang which is imported by default in all java programs.
Everything in the java.lang package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util package, which is not implicitly imported.
The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.
Java compiler imports 3 packages by default.
1. The package without name
2. The java.lang package(That's why you can declare String, Integer, System classes without import)
3. The current package (current file's package)
That's why you don't need to declare import statement for the java.lang package.
I'm bit late here, but just for new reader, According to my understanding
String is present in package java.lang which is imported by default at class loading time by rt.jar which is present at class path. Bootstrap Classloader (Primodial ClassLoader) is responsible for loading rt.jar.
We always include rt.jar in our classpath, otherwise, you don't have access to core java classes e.g. java.lang.String, java.lang.Thread, java.util.ArrayList or java.io.InputStream etc. and all other classes from Java API.
rt.jar will always reside under $JAVA_HOME/jre/lib and you can open it by using WinRAR or WinZip client
import java.lang.String;
This is an unnecessary import. java.lang classes are always implicitly imported.
This means that you do not have to import them manually (explicitly).
Related
I'm working now together with others in a grails project. I have to write some Java-classes. But I need access to an searchable object created with groovy. It seems, that this object has to be placed in the default-package.
My question is: Is there a way to access this object in the default-package from a Java-class in a named package?
You can’t use classes in the default package from a named package.
(Technically you can, as shown in Sharique Abdullah's answer through reflection API, but classes from the unnamed namespace are not in scope in an import declaration)
Prior to J2SE 1.4 you could import classes from the default package using a syntax like this:
import Unfinished;
That's no longer allowed. So to access a default package class from within a packaged class requires moving the default package class into a package of its own.
If you have access to the source generated by groovy, some post-processing is needed to move the file into a dedicated package and add this "package" directive at its beginning.
Update 2014: bug 6975015, for JDK7 and JDK8, describe an even stricter prohibition against import from unnamed package.
The TypeName must be the canonical name of a class type, interface type, enum type, or annotation type.
The type must be either a member of a named package, or a member of a type whose outermost lexically enclosing type is a member of a named package, or a compile-time error occurs.
Andreas points out in the comments:
"why is [the default package] there in the first place? design error?"
No, it's deliberate.
JLS 7.4.2. Unnamed Packages says: "Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development".
In fact, you can.
Using reflections API you can access any class so far. At least I was able to :)
Class fooClass = Class.forName("FooBar");
Method fooMethod = fooClass.getMethod("fooMethod", String.class);
String fooReturned = (String)fooMethod.invoke(fooClass.newInstance(), "I did it");
Use jarjar to repackage the jar file with the following rule:
rule * <target package name>.#1
All classes in the default package of the source jar file will move to the target package, thus are able to access.
You can use packages in the Groovy code, and things will work just fine.
It may mean a minor reorganization of code under grails-app and a little bit of a pain at first, but on a large grails project, it just make sense to organize things in packages. We use the Java standard package naming convention com.foo.<app>.<package>.
Having everything in the default package becomes a hindrance to integration, as you're finding.
Controllers seem to be the one Grails artifact (or artefact) that resists being put in a Java package. Probably I just haven't figured out the Convention for that yet. ;-)
just to complete the idea:
From inside default-package you can access objects resided in named packages.
This question is related to setting up an IntelliJ environment for Princeton's Algorithms 2 course available on Coursera.
I am trying to import external libraries, as JARs, into my project. I was able to add the JARs from the Project Structure menu via Project Structure -> Libraries -> New Project Library (the green plus sign). Now I have a class under src, WordNet.java, but I can only access my external libraries using the default package (ie no package). I would like to create packages to organize my code, but how can I import the external libraries from inside a package? Is there a simple solution to directly import the JAR's, or perhaps I can use Maven or Grails? Providing a simple answer for all of my options would be great.
I have the following project structure, with a src directory, src/assignemnt1 package, and External Libraries/stdlib/stdlib.jar external library:
My class that uses the external libraries, WordNet.java, has code as follows:
public class WordNet {
// constructor takes the name of the two input files
public WordNet(String synsets, String hypernyms) {
In read_synsets = new In(synsets);
read_synsets.hasNextLine();
}
}
Where In is a class under stdlib.jar. Under the default package, I can use In without importing. Unfortunately, if I have WordNet.java under src/assignment1 (inside the assignment1 package), I cannot seem to import In and IntelliJ offers no import suggestions either. Is there a way to use stdlib.jar within WordNet.java, inside the src/assignment1 package? Or do I have to stay withing the default package?
The Java language specification forbids any imports from the unnamed, or default, package.
A type in an unnamed package (§7.4.2) has no canonical name, so the requirement for a canonical name in every kind of import declaration implies that (a) types in an unnamed package cannot be imported, and (b) static members of types in an unnamed package cannot be imported. As such, §7.5.1, §7.5.2, §7.5.3, and §7.5.4 all require a compile-time error on any attempt to import a type (or static member thereof) in an unnamed package.
In order to access these classes from outside the default package without modifying the library, you would need to use reflection.
Additionally, the reason you don't need an import when your class is in the default package, is because you don't need to import classes when they are in the same package.
I'm afraid this is impossible. Specifically, you cannot "import" the default package into a named package. Since the library you're using has its classes in the default package, your only recourse is to use the default package as well, if you want to use the library.
Of course, you could move the library's classes to a package, but that's a different story.
In any IDE, when working with a class in a package and I need to use a class from another one, I have to import it. Why doesn't the IDE just automatically import the packages so there is no need to do it manually?
Because sometimes different classes have same 'short' name so the IDE does not know which one you meant. For example if you copy-paste code into your IDE containing Date, it does not know if you meant java.sql.Date or java.util.Date. In these cases the IDE will offer you to choose from all available classes with that name.
First, In Eclipse, you can use Ctrl-SHIFT-O to automatically import anything you need.
From the java package tutorial:
For convenience, the Java compiler automatically imports two entire
packages for each source file: (1) the java.lang package and (2) the
current package (the package for the current file).
The IDE will not import all your packages because 1.
You may not need them, why import them?
More importantly, you can have classes in different packages with the same name, then this will cause name ambiguities.
If a member in one package shares its name with a member in another
package and both packages are imported, you must refer to each member
by its qualified name. For example, the graphics package defined a
class named Rectangle. The java.awt package also contains a Rectangle
class. If both graphics and java.awt have been imported, the following
is ambiguous.
This would cause unnecessary headache making sure you are always referring to the correct package. By importing packages and classes yourself, you can be sure that you are always using the specific class that you intended to.
This is my thought. Think this way,
Suppose you have two classes having the same name in different packages like this, then how does IDE resolve the package import? How does it know which SendFormAction to be imported?
So generally IDE's give you an option to import the packages [cntrl+shift+O in eclipse IDE]
and if there is confusion, it will ask you which one to import.
com.xyz.action [package]
SendFormAction.java
com.abc.action [package]
SendFormAction.java
I'm working now together with others in a grails project. I have to write some Java-classes. But I need access to an searchable object created with groovy. It seems, that this object has to be placed in the default-package.
My question is: Is there a way to access this object in the default-package from a Java-class in a named package?
You can’t use classes in the default package from a named package.
(Technically you can, as shown in Sharique Abdullah's answer through reflection API, but classes from the unnamed namespace are not in scope in an import declaration)
Prior to J2SE 1.4 you could import classes from the default package using a syntax like this:
import Unfinished;
That's no longer allowed. So to access a default package class from within a packaged class requires moving the default package class into a package of its own.
If you have access to the source generated by groovy, some post-processing is needed to move the file into a dedicated package and add this "package" directive at its beginning.
Update 2014: bug 6975015, for JDK7 and JDK8, describe an even stricter prohibition against import from unnamed package.
The TypeName must be the canonical name of a class type, interface type, enum type, or annotation type.
The type must be either a member of a named package, or a member of a type whose outermost lexically enclosing type is a member of a named package, or a compile-time error occurs.
Andreas points out in the comments:
"why is [the default package] there in the first place? design error?"
No, it's deliberate.
JLS 7.4.2. Unnamed Packages says: "Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development".
In fact, you can.
Using reflections API you can access any class so far. At least I was able to :)
Class fooClass = Class.forName("FooBar");
Method fooMethod = fooClass.getMethod("fooMethod", String.class);
String fooReturned = (String)fooMethod.invoke(fooClass.newInstance(), "I did it");
Use jarjar to repackage the jar file with the following rule:
rule * <target package name>.#1
All classes in the default package of the source jar file will move to the target package, thus are able to access.
You can use packages in the Groovy code, and things will work just fine.
It may mean a minor reorganization of code under grails-app and a little bit of a pain at first, but on a large grails project, it just make sense to organize things in packages. We use the Java standard package naming convention com.foo.<app>.<package>.
Having everything in the default package becomes a hindrance to integration, as you're finding.
Controllers seem to be the one Grails artifact (or artefact) that resists being put in a Java package. Probably I just haven't figured out the Convention for that yet. ;-)
just to complete the idea:
From inside default-package you can access objects resided in named packages.
I'm making a JVM language. This language has modules (namespaces) and the ability to import java libraries. In the import section the user can import things like "java.io." or "java.concurrent." etc.
How do I know that a "File" reference in the source is in the package java.io and not somewhere else?
Because Java is statically typed the lookup need to be be unambiguous. When you import entire packages (or namespaces) your compiler will need to handle name clashes in those namespaces if the types are used in the source. So you'll need to scan the list of available types to check.
That is why you sometimes see source code with the full class name expanded. e.g. java.util.Date when in import both java.util and java.sql Otherwise the compiler doesn't know which one to use.
Scala has some interesting features about importing from Java packages. You can look at those for inspiration.
If you want to know which classes are in a package you need to list all the class files in the directory for that package in the class path.