I have class Hello
. I have successfully compiled the .class file from it and placed it into dir/subdir directory and have assigned it the dir.subdir package in its code. And I want to run it from the command line with java
command.
I have run it with command: java dir/subdir/Hello and it ran successfully! But I read in docs that it should be done with simply fully-qualified class name. I tried to execute: java dir.subdir.Hello and it ran successfully too!!
Which of these ways is sound approach and more correctly? What does each of them specifically means? What is their fundamental difference?
You should use the dotted form, but not because of platform compatibility.
The argument dir/subdir/Hello
is valid to use here because Java's default ClassLoader
implementation processes it correctly. However, not all ClassLoader
implementations support this. You should use the dotted form because according to the documentation in ClassLoader.loadClass
names are supposed to be binary names. The JLS defines binary names in JLS 13.1, item 1:
The class or interface must be named by its binary name, which must meet the following constraints:
The binary name of a top level type is its canonical name.
The binary name of a member type consists of the binary name of its immediately enclosing type, followed by
$
, followed by the simple name of the member.The binary name of a local class consists of the binary name of its immediately enclosing type, followed by
$
, followed by a non-empty sequence of digits, followed by the simple name of the local class.The binary name of an anonymous class consists of the binary name of its immediately enclosing type, followed by
$
, followed by a non-empty sequence of digits.The binary name of a type variable declared by a generic class or interface is the binary name of its immediately enclosing type, followed by
$
, followed by the simple name of the type variable.The binary name of a type variable declared by a generic method is the binary name of the type declaring the method, followed by
$
, followed by the descriptor of the method as defined in The Java Virtual Machine Specification, Java SE 7 Edition, followed by$
, followed by the simple name of the type variable.The binary name of a type variable declared by a generic constructor is the binary name of the type declaring the constructor, followed by
$
, followed by the descriptor of the constructor as defined in The Java Virtual Machine Specification, Java SE 7 Edition, followed by$
, followed by the simple name of the type variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With