Как скомпилировать консольную программу в java

от admin

javac

Reads Java class and interface definitions and compiles them into bytecode and class files.

Synopsis

javac [ options ] [ sourcefiles ] [ classes] [ @argfiles ]

Arguments can be in any order:

Command-line options. See Options.

sourcefiles

One or more source files to be compiled (such as MyClass.java ).

One or more classes to be processed for annotations (such as MyPackage.MyClass ).

One or more files that list options and source files. The -J options are not allowed in these files. See Command-Line Argument Files.

Description

The javac command reads class and interface definitions, written in the Java programming language, and compiles them into bytecode class files. The javac command can also process annotations in Java source files and classes.

There are two ways to pass source code file names to javac .

For a small number of source files, list the file names on the command line.

For a large number of source files, list the file names in a file that is separated by blanks or line breaks. Use the list file name preceded by an at sign (@) with the javac command.

Source code file names must have .java suffixes, class file names must have .class suffixes, and both source and class files must have root names that identify the class. For example, a class called MyClass would be written in a source file called MyClass.java and compiled into a bytecode class file called MyClass.class .

Inner class definitions produce additional class files. These class files have names that combine the inner and outer class names, such as MyClass$MyInnerClass.class .

Arrange source files in a directory tree that reflects their package tree. For example, if all of your source files are in \workspace , then put the source code for com.mysoft.mypack.MyClass in /workspace in \ workspace\com\mysoft\mypack\MyClass.java .

By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d option.

Options

The compiler has a set of standard options that are supported on the current development environment. An additional set of nonstandard options are specific to the current virtual machine and compiler implementations and are subject to change in the future. Nonstandard options begin with the -X option.

Standard Options

Specifies options to pass to annotation processors. These options are not interpreted by javac directly, but are made available for use by individual processors. The key value should be one or more identifiers separated by a dot (.).

-cp path or -classpath path

Specifies where to find user class files, and (optionally) annotation processors and source files. This class path overrides the user class path in the CLASSPATH environment variable. If neither CLASSPATH , -cp nor -classpath is specified, then the user class path is the current directory. See Setting the Class Path.

If the -sourcepath option is not specified, then the user class path is also searched for source files.

If the -processorpath option is not specified, then the class path is also searched for annotation processors.

-Djava.ext.dirs=directories

Overrides the location of installed extensions.

-Djava.endorsed.dirs=directories

Overrides the location of the endorsed standards path.

-d directory

Sets the destination directory for class files. The directory must already exist because javac does not create it. If a class is part of a package, then javac puts the class file in a subdirectory that reflects the package name and creates directories as needed.

If you specify -d C:\myclasses and the class is called com.mypackage.MyClass , then the class file is C:\myclasses\com\mypackage\MyClass.class .

If the -d option is not specified, then javac puts each class file in the same directory as the source file from which it was generated.

Note: The directory specified by the -d option is not automatically added to your user class path.

Shows a description of each use or override of a deprecated member or class. Without the -deprecation option, javac shows a summary of the source files that use or override deprecated members or classes. The -deprecation option is shorthand for -Xlint:deprecation .

-encoding encoding

Sets the source file encoding name, such as EUC-JP and UTF-8. If the -encoding option is not specified, then the platform default converter is used.

-endorseddirs directories

Overrides the location of the endorsed standards path.

-extdirs directories

Overrides the location of the ext directory. The directories variable is a colon-separated list of directories. Each JAR file in the specified directories is searched for class files. All JAR files found become part of the class path.

If you are cross-compiling (compiling classes against bootstrap and extension classes of a different Java platform implementation), then this option specifies the directories that contain the extension classes. See Cross-Compilation Options for more information.

Generates all debugging information, including local variables. By default, only line number and source file information is generated.

Does not generate any debugging information.

-g:[keyword list]

Generates only some kinds of debugging information, specified by a comma separated list of keywords. Valid keywords are:

Source file debugging information.

Line number debugging information.

Local variable debugging information.

Prints a synopsis of standard options.

-implicit:[class, none]

Controls the generation of class files for implicitly loaded source files. To automatically generate class files, use -implicit:class . To suppress class file generation, use -implicit:none . If this option is not specified, then the default is to automatically generate class files. In this case, the compiler issues a warning if any such class files are generated when also doing annotation processing. The warning is not issued when the -implicit option is set explicitly. See Searching for Types.

Passes option to the Java Virtual Machine (JVM), where option is one of the options described on the reference page for the Java launcher. For example, -J-Xms48m sets the startup memory to 48 MB. See java (1).

Note: The CLASSPATH, -classpath , -bootclasspath , and -extdirs options do not specify the classes used to run javac . Trying to customize the compiler implementation with these options and variables is risky and often does not accomplish what you want. If you must customize the complier implementation, then use the -J option to pass options through to the underlying Java launcher.

Disables warning messages. This option operates the same as the -Xlint:none option.

Stores formal parameter names of constructors and methods in the generated class file so that the method java.lang.reflect.Executable.getParameters from the Reflection API can retrieve them.

-proc: [none, only]

Controls whether annotation processing and compilation are done. -proc:none means that compilation takes place without annotation processing. -proc:only means that only annotation processing is done, without any subsequent compilation.

