Oc-windows.ru

IT Новости из мира ПК
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java run application

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 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!

Читать еще:  Класс thread java

To complete the answer :

Compile the Java File to a *.class file

  • This will create a TheJavaFile.class file

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:

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

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).

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 FilesJavajdk1.8.0_91bin» (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:ProgramDataOracleJavajavapath. 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:ProgramDataOracleJavajavapath» with a direct path to the java BIN folder «C:Program FilesJavajdk1.8.0_91bin».

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

Run a Java Application from the Command Line

Last modified: December 7, 2019

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

In the 9 years of running Baeldung, I’ve never, ever done a «sale».
But. we’ve also not been through anything like this pandemic either.
And, if making my courses more affordable for a while is going to help a company stay in business, or a developer land a new job, make rent or be able to provide for their family — then it’s well worth doing.
Effective immediately, all Baeldung courses are 33% off their normal prices!
You’ll find all three courses in the menu, above, or here.

1. Overview

Typically, every meaningful application includes one or more JAR files as dependencies. However, there are times a JAR file itself represents a standalone application or a web application.

We’ll focus on the standalone application scenario in this article. Hereafter, we’ll refer to it as a JAR application.

In this tutorial, we’ll first learn how to create a JAR application. Later, we’ll learn how to run a JAR application with or without command-line arguments.

2. Create a JAR Application

A JAR file can contain one or more main classes. Each main class is the entry point of an application. So, theoretically, a JAR file can contain more than one application, but it has to contain at least one main class to be able to run.

A JAR file can have one entry point set in its manifest file. In this case, the JAR file is an executable JAR. The main class has to be included in that JAR file.

First of all, let’s see a quick example of how to compile our classes and create an executable JAR with a manifest file:

A non-executable JAR is simply a JAR file that doesn’t have a Main-Class defined in the manifest file. As we’ll see later, we can still run a main class that’s contained in the JAR file itself.

Here’s how we would create a non-executable JAR without a manifest file:

3. Java Command Line Arguments

Just like any application, a JAR application accepts any number of arguments, including zero arguments. It all depends on the application’s need.

This allows the user to specify configuration information when the application is launched.

As a result, the application can avoid hardcoded values, and it still can handle many different use cases.

An argument can contain any alphanumeric characters, unicode characters and possibly some special characters allowed by the shell, for example ‘@’.

Arguments are separated by one or more spaces. If an argument needs to contain spaces, the spaces have to be enclosed between quotes. Either single quotes or double quotes work fine.

Usually, for a typical Java application, when invoking the application, the user enters command-line arguments after the name of the class.

However, it’s not always the case for JAR applications.

As we have already discussed, the entry point of a Java main class is the main method. The arguments are all Strings and are passed to the main method as a String array.

That said, inside the application, we can convert any element of the String array to other data types, such as char, int, double, their wrapper classes, or other appropriate types.

4. Run an Executable JAR with Arguments

Let’s see the basic syntax for running an executable JAR file with arguments:

java -jar jar-file-name [args …]

The executable JAR created earlier is a simple application that just prints out the arguments passed in. We can run it with any number of arguments. Below is an example with two arguments:

We’ll see the following output in the console:

So, when invoking an executable JAR, we don’t need to specify the main class name on the command line. We simply add our arguments after the JAR file name. If we do provide a class name after the executable JAR file name, it simply becomes the first argument to the actual main class.

Most times, a JAR application is an executable JAR. An executable JAR can have a maximum of one main class defined in the manifest file.

Consequently, other applications in the same executable JAR file can’t be set in the manifest file, but we can still run them from the command line just like we would for a non-executable JAR. We’ll see exactly how in the next section.

5. Run a Non-Executable JAR with Arguments

To run an application in a non-executable JAR file, we have to use -cp option instead of -jar. We’ll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute:

java -cp jar-file-name main-class-name [args …]

As you can see, in this case, we’ll have to include the main class name in the command line, followed by arguments.

The non-executable JAR created earlier contains the same simple application. We can run it with any (including zero) arguments. Here’s an example with two arguments:

And, just like we saw above, we’ll see the following output:

6. Conclusion

In this tutorial, we learned two ways of running a JAR application on the command line with or without arguments.

We also demonstrated that an argument could contain spaces and special characters (when allowed by the shell).

As always, the code for the examples is available over on GitHub.

Create your first Java application

In this tutorial, you will learn how to create, run, and package a simple Java application that prints Hello, World! to the system output. Along the way, you will get familiar with IntelliJ IDEA features for boosting your productivity as a developer: coding assistance and supplementary tools.

Create a new project

Install the JDK

To develop Java applications in IntelliJ >JDK ). If Java is not installed on your computer, you need to download a JDK package.

Open the jdk.java.net website.

There, you’ll find the Oracle’s OpenJDK binaries for Windows, macOS, and Linux as .tar.gz and .zip archives.

