Default Classes imported in java - java

I have a simple code:
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
I know that Object class is imported by default in every java program, but I wanted to ask whether PrintStream class is also imported by default if we are using print() or println() functions?
Because Object class belongs to java.lang package and PrintStream class belongs to java.io package, so if it is not imported by default, then how we are able to use the println() method of PrintStream class?
If it (PrintStream class) is not imported by default, then why the decompiler is importing it?
This is the output after decompiling it:

The types of intermediate expressions in your Java program do not need to be imported on the source code level. It's only when you assign the value of such an expression to a declared variable that you have to make its type explicit; at that moment you have to add the import (or use the qualified name).
In your case, System.out is such an intermediate expression; its type is indeed java.io.PrintStream, which is not imported by default as it is not in java.lang. If you would modify your class to
import java.io.PrintStream;
public class Hello {
public static void main(String[] args)
{
PrintStream myOut = System.out;
myOut.println("Hello World");
}
}
you need to add the import statement, or use the qualified name as in
public class Hello {
public static void main(String[] args)
{
java.io.PrintStream myOut = System.out;
myOut.println("Hello World");
}
}
On the bytecode level the story is different: since all dependencies need to be loaded for the JVM to be able to execute the code, all of them are listed in the .class file, including the types of intermediate expressions. Apparently the decompiler used in the screenshot of the OP isn't clever enough to realise that such imports are unnecessary on the source code level, and so it just creates import statements for all dependencies listed in the .class file.

I wanted to ask whether PrintStream class is also imported by default if we are using print() or println() functions
No, from the JLS:
A compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang.
So you can use System because it belongs to java.lang.
so if it is not imported by default,then how we are able to use the println() method of PrintStream class?
Because System.out is accessible to your type, so you can use all visible method of System.out

why the decompiler is importing it
Looks like a bug in the decompiler you are using. This import is completely unnecessary here.
You can program without imports at all, just using the fully-qualified class names like this:
java.io.PrintStream out = System.out;
Imports are used just for convenience, so you can use simple class names in your code. It's possible that the same simple name appears in different packages (for example, java.awt.List and java.util.List) so to resolve this ambiguity you have to either use full class name or import the one you want (in case you want to use both of them, you will still have to use the full name for one of them). As you correctly mentioned, only classes from java.lang are imported always by default. Again, this is done for convenience, so you can use just System instead of java.lang.System (though java.lang.System.out.println() is also valid).
In your example as you don't directly mention the PrintStream in the source, no need to import it. Imports have nothing in common with class loading (which happens in runtime, not during the compilation).

Related

Do we need to import a package only to create an object or to call a method from that object as well?

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.PrintStream instead of using the short name PrintStream.
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.
import is just saves you from typing total path if you import that class you are able to write PrintStream otherwise you have to write complete path java.io.PrintStream

Importing own file into Java class

Okay, not sure if this would work.. but would it be possible, to use my own Java file that has certain required methods in it, to be imported into my Java class just like any other import? Or does it have a special way?
If your Java file contains a proper Java class enclosing the methods mentioned above, and it is visible to the compiler (i.e. either its source file is on the compiler source path or its class file is on the compiler classpath), you can just import it like any other classes.
Have you tried it? Do you have any specific problem?
If that method is static and visible in your scope, you can use import static. It will make the imported static method look like it is in your class. For example, if your code parse a lot of integers, you can use
import static Integer.parseInt;
And then the parseInt method will be visible and invokable directly:
int parsed = parseInt("123");
That is only required if your other class is in a different namespace. if they are in the same namespace (this includes the default empty namespace), and you 'tell' the compiler about both files, you don't need to use import statements.
If however class A is in namespace org.example.stuffA, and you want to use it in class B in org.example.stuffB, you'll need to use a import org.example.stuffA.A statement, or hard-link it in the document (new org.example.stuffA.A() for example).
In the namespaces example, you still need to make sure the compiler is able to find the required classes. In both cases you also need to make sure the methods you need are of the correct permission type, they would probably need to be public.
You Can use Static methods or by create Object of it & Use.
public class abc
{
public static MyMethod()
{
// ..
}
}
public class pqr
{
abc.MyMethod();
}
Another Way
public class abc
{
public void MyMethod()
{
// ..
}
}
public class pqr
{
abc Obj=new abc();
Obj.MyMethod();
}

Write a Java class to use in another Java class