-processor class1 [,class2,class3. ]

Names of the annotation processors to run. This bypasses the default discovery process.

-processorpath path

Specifies where to find annotation processors. If this option is not used, then the class path is searched for processors.

Specifies the directory where to place the generated source files. The directory must already exist because javac does not create it. If a class is part of a package, then the compiler puts the source file in a subdirectory that reflects the package name and creates directories as needed.

If you specify -s C:\mysrc and the class is called com.mypackage.MyClass , then the source file is put in in C:\ mysrc\com\mypackage\MyClass.java .

-source release

Specifies the version of source code accepted. The following values for release are allowed:

The compiler does not support assertions, generics, or other language features introduced after Java SE 1.3.

The compiler accepts code containing assertions, which were introduced in Java SE 1.4.

The compiler accepts code containing generics and other language features introduced in Java SE 5.

No language changes were introduced in Java SE 6. However, encoding errors in source files are now reported as errors instead of warnings as in earlier releases of Java Platform, Standard Edition.

The compiler accepts code with features introduced in Java SE 7.

This is the default value. The compiler accepts code with features introduced in Java SE 8.

-sourcepath sourcepath

Specifies the source code path to search for class or interface definitions. As with the user class path, source path entries are separated by colons (:) on Oracle Solaris and semicolons on Windows and can be directories, JAR archives, or ZIP archives. If packages are used, then the local path name within the directory or archive must reflect the package name.

Note: Classes found through the class path might be recompiled when their source files are also found. See Searching for Types.

Uses verbose output, which includes information about each class loaded and each source file compiled.

Prints release information.

Terminates compilation when warnings occur.

Displays information about nonstandard options and exits.

Cross-Compilation Options

By default, classes are compiled against the bootstrap and extension classes of the platform that javac shipped with. But javac also supports cross-compiling, where classes are compiled against a bootstrap and extension classes of a different Java platform implementation. It is important to use the -bootclasspath and -extdirs options when cross-compiling.

-target version

Generates class files that target a specified release of the virtual machine. Class files will run on the specified target and on later releases, but not on earlier releases of the JVM. Valid targets are 1.1, 1.2, 1.3, 1.4, 1.5 (also 5), 1.6 (also 6), 1.7 (also 7), and 1.8 (also 8).

The default for the -target option depends on the value of the -source option:

If the -source option is not specified, then the value of the -target option is 1.8

If the -source option is 1.2, then the value of the -target option is 1.4

If the -source option is 1.3, then the value of the -target option is 1.4

If the -source option is 1.5, then the value of the -target option is 1.8

If the -source option is 1.6, then the value of the -target is option 1.8

If the -source option is 1.7, then the value of the -target is option 1.8

For all other values of the -source option, the value of the -target option is the value of the -source option.

Cross-compiles against the specified set of boot classes. As with the user class path, boot class path entries are separated by colons (:) and can be directories, JAR archives, or ZIP archives.

Compact Profile Option

Beginning with JDK 8, the javac compiler supports compact profiles. With compact profiles, applications that do not require the entire Java platform can be deployed and run with a smaller footprint. The compact profiles feature could be used to shorten the download time for applications from app stores. This feature makes for more compact deployment of Java applications that bundle the JRE. This feature is also useful in small devices.

The supported profile values are compact1 , compact2 , and compact3 . These are additive layers. Each higher-numbered compact profile contains all of the APIs in profiles with smaller number names.

When using compact profiles, this option specifies the profile name when compiling. For example:

javac does not compile source code that uses any Java SE APIs that is not in the specified profile. Here is an example of the error message that results from attempting to compile such source code:

In this example, you can correct the error by modifying the source to not use the Applet class. You could also correct the error by compiling without the -profile option. Then the compilation would be run against the full set of Java SE APIs. (None of the compact profiles include the Applet class.)

An alternative way to compile with compact profiles is to use the -bootclasspath option to specify a path to an rt.jar file that specifies a profile’s image. Using the -profile option instead does not require a profile image to be present on the system at compile time. This is useful when cross-compiling.

Nonstandard Options

Adds a suffix to the bootstrap class path.

-Xbootclasspath/a:path

Adds a prefix to the bootstrap class path.

-Xbootclasspath/:path

Overrides the location of the bootstrap class files.

-Xdoclint:[-] group [ /access ]

Enables or disables specific groups of checks, where group is one of the following values: accessibility , syntax , reference , html or missing . For more information about these groups of checks see the -Xdoclint option of the javadoc command. The -Xdoclint option is disabled by default in the javac command.

The variable access specifies the minimum visibility level of classes and members that the -Xdoclint option checks. It can have one of the following values (in order of most to least visible) : public , protected , package and private . For example, the following option checks classes and members (with all groups of checks) that have the access level protected and higher (which includes protected, package and public):

The following option enables all groups of checks for all access levels, except it will not check for HTML errors for classes and members that have access level package and higher (which includes package and public):

Disables all groups of checks.

Enables all groups of checks.

Enables all recommended warnings. In this release, enabling all available warnings is recommended.

Enables all recommended warnings. In this release, enabling all available warnings is recommended.

Disables all warnings.

