1

I know there are similar questions out there but none of those solutions work for my case. I tried to execute a Java file using Windows PowerShell.

This is what I have for Java file:

public class Demo1 { 
  public static void main (String arg[]){
        System.out.println("DEMO1 START RUNNING");
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Unable to process");
        }
        System.out.println("DEMO1 JAVA COMPLETED.");    
    }
}

For easy compilation, I have copies of Demo1.java, Demo1.jar, and Demo1.class in the desktop directory.

for powershell command, I have tried: 1st attempt:
C:..\Desktop> java Demo1.java

2nd attempt:
C:..\Desktop> java -class Demo1.class

3rd attempt:
C:..\Desktop> java -jar Demo1.jar

All the above attempt return this error:
PS C:\Users\b003485\Desktop> java .\Demo1.java
Exception in thread "main" java.lang.NoClassDefFoundError: /\Demo1/java
Caused by: java.lang.ClassNotFoundException: .\Demo1.java
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: .\Demo1.java. Program will exit.

Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
user3780972
  • 11
  • 1
  • 2
  • 2
    You will not run .java file, you need .class file. First compile and then run. Spend sometime on learning basics. – kosa Jun 26 '14 at 21:12
  • Simply `java Demo1`. I would recommend looking at [The Java Tutorials](http://docs.oracle.com/javase/tutorial/getStarted/cupojava/win32.html). – sgbj Jun 26 '14 at 21:36
  • guys, im referring to powershell here, not cmd command prompt. – user3780972 Jun 26 '14 at 22:28
  • 1
    PROBLEM SOLVED! , so I noticed there was a typo with the main method header:
    original: public static void main (String arg[]){ I changed to **public static void main(String[] args)** and then compiling it and export it to a jar file.
    THIS IS VERY IMPORTANT: when you exporting the file to jar, during the configuration. make sure choose your main class file or else you will run into the same problem like i did.
    finally run **java -jar Demo1.jar** in powershell and it works like a charm!
    – user3780972 Jun 26 '14 at 22:54
  • Changing the variable name from `arg` to `args` has nothing to do with why your program started working. And executing a Java application in PowerShell works the same way as you would with command prompt. See [executing a jar file from command prompt](http://stackoverflow.com/questions/5774970/run-jar-file-in-command-prompt), and note that it uses the same command you used. – sgbj Jun 27 '14 at 13:15

0 Answers0