5

Everytime I want to build and run my program I do:

javac myProgram.java
java myProgram

I want to do something like this:

buildrun = javac (some_argument).java && java (some_argument)

so after I can just

buildrun myProgram

How to achieve this on Windows?

3
  • 3
    .cmd file should solve your problem Commented May 15, 2017 at 16:43
  • 4
    In this case, of course, it is better to use build tools Commented May 15, 2017 at 16:47
  • 3
    A batch file maybe? Or just use an IDE... Commented May 15, 2017 at 16:47

4 Answers 4

2

As other's have suggested you can simply create a batch file to build and run your program. Copy this in Notepad and save as .bat.

@echo off
set /p class="Enter Class: "
javac "%class%".java
java "%class%"

As you want, the batch file will ask for a FileName when it runs. In your case, you can set it to 'myProgram' and it will then compile and run the program.

Just make sure your batch file and your java file reside in the same folder for this script to run. You can always tweak the bat file to even accept the full path of the Java file.

Sign up to request clarification or add additional context in comments.

Comments

1

To compile and run Java with single command line in cmd use: java myProgram.java

Comments

1

You can use Makefile this way:

  1. Create a file named Makefile within the same folder where your java files reside.
  2. Add these contents to Makefile
run: compile
    java $(class)

compile: 
    javac $(class).java
  1. From terminal, run this command: make run class=myProgram

This way, it will compile first then run your java class in a single command

Comments

0

Yet another solution. Create buildrun.cmd file with the following code:

@echo off
javac %1.java
if errorlevel = 0 goto RUN

:ERROR
echo "Build fails!"
goto END

:RUN
java %1

:END

Now you can pass the class name which should be processed. For example: buildrun MyProgram to compile MyProgram.java and run MyProgram.class In this case execution will performs only if your class was compiled successful.

Comments

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.