Disables warning name. See Enable or Disable Warnings with the -Xlint Option for a list of warnings you can disable with this option.

Disables warning name. See Enable or Disable Warnings with the -Xlint Option with the -Xlint option to get a list of warnings that you can disable with this option.

-Xmaxerrs number

Sets the maximum number of errors to print.

-Xmaxwarns number

Sets the maximum number of warnings to print.

-Xstdout filename

Sends compiler messages to the named file. By default, compiler messages go to System.err .

-Xprefer:[newer,source]

Specifies which file to read when both a source file and class file are found for a type. (See Searching for Types). If the -Xprefer:newer option is used, then it reads the newer of the source or class file for a type (default). If the -Xprefer:source option is used, then it reads the source file. Use — Xprefer:source when you want to be sure that any annotation processors can access annotations declared with a retention policy of SOURCE .

-Xpkginfo:[always,legacy,nonempty]

Control whether javac generates package-info.class files from package-info.java files. Possible mode arguments for this option include the following.

Always generate a package-info.class file for every package-info.java file. This option may be useful if you use a build system such as Ant, which checks that each .java file has a corresponding .class file.

Generate a package-info.class file only if package-info.java contains annotations. Don’t generate a package-info.class file if package-info.java only contains comments.

Note: A package-info.class file might be generated but be empty if all the annotations in the package-info.java file have RetentionPolicy.SOURCE .

Generate a package-info.class file only if package-info.java contains annotations with RetentionPolicy.CLASS or RetentionPolicy.RUNTIME .

Prints a textual representation of specified types for debugging purposes. Perform neither annotation processing nor compilation. The format of the output could change.

Prints information about which annotations a processor is asked to process.

Prints information about initial and subsequent annotation processing rounds.

Enable or Disable Warnings with the -Xlint Option

Enable warning name with the -Xlint:name option, where name is one of the following warning names. Note that you can disable a warning with the -Xlint:-name: option.

Warns about unnecessary and redundant casts, for example:

Warns about issues related to class file contents.

Warns about the use of deprecated items, for example:

The method java.util.Date.getDay has been deprecated since JDK 1.1

Warns about items that are documented with an @deprecated Javadoc comment, but do not have a @Deprecated annotation, for example:

Warns about division by the constant integer 0, for example:

Warns about empty statements after if statements, for example:

Checks the switch blocks for fall-through cases and provides a warning message for any that are found. Fall-through cases are cases in a switch block, other than the last case in the block, whose code does not include a break statement, allowing code execution to fall through from that case to the next case. For example, the code following the case 1 label in this switch block does not end with a break statement:

If the -Xlint:fallthrough option was used when compiling this code, then the compiler emits a warning about possible fall-through into case, with the line number of the case in question.

Warns about finally clauses that cannot complete normally, for example:

The compiler generates a warning for the finally block in this example. When the int method is called, it returns a value of 0. A finally block executes when the try block exits. In this example, when control is transferred to the catch block, the int method exits. However, the finally block must execute, so it is executed, even though control was transferred outside the method.

Warns about issues that related to the use of command-line options. See Cross-Compilation Options.

Warns about issues regarding method overrides. For example, consider the following two classes:

The compiler generates a warning similar to the following:.

When the compiler encounters a varargs method, it translates the varargs formal parameter into an array. In the method ClassWithVarargsMethod.varargsMethod , the compiler translates the varargs formal parameter String. s to the formal parameter String[] s , an array, which matches the formal parameter of the method ClassWithOverridingMethod.varargsMethod . Consequently, this example compiles.

Warns about invalid path elements and nonexistent path directories on the command line (with regard to the class path, the source path, and other paths). Such warnings cannot be suppressed with the @SuppressWarnings annotation, for example:

Warn about issues regarding annotation processing. The compiler generates this warning when you have a class that has an annotation, and you use an annotation processor that cannot handle that type of exception. For example, the following is a simple annotation processor:

Source file AnnocProc.java:

Source file AnnosWithoutProcessors.java:

The following commands compile the annotation processor AnnoProc , then run this annotation processor against the source file AnnosWithoutProcessors.java :

When the compiler runs the annotation processor against the source file AnnosWithoutProcessors.java , it generates the following warning:

To resolve this issue, you can rename the annotation defined and used in the class AnnosWithoutProcessors from Anno to NotAnno .

Warns about unchecked operations on raw types. The following statement generates a rawtypes warning:

The following example does not generate a rawtypes warning

List is a raw type. However, List<?> is an unbounded wildcard parameterized type. Because List is a parameterized interface, always specify its type argument. In this example, the List formal argument is specified with an unbounded wildcard ( ? ) as its formal type parameter, which means that the countElements method can accept any instantiation of the List interface.

Warns about missing serialVersionUID definitions on serializable classes, for example:

The compiler generates the following warning:

If a serializable class does not explicitly declare a field named serialVersionUID , then the serialization runtime environment calculates a default serialVersionUID value for that class based on various aspects of the class, as described in the Java Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values because the default process of computing serialVersionUID vales is highly sensitive to class details that can vary depending on compiler implementations, and as a result, might cause an unexpected InvalidClassExceptions during deserialization. To guarantee a consistent serialVersionUID value across different Java compiler implementations, a serializable class must declare an explicit serialVersionUID value.