Select and download the necessary JDK version.

If you’re not sure which version you need, select the latest stable version.

Unzip the archive and place the folder with Java to the Java home directory on your computer.

The default path on Windows: C:Program FilesJava , on macOS: /Library/Java/JavaVirtualMachines .

On Linux, the default location for Java might differ depending on the distribution that you use.

Create a new Java project

In IntelliJ IDEA, a project helps you organize your source code, tests, libraries that you use, build instructions, and your personal settings in a single unit.

Launch IntelliJ IDEA.

If the Welcome screen opens, click Create New Project .

Otherwise, from the main menu, select File | New | Project .

In the New Project wizard, select Java from the list on the left.

From the Project SDK list, select the JDK that you want to use in your project.

If the list is empty, click New and specify the path to the Java home directory (for example, jdk-11.0.0.jdk ).

We’re not going to use any additional libraries or frameworks for this tutorial, so click Next .

Don’t create a project from the template. In this tutorial, we’re going to do everything from scratch, so click Next .

Name the project, for example: HelloWorld .

If necessary, change the default project location and click Finish .

Create a package and a >Packages are used for grouping together classes that belong to the same category or provide similar functionality, for structuring and organizing large applications with hundreds of classes.

In the Project tool window, select the src folder, press Alt+Insert , and select Java Class .

In the Name field, type com.example.helloworld.HelloWorld and click OK .

IntelliJ >com.example.helloworld package and the HelloWorld class.

Together with the file, IntelliJ IDEA has automatically generated some contents for your class. In this case, the IDE has inserted the package statement and the class declaration.

This is done by means of file templates. Depending on the type of the file that you create, the IDE inserts initial code and formatting that is expected to be in all files of that type. For more information on how to use and configure templates, refer to File and code templates.

The Project tool window Alt+1 displays the structure of your application and helps you browse the project.

In Java, there’s a naming convention that you should follow when you name packages and classes.

Write the code

Add the main() method using live templates

In contrast to Enter , Shift+Enter starts a new line without breaking the current one.

Type main and select the template that inserts the main() method declaration.

As you type, IntelliJ >Ctrl+J .

Live templates are code snippets that you can insert into your code. main is one of such snippets. Usually, live templates contain blocks of code that you use most often. Using them can save you some time as you don’t have to type the same code over and over again.

For more information on where to find predefined live templates and how to create your own, refer to Live templates.

You can also add the statement using the sout live template.

Call the println() method using code completion

After the main() method declaration, IntelliJ IDEA automatically places the caret at the next line. Let’s call a method that prints some text to the standard system output.

Type Sy and select the System >java.lang package).

Press Ctrl+. to insert the selection with a trailing comma.

Type o , select out , and press Ctrl+. again.

Type p , select the println(String x) method, and press Enter .

IntelliJ IDEA shows you the types of parameters that can be used in the current context. This information is for your reference.

Type » . The second quotation mark is inserted automatically, and the caret is placed between the quotation marks. Type Hello, World!

Basic code completion analyses the context around the current caret position and and prov >Ctrl+Space .

For information on different completion modes, refer to Code completion.

Build and run the application

Val >main() method right from the editor using the green arrow icon in the gutter.

Click

When you click Run , IntelliJ >javac compiles your source code into JVM bytecode.

Once javac finishes compilation, it places the compiled bytecode to the out directory, which is highlighted with yellow in the Project tool window.

After that, the JVM runs the bytecode.

Automatically created run configurations are temporary, but you can modify and save them.

If you want to reopen the Run tool window, press Alt+4 .

Package the application in a JAR

When the code is ready, you can package your application in a Java archive (JAR) so that you can share it with other developers. A built Java archive is called an artifact .

Create an artifact configuration for the JAR

From the main menu, select File | Project Structure Ctrl+Shift+Alt+S and click Artifacts .

Click

Build the JAR artifact

From the main menu, select Build | Build Artifacts .

Point to HelloWorld:jar and select Build .

If you now look at the out/artifacts folder, you’ll find your JAR there.

Run the packaged application

To make sure that the JAR artifact is created correctly, you can run it.

Use Find Action Ctrl+Shift+A to search for actions and settings across the entire IDE.

Create a run configuration for the packaged application

To run a Java application packaged in a JAR, IntelliJ IDEA allows you to create a dedicated run configuration.

Press Ctrl+Shift+A , find and run the Edit Configurations action.

In the Run/Debug Configurations dialog, click

In the Path to JAR field, click and specify the path to the JAR file on your computer.

Under Before launch , click

Run configurations allow you to define how you want to run your application, with which arguments and options. You can have multiple run configurations for the same application, each with its own settings.

Execute the run configuration

On the toolbar, select the HelloWorldJar configuration and click

The process has exited successfully, which means that the application is packaged correctly.

Ссылка на основную публикацию
Adblock
detector