CMD and Powershell work differently for building and running java files

See this: YouTube video reference

Here, cmd works fine when working with Java, but not Powershell. Why is it so and how to make Powershell work with it?

Update (adding commands and outputs, so you may skip watching the video)

CMD:

C:\Users\reesh\Desktop\Java>javac MyFirstJavaProgram.java
C:\Users\reesh\Desktop\Java>java MyFirstJavaProgram
Hello World
C:\Users\reesh\Desktop\Java>

Powershell:

PS C:\Users\reesh\Desktop\Java> javac .\MyFirstJavaProgram.java
PS C:\Users\reesh\Desktop\Java> java .\MyFirstJavaProgram
Error: Could not find or load main class .\MyFirstJavaProgram
Caused by: java.lang.ClassNotFoundException: /\MyFirstJavaProgram
PS C:\Users\reesh\Desktop\Java>

In other words, PS is giving error, while cmd is not.

4

2 Answers

By default, Powershell has a security configuration that when you try to run a program by just giving the name, it does not search the current folder like cmd. Instead it just searches your PATH variable.

Therefore, the first fix is to make javac to ./javac. Secondly, when you write .\MyFirstJavaProgram, Java doesn't seem to be able to read the file name. Instead try making it a forward slash ./MyFirstJavaProgram.

Final command ./java.c ./MyFirstJavaProgram. Although, I want to emphasise this, you don't need a ./ on MyFirstJavaProgram because it is an argument, not a script or executable.

0

You didn't run the same command in both.

In the command shell, you ran java MyFirstJavaProgram

In PowerShell, you ran java .\MyFirstJavaProgram

If you had run the same command it would have worked. It's nothing to do with whether you're running from PowerShell. The issue is that Java expects you to give it the class name. The class name is not .\MyFirstJavaProgram - the class name is MyFirstJavaProgram.

You get the class name from what you write inside your .java file where it says class MyFirstJavaProgram.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like