Warns about issues relating to the use of statics, for example:

The compiler generates the following warning:

To resolve this issue, you can call the static method m1 as follows:

Alternately, you can remove the static keyword from the declaration of the method m1 .

Warns about issues relating to use of try blocks, including try-with-resources statements. For example, a warning is generated for the following statement because the resource ac declared in the try block is not used:

Gives more detail for unchecked conversion warnings that are mandated by the Java Language Specification, for example:

During type erasure, the types ArrayList<Number> and List<String> become ArrayList and List , respectively.

The ls command has the parameterized type List<String> . When the List referenced by l is assigned to ls , the compiler generates an unchecked warning. At compile time, the compiler and JVM cannot determine whether l refers to a List<String> type. In this case, l does not refer to a List<String> type. As a result, heap pollution occurs.

A heap pollution situation occurs when the List object l , whose static type is List<Number> , is assigned to another List object, ls , that has a different static type, List<String> . However, the compiler still allows this assignment. It must allow this assignment to preserve backward compatibility with releases of Java SE that do not support generics. Because of type erasure, List<Number> and List<String> both become List . Consequently, the compiler allows the assignment of the object l , which has a raw type of List , to the object ls .

Warns about unsafe usages of variable arguments ( varargs ) methods, in particular, those that contain non-reifiable arguments, for example:

Note: A non-reifiable type is a type whose type information is not fully available at runtime.

The compiler generates the following warning for the definition of the method ArrayBuilder.addToList

When the compiler encounters a varargs method, it translates the varargs formal parameter into an array. However, the Java programming language does not permit the creation of arrays of parameterized types. In the method ArrayBuilder.addToList , the compiler translates the varargs formal parameter T. elements to the formal parameter T[] elements, an array. However, because of type erasure, the compiler converts the varargs formal parameter to Object[] elements. Consequently, there is a possibility of heap pollution.

Command-Line Argument Files

To shorten or simplify the javac command, you can specify one or more files that contain arguments to the javac command (except -J options). This enables you to create javac commands of any length on any operating system.

An argument file can include javac options and source file names in any combination. The arguments within a file can be separated by spaces or new line characters. If a file name contains embedded spaces, then put the whole file name in double quotation marks.

File Names within an argument file are relative to the current directory, not the location of the argument file. Wild cards (*) are not allowed in these lists (such as for specifying *.java ). Use of the at sign (@) to recursively interpret files is not supported. The -J options are not supported because they are passed to the launcher, which does not support argument files.

When executing the javac command, pass in the path and name of each argument file with the at sign (@) leading character. When the javac command encounters an argument beginning with the at sign (@), it expands the contents of that file into the argument list.

You could use a single argument file named argfile to hold all javac arguments:

This argument file could contain the contents of both files shown in Example 2

You can create two argument files: one for the javac options and the other for the source file names. Note that the following lists have no line-continuation characters.

Create a file named options that contains the following:

Create a file named classes that contains the following:

Then, run the javac command as follows:

The argument files can have paths, but any file names inside the files are relative to the current working directory (not path1 or path2 ):

Annotation Processing

The javac command provides direct support for annotation processing, superseding the need for the separate annotation processing command, apt .

The API for annotation processors is defined in the javax.annotation.processing and j avax.lang.model packages and subpackages.

Читать:
Как из сборки сделать деталь в solidworks

How Annotation Processing Works

Unless annotation processing is disabled with the -proc:none option, the compiler searches for any annotation processors that are available. The search path can be specified with the -processorpath option. If no path is specified, then the user class path is used. Processors are located by means of service provider-configuration files named META-INF/services/javax.annotation.processing .Processor on the search path. Such files should contain the names of any annotation processors to be used, listed one per line. Alternatively, processors can be specified explicitly, using the -processor option.

After scanning the source files and classes on the command line to determine what annotations are present, the compiler queries the processors to determine what annotations they process. When a match is found, the processor is called. A processor can claim the annotations it processes, in which case no further attempt is made to find any processors for those annotations. After all of the annotations are claimed, the compiler does not search for additional processors.

If any processors generate new source files, then another round of annotation processing occurs: Any newly generated source files are scanned, and the annotations processed as before. Any processors called on previous rounds are also called on all subsequent rounds. This continues until no new source files are generated.

After a round occurs where no new source files are generated, the annotation processors are called one last time, to give them a chance to complete any remaining work. Finally, unless the -proc:only option is used, the compiler compiles the original and all generated source files.

Implicitly Loaded Source Files

To compile a set of source files, the compiler might need to implicitly load additional source files. See Searching for Types. Such files are currently not subject to annotation processing. By default, the compiler gives a warning when annotation processing occurred and any implicitly loaded source files are compiled. The -implicit option provides a way to suppress the warning.

Searching for Types

To compile a source file, the compiler often needs information about a type, but the type definition is not in the source files specified on the command line. The compiler needs type information for every class or interface used, extended, or implemented in the source file. This includes classes and interfaces not explicitly mentioned in the source file, but that provide information through inheritance.

For example, when you create a subclass java.applet.Applet , you are also using the ancestor classes of Applet : java.awt.Panel , java.awt.Container , java.awt.Component , and java.lang.Object .

