# The Java Command — ‘java’ and ‘javaw’
A Java entry-point class has a main method with the following signature and modifiers:
Sidenote: because of how arrays work, it can also be (String args[])
When the java command starts the virtual machine, it loads the specified entry-point classes and tries to find main . If successful, the arguments from command line are converted to Java String objects and assembled into an array. If main is invoked like this, the array will not be null and won’t contain any null entries.
A valid entry-point class method must do the following:
- Be named main (case-sensitive)
- Be public and static
- Have a void return type
- Have a single argument with an array String[] . The argument must be present and no more than one argument is allowed.
- Be generic: type parameters are not allowed.
- Have a non-generic, top-level (not nested or inner) enclosing class
It is conventional to declare the class as public but this not strictly necessary. From Java 5 onward, the main method’s argument type may be a String varargs instead of a string array. main can optionally throw exceptions, and its parameter can be named anything, but conventionally it is args .
# JavaFX entry-points
From Java 8 onwards the java command can also directly launch a JavaFX application. JavaFX is documented in the JavaFX
(opens new window) tag, but a JavaFX entry-point must do the following:
- Extend javafx.application.Application
- Be public and not abstract
- Not be generic or nested
- Have an explicit or implicit public no-args constructor
# Running an executable JAR file
Executable JAR files are the simplest way to assemble Java code into a single file that can be executed. *(Editorial Note: Creation of JAR files should be covered by a separate Topic.) *
Assuming that you have an executable JAR file with pathname <jar-path> , you should be able to run it as follows:
If the command requires command-line arguments, add them after the <jar-path> . For example:
If you need to provide additional JVM options on the java command line, they need to go before the -jar option. Note that a -cp / -classpath option will be ignored if you use -jar . The application’s classpath is determined by the JAR file manifest.
# Running a Java applications via a "main" class
When an application has not been packaged as an executable JAR, you need to provide the name of an entry-point class
(opens new window) on the java command line.
# Running the HelloWorld class
The "HelloWorld" example is described in Creating a new Java program
(opens new window) . It consists of a single class called HelloWorld which satisfies the requirements for an entry-point.
Assuming that the (compiled) "HelloWorld.class" file is in the current directory, it can be launched as follows:
Some important things to note are:
- We must provide the name of the class: not the pathname for the ".class" file or the ".java" file.
- If the class is declared in a package (as most Java classes are), then the class name we supply to the java command must be the full classname. For instance if SomeClass is declared in the com.example package, then the full classname will be com.example.SomeClass .
# Specifying a classpath
Unless we are using in the java -jar command syntax, the java command looks for the class to be loaded by searching the classpath; see The Classpath
(opens new window) . The above command is relying on the default classpath being (or including) the current directory. We can be more explicit about this by specifying the classpath to be used using the -cp option.
This says to make the current directory (which is what "." refers to) the sole entry on the classpath.
The -cp is an option that is processed by the java command. All options that are intended for the java command should be before the classname. Anything after the class will be treated as an command line argument for the Java application, and will be passed to application in the String[] that is passed to the main method.
(If no -cp option is provided, the java will use the classpath that is given by the CLASSPATH environment variable. If that variable is unset or empty, java uses "." as the default classpath.)
# Troubleshooting the ‘java’ command
This example covers common errors with using the ‘java’ command.
# "Command not found"
If you get an error message like:
when trying to run the java command, this means that there is no java command on your shell’s command search path. The cause could be:
- you don’t have a Java JRE or JDK installed at all,
- you have not updated the PATH environment variable (correctly) in your shell initialization file, or
- you have not "sourced" the relevant initialization file in the current shell.
(opens new window) for the steps that you need to take.
# "Could not find or load main class"
This error message is output by the java command if it has been unable to find / load the entry-point class that you have specified. In general terms, there are three broad reasons that this can happen:
- You have specified an entry point class that does not exist.
- The class exists, but you have specified it incorrectly.
- The class exists and you have specified it correctly, but Java cannot it find it because the classpath is incorrect.
Here is a procedure to diagnose and solve the problem:
-
1. If you have source code for a class, then the full name consists of the package name and the simple class name. The instance the "Main" class is declared in the package "com.example.myapp" then its full name is "com.example.myapp.Main". 1. If you have a compiled class file, you can find the class name by running `javap` on it. 1. If the class file is in a directory, you can infer the full class name from the directory names. 1. If the class file is in a JAR or ZIP file, you can infer the full class name from the file path in the JAR or ZIP file.
-
1. Check that it exactly matches the full classname for the entry-point class. 1. It should not end with ".java" or ".class". 1. It should not contain slashes or any other character that is not legal in a Java identifier 1 . 1. The casing of the name should exactly match the full class name.
-
1. Work out the pathname that the classname maps to; see [Mapping classnames to pathnames](http://stackoverflow.com/documentation/java/3720/classpath/19816/mapping-classnames-to-pathnames#t=201609101442436616455) 1. Work out what the classpath is; see this example: [Different ways to specify the classpath](http://stackoverflow.com/documentation/java/3720/classpath/12852/different-ways-to-specify-the-classpath) 1. Look at each of the JAR and ZIP files on the classpath to see if they contain a class with the required pathname. 1. Look at each directory to see if the pathname resolves to a file within the directory.
- Check that it exactly matches the full classname for the entry-point class.
- It should not end with ".java" or ".class".
- It should not contain slashes or any other character that is not legal in a Java identifier 1 .
- The casing of the name should exactly match the full class name.
If checking the classpath by hand did not find the issue, you could add the -Xdiag and -XshowSettings options. The former lists all classes that are loaded, and the latter prints out settings that include the effective classpath for the JVM.
Finally, there are some obscure causes for this problem:
- An executable JAR file with a Main-Class attribute that specifies a class that does not exist.
- An executable JAR file with an incorrect Class-Path attribute.
- If you mess up 2 the options before the classname, the java command may attempt to interpret one of them as the classname.
- If someone has ignored Java style rules and used package or class identifiers that differ only in letter case, and you are running on a platform that treats letter case in filenames as non-significant.
- Problems with homoglyphs in class names in the code or on the command line.
# "Main method not found in class "
This problem happens when the java command is able to find and load the class that you nominated, but is then unable to find an entry-point method.
There are three possible explanations:
- If you are trying to run an executable JAR file, then the JAR’s manifest has an incorrect "Main-Class" attribute that specifies a class that is not a valid entry point class.
- You have told the java command a class that is not an entry point class.
- The entry point class is incorrect; see Entry point classes
# Other Resources
1 — From Java 8 and later, the java command will helpfully map a filename separator ("/" or "") to a period ("."). However, this behavior is not documented in the manual pages.
2 — A really obscure case is if you copy-and-paste a command from a formatted document where the text editor has used a "long hyphen" instead of a regular hyphen.
# Running a Java application with library dependencies
This is a continuation of the "main class"
Typical Java applications consist of an application-specific code, and various reusable library code that you have implemented or that has been implemented by third parties. The latter are commonly referred to as library dependencies, and are typically packaged as JAR files.
Java is a dynamically bound language. When you run a Java application with library dependencies, the JVM needs to know where the dependencies are so that it can load classes as required. Broadly speaking, there are two ways to deal with this:
For an executable JAR file, the runtime classpath is specified by the "Class-Path" manifest attribute. (Editorial Note: This should be described in a separate Topic on the jar command.) Otherwise, the runtime classpath needs to be supplied using the -cp option or using the CLASSPATH environment variable.
For example, suppose that we have a Java application in the "myApp.jar" file whose entry point class is com.example.MyApp . Suppose also that the application depends on library JAR files "lib/library1.jar" and "lib/library2.jar". We could launch the application using the java command as follows in a command line:
(On Windows, you would use ; instead of : as the classpath separator, and you would set the (local) CLASSPATH variable using set rather than export .)
While a Java developer would be comfortable with that, it is not "user friendly". So it is common practice to write a simple shell script (or Windows batch file) to hide the details that the user doesn’t need to know about. For example, if you put the following shell script into a file called "myApp", made it executable, and put it into a directory on the command search path:
then you could run it as follows:
Any arguments on the command line will be passed to the Java application via the "$@" expansion. (You can do something similar with a Windows batch file, though the syntax is different.)
# Spaces and other special characters in arguments
First of all, the problem of handling spaces in arguments is NOT actually a Java problem. Rather it is a problem that needs to be handled by the command shell that you are using when you run a Java program.
As an example, let us suppose that we have the following simple program that prints the size of a file:
Now suppose that we want print the size of a file whose pathname has spaces in it; e.g. /home/steve/Test File.txt . If we run the command like this:
the shell won’t know that /home/steve/Test File.txt is actually one pathname. Instead, it will pass 2 distinct arguments to the Java application, which will attempt to find their respective file sizes, and fail because files with those paths (probably) do not exist.
# Solutions using a POSIX shell
POSIX shells include sh as well derivatives such as bash and ksh . If you are using one of these shells, then you can solve the problem by quoting the argument.
The double-quotes around the pathname tell the shell that it should be passed as a single argument. The quotes will be removed when this happens. There are a couple of other ways to do this:
Single (straight) quotes are treated like double-quotes except that they also suppress various expansions within the argument.
A backslash escapes the following space, and causes it not to be interpreted as an argument separator.
For more comprehensive documentation, including descriptions of how to deal with other special characters in arguments, please refer to the quoting topic
# Solution for Windows
The fundamental problem for Windows is that at the OS level, the arguments are passed to a child process as a single string (source
(opens new window) ). This means that the ultimate responsibility of parsing (or re-parsing) the command line falls on either program or its runtime libraries. There is lots of inconsistency.
In the Java case, to cut a long story short:
For more detail, please refer to the Batch-File
# Java Options
The java command supports a wide range of options:
# Setting system properties with -D
The -D<property>=<value> option is used to set a property in the system Properties object. This parameter can be repeated to set different properties.
# Memory, Stack and Garbage Collector options
The main options for controlling the heap and stack sizes are documented in Setting the Heap, PermGen and Stack sizes
(opens new window) . (Editorial note: Garbage Collector options should be described in the same topic.)
# Enabling and disabling assertions
The -ea and -da options respectively enable and disable Java assert checking:
- All assertion checking is disabled by default.
- The -ea option enables checking of all assertions
- The -ea:<packagename>. enables checking of assertions in a package and all subpackages.
- The -ea:<classname>. enables checking of assertions in a class.
- The -da option disables checking of all assertions
- The -da:<packagename>. disables checking of assertions in a package and all subpackages.
- The -da:<classname>. disables checking of assertions in a class.
- The -esa option enables checking for all system classes.
- The -dsa option disables checking for all system classes.
The options can be combined. For example.
Note that enabling to assertion checking is liable to alter the behavior of a Java programming.
- It is liable make the application slower in general.
- It can cause specific methods to take longer to run, which could change timing of threads in a multi-threaded application.
- It can introduce serendipitous happens-before relations which can cause memory anomalies to disappear.
- An incorrectly implemented assert statement could have unwanted side-effects.
# Selecting the VM type
The -client and -server options allow you to select between two different forms of the HotSpot VM:
- The "client" form is tuned for user applications and offers faster startup.
- The "server" form is tuned for long running applications. It takes longer capturing statistic during JVM "warm up" which allows the JIT compiler to do a better of job of optimizing the native code.
By default, the JVM will run in 64bit mode if possible, depending on the capabilities of the platform. The -d32 and -d64 options allow you to select the mode explicitly.
1 — Check the official manual for the java command. Sometimes a standard option is described as "subject to change".
# Syntax
# Remarks
The java command is used for running a Java application from the command line. It is available as a part of any Java SE JRE or JDK.
On Windows systems there are two variants of the java command:
- The java variant launches the application in a new console window.
- The javaw variant launches the application without creating a new console window.
On other systems (e.g. Linux, Mac OSX, UNIX) only the java command is provided, and it does not launch a new console window.
The <opt> symbol in the syntax denotes an option on the java command line. The "Java Options" and "Heap and stack sizing options" topics cover the most commonly used options. Others are covered in the JVM Flags
Running JAR-Packaged Software
Now that you have learned how to create JAR files, how do you actually run the code you packaged? Consider these scenarios:
- Your JAR file contains an applet that is to be run inside a browser.
- Your JAR file contains an application that is to be started from the command line.
- Your JAR file contains code that you want to use as an extension.
This section will cover the first two situations. A separate trail in the tutorial on the extension mechanism covers the use of JAR files as extensions.
Applets Packaged in JAR Files
To start any applet from an HTML file for running inside a browser, you use the applet tag. For more information, see the Java Applets lesson. If the applet is bundled as a JAR file, the only thing you need to do differently is to use the archive parameter to specify the relative path to the JAR file.
As an example, use the TicTacToe demo applet. The applet tag in the HTML file that displays the applet can be marked up like this:
If the TicTacToe demo was packaged in a JAR file named TicTacToe.jar, you can modify the applet tag with the addition of an archive parameter:
The archive parameter specifies the relative path to the JAR file that contains TicTacToe.class. For this example it is assumed that the JAR file and the HTML file are in the same directory. If they are not, you must include the JAR file's relative path in the archive parameter's value. For example, if the JAR file was one directory below the HTML file in a directory called applets, the applet tag would look like this:
JAR Files as Applications
You can run JAR packaged applications with the Java launcher (java command). The basic command is:
The -jar flag tells the launcher that the application is packaged in the JAR file format. You can only specify one JAR file, which must contain all of the application-specific code.
Before you execute this command, make sure that the runtime environment has information about which class within the JAR file is the application's entry point.
To indicate which class is the application's entry point, you must add a Main-Class header to the JAR file's manifest. The header takes the form:
The header's value, classname, is the name of the class that is the application's entry point.
For more information, see the Setting an Application’s Entry Point section.
When the Main-Class is set in the manifest file, you can run the application from the command line:
Способы запуска исполняемого файла JAR

Чтобы иметь возможность запускать исполняемые файлы JAR без использования эмуляторов, на компьютер необходимо установить платформу Java. Устанавливается компонент как обычная программа.
Способ 1: Меню Java (TM) Platform SE

Сразу нужно отметить, что возможности данного способа ограничены. Хотя последняя версия платформы Java поддерживает запуск файлов JAR, далеко не факт, что конкретная Java-программа будет выполнена. Способ прост: кликните правой кнопкой мыши по файлу JAR и выберите в контекстном меню опцию «Открыть с помощью» «Java (TM) Platform SE binary».
Если ничего не произойдет, переходите к следующему способу.
Способ 2: Запуск в «Командной строке»
Попробуйте запустить исполняемый файл в консоли, если Java-программа не запустится, — по крайней мере, команда запуска вернет описание ошибки, по которому можно будет установить характер проблемы.
- Запустите из контекстного меню или системного поиска «Командную строку» или «PowerShell» (можно с обычными правами).

- Сформируйте и выполните команду вида java -jar «D:\executablejarfile.jar» , где содержимое кавычек – это путь к исполняемому файл JAR.

Способ 3: Эмуляторы Java
Лучше всего для запуска приложений Java использовать специальные программы-эмуляторы, из которых самым известным, универсальным и наиболее функциональным является KEmulator Lite. В настоящее время официальный сайт разработчика недоступен, но приложение по-прежнему можно найти в свободном доступе в интернете. Рекомендуем использовать русифицированную портативную версию эмулятора.
- Скачайте архив с программой, распакуйте в удобное расположение и запустите исполняемый файл KEmulator.exe.
Если файл не запустится или эмулятор выдаст ошибку, возможно, что-то не так с самим JAR-файлом либо для полноценной работы эмулятора требуются дополнительные компоненты, в частности Java SE Development.
Sony Ericsson SDK
В качестве альтернативы маловесному KEmulator Lite можно попробовать полноценную платформу виртуализации Java-приложений Sony Ericsson SDK. Официальный сайт разработчика более недоступен, однако эмулятор по-прежнему находится в свободном доступе. Также для этого понадобится набор библиотек Java SE Development Kit и утилита JADMaker, которую также придется поискать на просторах интернета.
- Скачайте Sony Ericsson SDK, Java SE Development Kit (рекомендуется версия 8u191 x86) и JADMaker.
- Установите сначала Java SE Development Kit, а затем Sony Ericsson SDK. Инсталляцию следует выполнять с настройками по умолчанию, если вдруг эмулятор попросит добавить себя в исключения брандмауэра Windows, на это нужно дать согласие. Архив с утилитой JADMaker распакуйте в удобное расположение, она понадобится позже. В начале установки Sony Ericsson SDK появится окошко с предложением автоматического обнаружения каталогов Java SE Development Kit, нажмите в этом окошке «Да».

- Установив набор библиотек и эмулятор Sony Ericsson, зайдите в меню «Пуск» и выберите опцию «Sony Ericsson» → «Default Device Selection».

- В открывшемся диалоговом окне выберите модель виртуального мобильного телефона, который станет использоваться по умолчанию.

- Запустите утилиту JADMaker и перетащите на ее окошко файл JAR, который будет преобразован в файл JAD. По умолчанию сконвертированный файл сохраняется в исходную папку.

- Откройте опять меню «Пуск» и запустите эмулятор, выбрав опцию «Sony Ericsson» → «Run WIDP Application».

- В открывшемся окне обзора укажите путь к сконвертированному в JAD файлу JAR.

- В результате откроется окно эмулятора с названием Java-приложения. Чтобы его запустить, нажмите кнопку «Launch».

К сожалению, использование даже такого мощного инструмента как Sony Ericsson SDK не гарантирует, что Java-приложение будет сразу же успешно запущено. Успех или неудача будут зависть от ряда факторов, как то: совместимость версии Java-приложения с эмулируемым мобильным устройством, а также сборки Windows 10. Так, по каким-то причинам в последних сборках этой системы платформа Sony Ericsson SDK работает некорректно.
Как открыть jar файл с помощью java
Though it’s a newer programming language with a small development community, Roc is meant to be an easy-to-read language that .
Review these five common RESTful API HTTP methods that developers need to know. Use this guide to understand the differences and .
As developers build more complex applications, the widespread use of APIs is creating significant security challenges for .
New to containerization and Kubernetes? Here’s what the dev team should know about container image scanning, container file .
Google’s generative AI products play catch-up with Copilot and others, but the upcoming addition of Duet AI to AppSheet might .
Performing QA duties properly should mean more than checking lists of basic application requirements. Here are five ways software.
VMware Explore 2023 kicked off with big announcements surrounding generative AI and multi-cloud innovation. Read up on the latest.
A lack of visibility means organizations can easily lose unused resources which rack up costs. However, there are tools and best .
Don’t pay for resources you don’t use. Implement these best practices to avoid overprovisioning through access controls, policies.
With a ransomware recovery plan, organizations can act quickly to prevent data loss without descending into chaos. Learn the six .
There are eight main types of ransomware but hundreds of examples of ransomware strains. Learn how the ransomware types work, and.
Executives, researchers and former employees told TechTarget Editorial about issues with Microsoft security practices, including .
Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .