0

this is a beginner question. I am having a problem running my java program from command line. I am using Windows10. The problem is the following. I have a folder named "folder1", which is located o the dekstop of my computer. So the full path would be C:\Users\Ioanna\Desktop\folder1 Inside that folder I have created a second folder which I named folder2. so the path to this would be C:\Users\Ioanna\Desktop\folder1\folder2

Inside folder2 I have a java file named example.java I want to compile it and run this file with setting the -classpath option through cmd. I dont want to set the path or to add the folder to tha path from environment variables.

I am trying

C:\Users\Ioanna\javac -cp C:\Users\Ioanna\Desktop\folder1\folder2 example.java

but it says file not found. I tried several other alternatives, but I can't seem to find how to compile successfully the program.

1
  • Are you in C:\Users\Ioanna\Desktop\folder1\folder2 ? What does javac print exactly? Commented Nov 12, 2016 at 18:11

2 Answers 2

1

Code compilation (to bytecode) and code execution are two separate steps, in Java.

First, compile your .java to obtain the corresponding .class file (I'm assuming your folder paths are right):

C:\Users\Ioanna\javac C:\Users\Ioanna\Desktop\folder1\folder2\example.java

This will give you example.class in that same folder.
Next, run that class (provided it has a main() method):

C:\Users\Ioanna\java -cp C:\Users\Ioanna\Desktop\folder1\folder2 example
Sign up to request clarification or add additional context in comments.

4 Comments

No. java doesn't expects a path to a .class file. It expects a fully qualified class name, and looks for the corresponding .class file in the classpath.
@JBNizet So the instructions in my example won't work?
The first one will. The second won't. Assuming the example class is in the default package (which is a bad practice), it would have to be java -cp C:\Users\Ioanna\Desktop\folder1\folder2 example.
@JBNizet Yep, fixed. Too much used to IDE's I guess.
1

java expects the path of the file(s) to compile. And example.java is not in the current folder (C:\Users\Ioanna).

Use

javac Desktop\folder1\folder2\example.java

1 Comment

thanks that worked !! It compiled ! and what do I user to run the example.class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.