When the compiler needs type information, it searches for a source file or class file that defines the type. The compiler searches for class files first in the bootstrap and extension classes, then in the user class path (which by default is the current directory). The user class path is defined by setting the CLASSPATH environment variable or by using the -classpath option.

If you set the -sourcepath option, then the compiler searches the indicated path for source files. Otherwise, the compiler searches the user class path for both class files and source files.

You can specify different bootstrap or extension classes with the -bootclasspath and the -extdirs options. See Cross-Compilation Options.

A successful type search may produce a class file, a source file, or both. If both are found, then you can use the -Xprefer option to instruct the compiler which to use. If newer is specified, then the compiler uses the newer of the two files. If source is specified, the compiler uses the source file. The default is newer .

If a type search finds a source file for a required type, either by itself, or as a result of the setting for the -Xprefer option, then the compiler reads the source file to get the information it needs. By default the compiler also compiles the source file. You can use the -implicit option to specify the behavior. If none is specified, then no class files are generated for the source file. If class is specified, then class files are generated for the source file.

The compiler might not discover the need for some type information until after annotation processing completes. When the type information is found in a source file and no -implicit option is specified, the compiler gives a warning that the file is being compiled without being subject to annotation processing. To disable the warning, either specify the file on the command line (so that it will be subject to annotation processing) or use the -implicit option to specify whether or not class files should be generated for such source files.

Programmatic Interface

The javac command supports the new Java Compiler API defined by the classes and interfaces in the javax.tools package.

Example

To compile as though providing command-line arguments, use the following syntax:

The example writes diagnostics to the standard output stream and returns the exit code that javac would give when called from the command line.

You can use other methods in the javax.tools.JavaCompiler interface to handle diagnostics, control where files are read from and written to, and more.

Old Interface

Note: This API is retained for backward compatibility only. All new code should use the newer Java Compiler API.

The com.sun.tools.javac.Main class provides two static methods to call the compiler from a program:

The args parameter represents any of the command-line arguments that would typically be passed to the compiler.

The out parameter indicates where the compiler diagnostic output is directed.

The return value is equivalent to the exit value from javac .

Note: All other classes and methods found in a package with names that start with com.sun.tools.javac (subpackages of com.sun.tools.javac ) are strictly internal and subject to change at any time.

Examples

This example shows how to compile the Hello.java source file in the greetings directory. The class defined in Hello.java is called greetings.Hello . The greetings directory is the package directory both for the source file and the class file and is underneath the current directory. This makes it possible to use the default user class path. It also makes it unnecessary to specify a separate destination directory with the -d option.

The source code in Hello.java :

This example compiles the Aloha.java , GutenTag.java , Hello.java , and Hi.java source files in the greetings package.

After changing one of the source files in the previous example, recompile it:

Because greetings.Hi refers to other classes in the greetings package, the compiler needs to find these other classes. The previous example works because the default user class path is the directory that contains the package directory. If you want to recompile this file without concern for which directory you are in, then add the examples directory to the user class path by setting CLASSPATH . This example uses the -classpath option.

If you change greetings.Hi to use a banner utility, then that utility also needs to be accessible through the user class path.

To execute a class in the greetings package, the program needs access to the greetings package, and to the classes that the greetings classes use.

The following example uses javac to compile code that runs on JVM 1.7.

The -source 1.7 option specifies that release 1.7 (or 7) of the Java programming language be used to compile OldCode.java . The option -target 1.7 option ensures that the generated class files are compatible with JVM 1.7. Note that in most cases, the value of the -target option is the value of the -source option; in this example, you can omit the -target option.

You must specify the -bootclasspath option to specify the correct version of the bootstrap classes (the rt.jar library). If not, then the compiler generates a warning:

If you do not specify the correct version of bootstrap classes, then the compiler uses the old language rules (in this example, it uses version 1.7 of the Java programming language) combined with the new bootstrap classes, which can result in class files that do not work on the older platform (in this case, Java SE 7) because reference to nonexistent methods can get included.

This example uses javac to compile code that runs on JVM 1.7.

The -source 1.7 option specifies that release 1.7 (or 7) of the Java programming language to be used to compile OldCode.java. The -target 1.7 option ensures that the generated class files are compatible with JVM 1.7.

You must specify the -bootclasspath option to specify the correct version of the bootstrap classes (the rt.jar library). If not, then the compiler generates a warning:

If you do not specify the correct version of bootstrap classes, then the compiler uses the old language rules combined with the new bootstrap classes. This combination can result in class files that do not work on the older platform (in this case, Java SE 7) because reference to nonexistent methods can get included. In this example, the compiler uses release 1.7 of the Java programming language.

Как скомпилировать консольную программу в java

Итак, после установки JDK создадим первое приложение на языке Java. Что необходимо для создания программы на Java? Прежде всего нам надо написать код программы, и для этого нужен текстовый редактор. Можно использовать любой текстовый редактор, например, Notepad++.

