Compiling and running java program in windows

How to Compile and Run your First Java Program

By Chaitanya Singh | Filed Under: Learn Java

In this tutorial, we will see how to write, compile and run a java program. I will also cover java syntax, code conventions and several ways to run a java program.

Simple Java Program:

Output: This is my first program in java

How to compile and run the above program

Prerequisite: You need to have java installed on your system. You can get the java from here.

Step 1: Open a text editor, like Notepad on windows and TextEdit on Mac. Copy the above program and paste it in the text editor.

You can also use IDE like Eclipse to run the java program but we will cover that part later in the coming tutorials. For the sake of simplicity, I will only use text editor and command prompt (or terminal) for this tutorial

Step 2: Save the file as FirstJavaProgram.java. You may be wondering why we have named the file as FirstJavaProgram, the thing is that we should always name the file same as the public class name. In our program, the public class name is FirstJavaProgram , that’s why our file name should be FirstJavaProgram.java.

Step 3: In this step, we will compile the program. For this, open command prompt (cmd) on Windows, if you are Mac OS then open Terminal.
To compile the program, type the following command and hit enter.

You may get this error when you try to compile the program: “javac’ is not recognized as an internal or external command, operable program or batch file“. This error occurs when the java path is not set in your system

If you get this error then you first need to set the path before compilation.

Set Path in Windows:
Open command prompt (cmd), go to the place where you have installed java on your system and locate the bin directory, copy the complete path and write it in the command like this.

Note: Your jdk version may be different. Since I have java version 1.8.0_121 installed on my system, I mentioned the same while setting up the path.

Set Path in Mac OS X
Open Terminal, type the following command and hit return.

Type the following command on terminal to confirm the path.

The steps above are for setting up the path temporary which means when you close the command prompt or terminal, the path settings will be lost and you will have to set the path again next time you use it. I will share the permanent path setup guide in the coming tutorial.

Step 4: After compilation the .java file gets translated into the .class file(byte code). Now we can run the program. To run the program, type the following command and hit enter:

Note that you should not append the .java extension to the file name while running the program.

Closer look to the First Java Program

Now that we have understood how to run a java program, let have a closer look at the program we have written above.

This is the first line of our java program. Every java application must have at least one class definition that consists of class keyword followed by class name. When I say keyword, it means that it should not be changed, we should use it as it is. However the class name can be anything.

I have made the class public by using public access modifier, I will cover access modifier in a separate post, all you need to know now that a java file can have any number of classes but it can have only one public class and the file name should be same as public class name.

This is our next line in the program, lets break it down to understand it:
public : This makes the main method public that means that we can call the method from outside the class.

static : We do not need to create object for static methods to run. They can run itself.

void : It does not return anything.

main : It is the method name. This is the entry point method from which the JVM can run your program.

(String[] args) : Used for command line arguments that are passed as strings. We will cover that in a separate post.

This method prints the contents inside the double quotes into the console and inserts a newline after.

Checkout these basic java programs before reading next topic:

