This version of the code was placed in a path like: G:\JavaExamples\myPackage\Test.java... again, it compiles just fine; however, I get the error "could not find or load main class...."
I tried using the command line in two ways (in both cases, I started the run by going to the folder in the command prompt):
1. java myPackage.Test
2. java Test
If I comment out the package in the source:
And recompile, I can successfully run the code using: java Test
What am I doing wrong?
Note: For some reason, my indentations in my code are not showing up in this post; however, when I came back to edit this post, I see them
You need the code button to maintain the indentation. I have edited your post with the code button and doesn't it look better
If you are still at the hello world stage, then using packages simply makes things more difficult for you. The thing about packages is that they require a certain directory structure and they change the name of your class. In the first code snippet, the class name is not Test; it is myPackage.Test. Try it:-In order to run it you have to call it by its correct name.
… and that name must correspond to the directory structure. When you say myPackage.... you must find the Test.class file inside the myPackage folder. You must be able to do… and get myPackage as part of the output. You will probably have to write
first. The .. bit is universal shorthand for one directory towards the root, i.e. the parent directory of wherever you start off.
So, to get that to run, you can do lots of different things. An easy way:-
G:\JavaExamples\myPackage to run it.
Instead, you need to run it from
Your 1st command will do.
Note:you should compile from
And you can see that it works just the same on a Linux box except you write ls instead of dir.
campbell@campbellsComputer:~$ cd java/
campbell@campbellsComputer:~/java$ mkdir myPackage
campbell@campbellsComputer:~/java$ cd myPackage/
campbell@campbellsComputer:~/java/myPackage$ gedit Test.java
campbell@campbellsComputer:~/java/myPackage$ javac Test.java
campbell@campbellsComputer:~/java/myPackage$ cd ..
. . .
. . .
campbell@campbellsComputer:~/java$ java myPackage.Test
This is a test
Class name = myPackage.Test