И чтобы превратить код программы в исполняемое приложение необходим компилятор. После установки JDK все файлы по умолчанию помещаются в каталог C:\Program Files\Java\jdk-[номер_версии] (при использовании ОС Windows). В моем случае это каталог C:\Program Files\Java\jdk-19 . Если мы откроем в нем подкаталог bin , то мы сможем увидеть в нем ряд утилит. Нас прежде всего интересует утилита компилятора javac . Чтобы скомпилировать класс программы, нам надо передать ее код этому компилятору.

Компилятор javac в Java

Также следует отметить другую утилиту из этой папки — java.exe, которая позволяет запускать скомпилированную программу.

Итак, создадим на жестком диске какой-нибудь каталог, в котором будут располагаться файлы с исходным кодом на языке Java. Допустим, это будет каталог C:/Java . Затем создадим в этом каталоге текстовый файл, который переименуем в Program.java . Откроем этот файл в любом текстовом редакторе и наберем в нем следующую программу:

Java является объектно-ориентированным языком, поэтому вся программа представляется в виде набора взаимодействующих классов. В данном случае определен один класс Program.

При определении класса вначале идет модификатор доступа public , который указывает, что данный класс будет доступен всем, то есть мы сможем его запустить из командной строки. Далее идет ключевое слово class , а затем название класса. То есть класс называется Program. После названия в фигурных скобках расположено содержимое класса.

Класс может содержать различные переменные и методы. В данном случае у нас объявлен один метод main . Это главный метод в любой программе на Java, он является входной точкой программы и с него начинается все управление. Он обязательно должен присутствовать в программе.

Метод main также имеет модификатор public . Слово static указывает, что метод main — статический, а слово void — что он не возвращает никакого значения. Позже мы подробнее разберем, что все это значит.

Далее в скобках у нас идут параметры метода — String args[] — это массив args, который хранит значения типа String , то есть строки. В данном случае ни нам пока не нужны, но в реальной программе это те строковые параметры, которые передаются при запуске программы из командной строки.

После списка параметров в фигурных скобках идет тело метода — это собственно те инструкции, которые и будет выполнять метод. В данном случае фактически определени определена только одна инструкция — вывод на консоль некоторой строки. Для вывода на консоль используется встроенный метод System.out.println() . В этот метод передается выводимая строка. Каждая инструкция завершается точкой с запятой.

Теперь скомпилируем написанную программу. Откроем командную строку (в Windows) или терминал в Linux/MacOS и введем там соответствующие команды. Первым делом перейдем в каталог, где лежит наш файл с программой с помощью команды:

В данном случае файл находится в каталоге C:\Java.

Первая программа на Java 16

Затем cкомпилируем программу с помощью команды

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

После этого программа компилируется в байт-код, и в каталоге C:\Java можно будет найти новый файл Program.class . Это и будет файл с байт-кодом программы. Теперь нам надо его запустить с помощью утилиты java:

Здесь уже расширение у файла не надо использовать.

Для ОС Windows весь процесс будет выглядеть следующим образом:

Первая программа на Java

Добавление java в переменную Path

Для компиляции приходится вводить полный путь к комилятору javac, что может быть сопряжено с ошибками при вводе, да и каждый раз вводить полный путь тоже неудобно. Чтобы в дальнейшем облегчить работу, добавим путь к JDK в переменную PATH в переменных среды. Если мы работаем в Windows, то для добавления переменной среды через поиск найдем найдем параметр Изменение системных переменных среды . Для этого введем в поле поиска «Изменение системных переменных среды»:

Переменные среды в Windows

Выберем пункт Изменение системных переменных среды . И сначала нам откроется окно «Свойства системы», где нажмем на кнопку Переменные среды :

Системные переменные среды в Windows

Затем нам откроется окно, где мы можем увидеть все переменные среды. (Также можно перейти через Параметры и пункт Система ->Дополнительные параметры системы ->Переменные среды )

Здесь нам нужно исправить системную переменную Path . Для этого выделим ее и нажмем на кнопку «Изменить»:

Установка системной переменной пути к JDK в Windows

В эту переменную Path нам надо добавить путь к инструментам JDK. И тут есть два момента. Во-первых, при установке jdk по умолчанию ряд утилит также устанавливаются в папку C:\Program Files\Common Files\Oracle\Java\javapath . В том числе это такие файлы как java.exe и javac.exe. И путь к этой папке по умолчанию добавляется в перемнную Path. То есть мы можем использовать этот путь.

Второй момент — в последних сборках Windows компания Microsoft также устанавливает свои сборки JDK, точнее OpenJDK, которые также по умолчанию добавляются в переменную Path и которые мы также можем использовать. Но у этих сборок есть большой минус — они применяют одну из прошлых версий JDK (обычно это LTS-сборки). Например, в моем случае это 11-я версия, хотя текущей является 19-я.

Чтобы использовать последнюю 19-ю версию среди путей в переменной Path убедимся, что путь C:\Program Files\Common Files\Oracle\Java\javapath располагается выше путей к сборкам JDK от Microsoft. Для перемещения определенного пути вверх среди переменных среды можно использовать кнопку «Вверх:

Установка системной переменной пути к JDK в Windows и сборки OpenJDK от Microsoft

Также можно напрямую создать использовать путь «C:\Program Files\Java\jdk-19\bin».

Установка системной переменной пути к JDK в Windows и сборки OpenJDK от Microsoft