I'm a Java noob.
Here's what I'm trying to do:
//File 1
public class Class1
{
//....does some stuff
}
//File 2
public class Class2
{
//..also does some stuff including:
Class1 c = new Class1();
}
File 1 and File 2 are in the same directory.
To compile, I'm using the command:
javac Class2.java
This is giving me errors of the form:
Error: Cannot find symbol Class1
How do I solve this?
If the two files Class1.java and Class2.java are in the same directory, (and assuming you have declared the class you want to use as) you do not need to do any import at all in order to use one from the other; Java will find the other class automatically.
So in Class2.java you can simply do:
public class Class2 {
void someMethod() {
Class1 c = new Class1();
}
}
On base class,
package ABC;
public class PQR {
// Do stuff
}
import ABC.*;
class XYZ {
// Use the PQR class method
}
Assuming they are in the same folder, you shouldn't have to import, if they aren't then you need to specify the package like import java.util.Scanner;. In Java you don't suffix with an extension.
What are you using to write your code in?
not sure I understand the question - are you trying to use an inner class (one class definition inside another class definition) or are these classes separate and independent? imports are required to define the packages/ classes you would have an access to, the ones in the same package are available by default. So if these are in the same package, you don't really need any imports. Also, both these classes need to be visible to each other. When you say it doesn't work, what error do you get?
one way to use inner classes is e.g. outer.new Class1() (where outer is an object of the class that encapsulates Class1). If these are not inner classes, they need to be in separate .java files.
Btw, it is always recommended to provide an access modifier (public, private, protected) explicitly.
Full code listing with error messages would help me give a better answer...
For using multiple classes in one file take a look into this tutorial
If you are writing your classes in two different files and they are in the same package it doesn't require to import them in order to use it. But if you are compiling them manually (using command prompt) make sure you have compiled all the .java file. Otherwise you will get errors.
If you are writing them in different package make sure these classes are public in order to use them. And yes in this case you have to import the package containig the class that you want to use. Again make sure all the classes are compiled if you are using command promt.
My suggestion is to use a good IDE (there are many :)) for doing your code because they assist you much more than we do :)

Java compilation of a .java file without a public class

Okay, so a java source file must have at least one public class and the file should be called "class-name.java". Fair enough.
Hence, if I have a class, then the following would compile:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
But what bugs me is that if I remove the 'public' access modifier from the above code, the code still compiles. I just don't get it. Removing it, the code looks like:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
In the above code, since I removed the public access modifier, my class has default or package access, i.e. it can't be accessed from the outside world, only from within the package.
So my question is, how does the above code compile ? The file HelloWorld.java in this case does not have a public HelloWorld class (only a package-private HelloWorld.class) and thus to my understanding should not compile.
a java source file must have at least one public class and the file should be called class-name.java
Incorrect, a top level class does not have to be declared public. The JLS states;
If a top level class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.
See http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#104285 section 6.6.1.
You can place non-public class in a file, and it's not a bug but feature.
Your problem is on level of packaging, not compile. Because you can compile this file with non-public class, but you can't call it from outside, so it's not working as application base class
Like this:
// [+] single file: SomeWrapper.java
public class SomeWrapper {
ArrayList<_PrivateDataType> pdt;
}
// [-] single file: SomeWrapper.java
// [+] single file: _PrivateDataType.java
class _PrivateDataType {
// members, functions, whatever goes here
}
// [-] single file: _PrivateDataType.java
A main method is just like any other method. The only difference is that it may be invoked from the command line with the java command. Even if the main method is not visible from the command line, the class can still be used like any other Java class, and your main method may be invoked by another class in the same package. Therefore i makes sense that it compiles.
In Java main function are not special in any sense. There just exists a terminal command that is able to invoke static methods called main...
There are valid usages for a non public classes. So the compiler does not give error when you try to compile the file.
That's nothing to wonder about. I suppose this behavior is similar to the one of some C/C++-compiler.
Code like "void main() { /.../ }" will be compiled correctly by those compilers, although it is not standards-compliant code. Simply said, the compiler exchanges the "void" with "int".
I think a similar behavior is implemented by the java compiler.
When you do not specify the access modifier of the class (or its field or method), it is assigned "default" access. This means it is only accessible from within the same package (in this case, the default package).
The website Javabeginner.com has an article on the subject - you should become familiar with access modifiers in Java, either from this site, or others.

current package keyword in java

1.Is there a keyword to refer to the current package that you are working in Java. Like we have "this" to refer to the current object. So , is there something similar for a package?
2.Also if the current class that I am working on is in a directory which has other classes,and my class has no package statement, then it will be in the default package. So, is there any way to import rest of the classes in the directory. I know that we can specify the classpath while compiling, but is there any way to do it using imports ?
No, there is not
No, classes in the default package can't be imported. That's one of the reasons you should never put your classes in the default package. The obvious reason is that, if every library did that, you would end up with conflicts between classes.
The first one
No keyword like this to get package name, but you can get package name by java reflection, like the following code
package com.netease.unitest.controller;
public class GenTest {
public static void main(String[] args) {
System.out.println(GenTest.class.getPackage().getName());
}
}
the output is
com.netease.unitest.controller
you can get more details in the following link
http://tutorials.jenkov.com/java-reflection/index.html

Categories