class TestFormat
{
public static void main(String[] args)
{
System.out.println("hello");
}
}
In the above simple code the out object is of type java.io.PrintStream. The println() method is also of class PrintStream. PrintStream resides in a different package then java.lang which is the default java package.
My question is how are we able to use method of a class from a package(java.io) we have not even imported? Granted that the object of that class is already provided to us but does that means that we need to import a package only to create an object of a class from that package and not to use its methods afterwards?
Thnax in advance!
You misunderstand what import does.
Yes, you can use a class and its methods without an import statement. It means that you’ll have to type out
java.io.PrintStreaminstead of using the short namePrintStream.The class loader searches the classpath for a .class file when you first use a class; import has nothing to do with this process. It’s just a way to save you from having to type out the fully resolved class name.
You can write Java successfully and never use an import if you wish. You just need to be a good touch typist.