Для создания новой переменной надо нажать на кнопку «Создать» и ввести в новое поле путь «C:\Program Files\Java\jdk-19\bin». Но опять же его следуется с помощью кнопки Вверх поместить над путями к OpenJDK от Microsoft.

После установки переменной Path перейдем к командной строке/терминалу (в более старых версиях Windows может потребоваться перезауск командной строки) и для проверки версии введем команду

Консоль нам должна в ответ ввести номер только что установленной версии JDK:

#8. Компиляция и выполнение java программы с командной строки

Продолжаем курс программирования java для android-разработчиков. Данный урок научит вас запускать java программы из командной строки, для общего понимания процесса компиляции и запуска программ на языке java.

После создания простого приложения, которое выводит что-то на экран, вы должны компилировать ваш код и запустить его.

Независимо от того, какую операционную систему вы используете, Linux, Mac или Windows, если на вашем компьютере установлен JDK (Java Development Kit), вы можете в консоли набрать следующие команды чтобы скомпилировать и запустить программу:

  • javac (или javac.exe)
  • java (или java.exe)

В первом случае будет вызван компилятор javac.exe, а во втором случае – запускалка java.exe, которая стартует нашу программу. Эти файлы лежат в папке bin вашего JDK.

Рассмотрим на примере. Вспомним код из первого урока – создадим файл с названием Main.java.

Идем в папку, куда среда разработки сохранила проект. Я работаю в IntelliJIDEA, и мой проект лежит в C:\Users\имя пользователя\IdeaProjects\название проекта\src. Находим там наш файл Main.java. Консоль вызывается так: щелкаем правой клавишей мыши с зажатой клавишей Shift на пустом месте в папке, где лежит файл нашей программы, и выбираем пункт контекстного меню “Открыть окно команд”.
Для того, чтобы скомпилировать его нужно набрать в консоли команду javac и в качестве параметра передать имя нашего файла:

Эта команда вызовет компилятор, который создаст файл Main.class, содержащий скомпилированный код нашей java программы.

Чтобы запустить ее, нужно ввести команду java с именем класса (не файла!) в качестве параметра:

Аргументы

В главном классе нашей программы есть метод public static void main(. ) , который в качестве аргумента принимает массив String[] args.

Массив строк в качестве аргумента можно передать в программу при запуске из командной строки .

Любой массив в Java имеет переменную длину, это число элементов в этом массиве.

Добавим такой код в класс Main.java:

И чтобы скомпилировать и запустить программу с аргументами, пишем в консоль:

Упражнение

Создайте программу, которая выводит аргументы, переданные при запуске, в одну строку.

Создание, компиляция и выполнения Java программ

Перед тем как программа может быть выполнена, её необходимо создать и скомпилировать. Если в вашей программе возникли ошибки компиляции, вам необходимо изменить программу, чтобы исправить их, а затем перекомпилировать её. Если в вашей программе возникли ошибки выполнения, или она не приводит к правильному результату, вам необходимо изменить программу, перекомпилировать её и запустить снова. Этот процесс и является созданием (разработкой) программы.

Для создания и редактирования исходного кода Java вы можете использовать любой текстовый редактор или IDE. Этот раздел демонстрирует, как создавать, компилировать и запускать программы Java из командной строки. В разделе «Компиляция и запуск Java программ в NetBeans» показано, как это делать в IDE на примере NetBeans.

Можно вообще обойтись без IDE, а писать исходный код в любом текстовом редакторе (например, в Notepad), а компилировать в командной строке.

Внимание: файл с исходным кодом должен иметь расширение .java и иметь в точности такое же имя, как и имя публичного (public) класса. Например, файл с исходным кодом:

должен называться Welcome.java, поскольку имя public класса – Welcome.

Компилятор Java преобразовывает файл с исходным кодом Java в файл с байткодом Java. Следующая команда компилирует Welcome.java:

Если нет синтаксических ошибок, компилятор генерирует файл байкода с расширением .class. Следовательно, приведённая выше команда генерирует файл с названием Welcome.class.

Чтобы иметь возможность компилировать и запускать программы, вы должны установить JDK. Как это сделать описано в инструкциях:

  • Установка Java (JDK) в Windows
  • Установка Java (JDK) в Linux

Язык Java – это высокоуровневый язык программирования, но байткод Java – это низкоуровневый язык. Байткод похож на машинные инструкции, но нейтрален к архитектуре (не зависит от архитектуры) и может запускаться на любой платформе, которая имеет виртуальную машину Java – Java Virtual Machine (JVM). В отличие от физической машины, виртуальная машина – это программа, которая интерпретирует байткод Java. Это одно из главных преимуществ Java: байткод Java может работать на различных аппаратных платформах и операционных системах. Исходный код Java компилируется в байткод Java, а байткод Java интерпретируется виртуальной машиной Java. Ваш код Java может использовать код библиотеки Java. JVM выполняет ваш код вместе с кодом из библиотеки.

Выполнить Java программу – это значит запустить байткод программы. Вы можете выполнить байткод на любой платформе с JVM, которая является интерпретатором. Она (виртуальная машина Java) переводит отдельные инструкции байткода в целевой машинный языковой код. Это делается последовательно – одна инструкция за раз, а не вся программ за один присест. Каждый шаг немедленно выполняется, сразу после перевода.