How to start compiling and running Java programs [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Читайте также:  Windows is loading files gif

Closed 7 years ago .

I’ve tried to search for somthing that will run java for me. Like the class, Im not too sure. Im only 14.. I didnt understand with all this ‘javac’, SKD or something along those line. I just need somthing free that I can downlooad to run my java files.

4 Answers 4

You need the Java JDK to get javac so you can run programs you write— get it here

You can use javac to compile your source files to .class files. Then you use java to run your program.

Please read the Getting started tutorial for more info

If you want to learn to understand how to use javac on the command line , you should go through beginner tutorials, where you just type the code you read and try to understand what it does.

If you only want to write java code and don’t want to understand all the compiler stuff, you should use an IDE (integrated development environment) such as Oracle Netbeans or Eclipse

Ok ill help you get started, I would highly recommend Eclipse, i have used it for years. Its by far the best IDE out there in my opinion. You can make classes, run programs, make applets, debug your programs with ease and much much more. Eclipse makes all your programming easier and more efficient. You can even use it to create jar files. If your a beginner to java then i would highly recommend looking at some of their sample code. They have an entire section dedicated to samples. I think its the best option for you as long as your computer has about 200 meg free ram. heres the web address for the FREE download:

hope this helped!

First you need to download the JDK for the appropiate OS.

You can compile java files (*.java) using the javac command.

Once you have your java file compiled (they are turned into *.class files) you can run your java application using java command.

I recommend you to use an IDE.

The most used IDEs are:

Not the answer you’re looking for? Browse other questions tagged java or ask your own question.

Hot Network Questions

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

HOW TO WRITE , COMPILE AND RUN JAVA PROGRAM ON «WINDOWS 8 X64 BIT» IN COMMAND PROMPT

How to Write , compile and Run java Program via Command Prompt(CMD) in 64 bit Windows 8/7
=======================================================================================
In the previous version of windows writing java programs is done via «edit » command. Bur now in the modern 64bit version of windows don’t have the classic MS-Editor(edit.exe) though 32bit versions still have it.. In 64bit Windows the only option to write any text via CMD is «notepad». All the procedure is as follows

1. Download latest JDK 64bit (jdk1.7.0_25 x64) & install it.

2. Right click on Computer icon(desktop) and click properties
click Advance System Settings
click Environment Variables
In the system variables box click on Path —-Click Edit
In the variable value just ADD «;C:\Program Files\Java\jdk1.7.0_25\bin» without quotes at last. i.e. Don’t delete a single letter of the previous value, only add the above text after it
save every thing you’ve done by clicking OK.

3. Now open CMD(windows key +R and type cmd & Enter)

4. Type «notepad» without quotes

5. Write your java program and save it in your Home Directory. i.e. C:/Users/usrername(currently you have logged in)

6. Now you can compile your java program by javac and by typing java filename you can run your java program.

**This process is also applicable for 32bit windows(7&8). Change is that you have to download latest jdk 32bit ( till now latest version is 1.7.0_25) version and you can use «edit» or «notepad» any command to write your program. All the rest is same

How do I run a Java program from the command line on Windows?

I’m trying to execute a Java program from the command line in Windows. Here is my code:

I’m not sure how to execute the program — any help? Is this possible on Windows? Why is it different than another environment (I thought JVM was write once, run anywhere)?

12 Answers 12

Let’s say your file is in C:\mywork\

Run Command Prompt

This makes C:\mywork the current directory.

This displays the directory contents. You should see filenamehere.java among the files.

This tells the system where to find JDK programs.

This runs javac.exe, the compiler. You should see nothing but the next system prompt.

javac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.

This runs the Java interpreter. You should then see your program output.

If the system cannot find javac, check the set path command. If javac runs but you get errors, check your Java text. If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command. Java is case-sensitive!

To complete the answer :

Compile the Java File to a *.class file

  • This will create a TheJavaFile.class file
Читайте также:  Энергосберегающий режим компьютера windows

Execution of the Java File

Creation of an executable *.jar file

You’ve got two options here —

With an external manifest file :

Create the manifest file say — MANIFEST.mf

The MANIFEST file is nothing but an explicit entry of the Main Class

jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class

Executable by Entry Point:

To run the Jar File

In case your Java class is in some package. Suppose your Java class named ABC.java is present in com.hello.programs , then you need to run it with the package name.

Compile it in the usual way:

But to run it, you need to give the package name and then your java class name:

Complile a Java file to generate a class:

Execute the generated class:

Assuming the file is called «CopyFile.java», do the following:

The first line compiles the source code into executable byte code. The second line executes it, first adding the current directory to the class path (just in case).

Since Java 11, java command line tool has been able to run a single-file source-code directly. e.g.

This was an enhancement with JEP 330: https://openjdk.java.net/jeps/330

For the details of the usage and the limitations, see the manual of your Java implementation such as one provided by Oracle: https://docs.oracle.com/en/java/javase/11/tools/java.html

It is easy. If you have saved your file as A.text first thing you should do is save it as A.java. Now it is a Java file.

Now you need to open cmd and set path to you A.java file before compile it. you can refer this for that.

Then you can compile your file using command

Then run it using

So that is how you compile and run a java program in cmd. You can also go through these material that is Java in depth lessons. Lot of things you need to understand in Java is covered there for beginners.

You can compile any java source using javac in command line ; eg, javac CopyFile.java. To run : java CopyFile. You can also compile all java files using javac *.java as long as they’re in the same directory

If you’re having an issue resulting with «could not find or load main class» you may not have jre in your path. Have a look at this question: Could not find or load main class

On Windows 7 I had to do the following:

quick way

  1. Install JDK http://www.oracle.com/technetwork/java/javase/downloads
  2. in windows, browse into «C:\Program Files\Java\jdk1.8.0_91\bin» (or wherever the latest version of JDK is installed), hold down shift and right click on a blank area within the window and do «open command window here» and this will give you a command line and access to all the BIN tools. «javac» is not by default in the windows system PATH environment variable.
  3. Follow comments above about how to compile the file («javac MyFile.java» then «java MyFile») https://stackoverflow.com/a/33149828/194872

long way

  1. Install JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. After installing, in edits the Windows PATH environment variable and adds the following to the path C:\ProgramData\Oracle\Java\javapath. Within this folder are symbolic links to a handful of java executables but «javac» is NOT one of them so when trying to run «javac» from Windows command line it throws an error.
  3. I edited the path: Control Panel -> System -> Advanced tab -> «Environment Variables. » button -> scroll down to «Path», highlight and edit -> replaced the «C:\ProgramData\Oracle\Java\javapath» with a direct path to the java BIN folder «C:\Program Files\Java\jdk1.8.0_91\bin».

This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.

Compile and run Java program in package from command line

How to Compile JAVA Program in Package from command line

The topic is very easy and i am sure that lots of java programmer already know how to compile java program existing in package. However there are users who frequently works on eclipse, netbeans or any other IDE and don’t know that how the program actually works behind the IDE. So this article basically emphasizes on basics of Java Compilation.

Consider following directory structure :

Java Directory structure

Our java files will be in “ src ” folder. I want all the class files in folder “ classes ” and currently i am in folder “ Exec Jar “.

Consider below Java Files:

Run below steps to compile and run java programs from command line:

Compile and run Java Program in Package from Command Line

Command Explanation :

Line 1 :

  • “javac” is the java compiler available in bin folder of the jdk.
  • -d” stands for the “directory“. it explains compiler that where the class files should be created.
  • Last argument is the Complete path, where the java file exists.

Line 2 :

  • in line 2, you have noted one extra parameter “-classpath“. As class “Start” depends on class “Person” and its class file is not in the same directory. Therefore we need to explicitly tell compiler that where it can find required class files.
  • To include more than one classpath use semicolon “;”. Example: -classpath path1;path2;path3

Line 3 :

  • It will run the program. her we have to again specify that where all the class files exist with the help of parameter “-classpath

Next article, How to create executable jar file for packages in java

Share this post

37 thoughts on “Compile and run Java program in package from command line”

if have another directory to execute the java program
to compile the program
c:/>javac -cp d:sub;. use.java
to execute the program
c:/>java -cp d:sub;. use

hey can u clearly show us d command dt what’s d syntax to compile a program which use package….

sorry we didnt understood ;;;;eplain clear whatever u want ………..

hard to understand….

Option -d works if the directory structure is already there.What if the directory structure doesn’t exist from before?

Not Complete Directory structure. You just need to give the root path for the “.class” files. Remaining folders will be automatically created as per package structure.

Regards,
Jitendra Zaa

can you please explain little more deeply…. i can’t understand….can’t you give any example which uses package and importing a user defined package….

Hi Rachana,
Please follow the steps as per article. I have included the screens also. It worked for everyone.

Regards,
Jitendra Zaa

yes its working by the way you said..but what should i have to do the class files are in the same package where he classes are stored. bcz i’m having two classes with in com.example.payroll. the first class employee.java has compiled successfully but when i try to compile Test.java which has initialization of an object employee class shows cannot find symbol error i don’t know what is the reason here.

please give some simple programe of packages

sir i m unable to compile and run java package in jdk1.77. so pls tell me sir how can compile and run packages in java.

Hi Rihan,
Please follow the exact steps with same folder name, if you still face any problem than attach your screen shot showing error. i will surely guide you.

Thanks,
Jitendra Zaa

package is hard to run help everyone who wants help thank

I know its hard to run, thats why i have provided article. I have provided screen shots with step by step description. Just follow the same folder names and instructions. If you get any error then reply with full description.
Regards,
Jitendra Zaa

sir how to run this program plssssssssssssss

//multiplication.java
package mp;
public class multiplication
<
int n;
public multiplication(int n)
<
this.n=n;
>
public void table()
<
if(n

Hi Somasekharkote,It will need command line argument which will be converted as number and print the multiplication table.

Thank you for the good article, I was able to proceed further using this article, but I have getting this error (PFA screenshot)

I have my java file stored in                   C:UsersAshi’sworkspaceJavaPracticeMyPackÂ
and I have my java executable files stored at       C:Program FilesJavajdk1.7.0_02binÂ

Hi Add the path upto java/bin in “Classpath” and run the program from base package

Thank you for the reply Sir, but I did not understand what you mean by the above statement. Are you intending on going to my executable files folder and then using the classpath flag along with javac command? Really confused here 🙁

Thanks. It works… 🙂

Thanks Ran on Ubuntu 12.04 just as is. I did have to include all the directories to the source file.
b

thx a lot for this post, thx once again,

if i can write the both files (package & main class file) in one program then how to run this program.

It’s not working sir , I did the above step as you mention , It creating lot of confusion

this is my package….. how shud i compile n run it?

my classname is Main

this is nt d pkg created by me… m preparing 4 a cmpny n it hs told 2 use dis pkg in d code

if i change the package name of Start.java then how to run it

You are a life saver man! Thanks a ton 🙂

sir how to run this
import java.net.*;
import java.io.*;
import java.sql.*;
class trainserver
<
public static void main(String args[])
<
String Query;
ResultSet rs = null;
String msg;
int pnr = 0,trainnum=0;
String from = new String();
String to = new String();
String date = new String();
String name = new String();
try
<
ServerSocket ser=new ServerSocket(8000);
System.out.println(“Server Started…”);
Socket soc=null;
soc=ser.accept();
System.out.println(“Received Connection: “+soc.getInetAddress().getHostAddress());
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
try <
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection conn=DriverManager.getConnection(“jdbc:odbc:mydb”,”scott”,”tiger”);
Statement stmt=conn.createStatement();
msg = in.readLine();
pnr = Integer.parseInt(msg);
Query = “Select * from train where pnrno = “+pnr;
rs = stmt.executeQuery(Query);
if(rs.next())
<
pnr = Integer.parseInt(rs.getString(1));
from = rs.getString(2);
to = rs.getString(3);
date = rs.getString(4);
name = rs.getString(5);
trainnum=Integer.parseInt(rs.getString(6));
>
else
<
System.out.println(“invalid PNRNO”);
>
>
catch(SQLException e)
<
System.out.println(“Error Caught: “+e);
>
out.writeBytes(“”.valueOf(pnr));
out.write(10);
out.writeBytes(from);
out.write(10);
out.writeBytes(to);
out.write(10);
out.writeBytes(date);
out.write(10);
out.writeBytes(name);
out.write(10);
out.writeBytes(“”.valueOf(trainnum));
out.write(10);
soc.close();
>
catch(Exception e)
<
System.out.println(“Error Caught: “+e);
>
>
>
//Client side

class traindbclient
<
public static void main(String args[])
<
Socket objclient= null;
BufferedReader br = null,in = null;
DataOutputStream out = null;
int pnr = 0;
try
<
objclient = new Socket(“Localhost”,8000);
in = new BufferedReader(new InputStreamReader(objclient.getInputStream()));
br = new BufferedReader(new InputStreamReader(System.in));
out = new DataOutputStream(objclient.getOutputStream());
System.out.println(“Enter the PNR NO: “);
pnr = Integer.parseInt(br.readLine());
out.flush();
out.writeBytes(“”.valueOf(pnr));
out.write(10);
System.out.println(“PNRNo: “+in.readLine());
System.out.println(“SOURCE : “+in.readLine());
System.out.println(“DESTINATION: “+in.readLine());
System.out.println(“JOURNEY DATE: “+in.readLine());
System.out.println(“CUSTOMER NAME: “+in.readLine());
System.out.println(“TRAIN NO: “+in.readLine());
objclient.close();
>
catch(Exception e)
<
System.out.println(“Error Caught: “+e);
>
>
>

please give me solution sir

thank you. Had been trying to do this for several hours until I read your post. You’re right here “…However there are users who frequently works on eclipse, netbeans or any other IDE and don’t know that how the program actually works behind the IDE…. “

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Читайте также:  Топ эмуляторов терминала linux
Оцените статью