Следующая команда выполняет байткод для программы, которая приведена выше:

На скриншоте ниже показан процесс компиляции и запуска:

Внимание: не используйте расширение .class в команде, когда запускаете программу. Используйте ИмяКласса для запуска программы. Если вы в командной строке используете ИмяКласса.class, то система будет пытаться работать с файлом ИмяКласса.class.class.

Справка: когда выполняется Java программа, JVM начинает с загрузки байткода класса в память, используя программу под названием загрузчик классов (class loader). Если ваша программа использует другие классы, загрузчик классов динамически подгружает их перед тем, как они понадобятся. После загрузки класса, JVM использует программу под названием контролёр байткода (bytecode verifier) для проверки правильности байткода и проверки, что байткод не нарушает ограничений безопасности Java. Java обеспечивает строгую защиту, чтобы убедиться, что файлы классов Java не подделаны и не вредят вашему компьютеру.

Педагогическое примечание: ваш инструктор может требовать от вас использовать пакеты для организации программ. Например, все программы из этой части можно поместить в пакет chapter2. Подробности о пакетах и пространствах имён будут рассмотрены далее. Также посмотрите раздел «Почему NetBeans всегда использует package».

Типичные ошибки компиляции и запуска Java программ

Команда javac не найдена

Если при запуске javac, т.е. при попытке компиляции Java программы вы получаете ошибку:

Это означает, что JDK не установлен. Либо установлен, но не настроены переменные окружения. Способы исправления очевидны:

  • установить JDK
  • настроить переменные окружения

Если JDK установлен, то можно обойтись без добавления переменной окружения. Для этого используйте абсолютный путь до исполнимого файла javac:

Ошибка Class names are only accepted if annotation processing is explicitly requested

Если попытаться скомпилировать программу следующим образом:

то возникнет ошибка:

Причина ошибки в том – что вы забыли указать расширение файла .java.

Ошибка записи (error while writing)

Компиляция заканчивается ошибкой:

Причина ошибки в том, что у компилятора (javac) недостаточно прав на запись в тот каталог, куда он пытается сохранить новый файл .class. Чтобы ошибка исчезла: предоставьте компилятору дополнительные права (запустите от имени администратора), либо сохраняйте в папку, на которую у текущего пользователя имеются права записи.

Ошибка «class is public, should be declared in a file named»

который заканчивается примерной такой ошибкой

означает, что вы неправильно назвали класс в исходном коде программы. Имя класса должно совпадать с именем файла. В данном случае файл называется Welcome.java, а класс внутри программы назван Welcomee

Error: Could not find or load main class

Если попытаться запустить программу следующим образом:

то возникнет ошибка

Причина её в том, что не нужно было добавлять к названию файла расширение .class. Виртуальная машина автоматически добавляет расширение и в приведённом примере она ищет файл Welcome.class.class

Ошибка Error: Could not find or load main class при запуске Java программы по абсолютному пути

Эта ошибка возможно при запуске Java программы по абсолютному пути:

Ошибка возникает как в Windows, так и в Linux:

Если в терминале вы находитесь в той же директории, что и файл, который вы запускаете, то не нужно указывать абсолютный путь. Например, нужно запускать так:

Если же вы находитесь в другой директории, то нужно использовать опцию -cp, после которой указать путь до каталога, где размещена запускаемая программа. А далее указать запускаемый файл без расширения .class:

Как видно из скриншота, командная строка находится в папке C:\WINDOWS\system32. Файл, который нам нужно запустить, находится в папке C:\ (корень диска). Мы указываем после ключа -cp папку C:\, а затем пишем имя файла программы без расширения – Welcome.

Аналогично нужно поступать в Linux. Пример команды:

Ошибка Main method not found in class

Если при запуске вы столкнулись с ошибкой:

Это означает, что вы не указали метод main, либо написали слово неправильно (например, Main вместо main).

Особенности компиляции и запуска Java программ в Windows

Команда "javac" не является внутренней или внешней командой, исполняемой программой или пакетным файлом

Эта ошибка рассмотрена чуть выше. Для установки и настройки переменных окружения в Windows обратитесь к инструкции «Установка Java (JDK) в Windows».

Проблема с кодировкой в Java программах в командной строке Windows

Если вы написали программу, которая выводит кириллицу в консоль:

А в качестве результата получили крякозяблы:

Значит кодировка, в которой выводит строки ваша программа, отличается от кодировки командной строки Windows.

Имеется несколько способов исправить эту проблему. Кстати, если для запуска консольных программ Java вы используете NetBeans, то он выводит строки в правильной кодировке. В Linux эта проблема также отсутствует. Если вам нужно поменять кодировку на время, то вы можете выполнить следующие команды:

Для того, чтобы смена кодировки командной строки Windows не сбрасывалась после закрытия и открытия командной строки, можно внести изменения в реестр Windows. Для этого нажмите Win+x, выберите «Выполнить», в открывшееся окно введите regedit. В открывшейся программе (редактор реестра Windows) перейдите к [HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\Autorun] и измените (или добавьте) значение на @chcp 65001>nul

Похожие статьи