Что такое компиляция в java
Перейти к содержимому

Что такое компиляция в java

  • автор:


In Java, programs are not compiled into executable files; they are compiled into bytecode (as discussed earlier), which the JVM (Java Virtual Machine) then executes at runtime. Java source code is compiled into bytecode when we use the javac compiler. The bytecode gets saved on the disk with the file extension .class . When the program is to be run, the bytecode is converted, using the just-in-time (JIT) compiler. The result is machine code which is then fed to the memory and is executed.

Java code needs to be compiled twice in order to be executed:

  1. Java programs need to be compiled to bytecode.
  2. When the bytecode is run, it needs to be converted to machine code.

The Java classes/bytecode are compiled to machine code and loaded into memory by the JVM when needed the first time. This is different from other languages like C/C++ where programs are to be compiled to machine code and linked to create an executable file before it can be executed.

Quick compilation procedure [ edit | edit source ]

To execute your first Java program, follow the instructions below:

If you obtain another message ending by 1 error or . errors , there may be a mistake in your code. Are you sure all words are spelled correctly and with the exact case as shown? Are there semicolons and brackets in the appropriate spot? Are you missing a quote? Usually, modern IDEs would try coloring the entire source as a quote in this case.

If your computer emits beeps, then you may have illegal characters in your HelloWorld.java .

If no HelloWorld.class file has been created in the same folder, then you’ve got an error. Are you launching the javac program correctly?

If you obtain an error message like Exception in thread «main» java.lang.NoSuchMethodError: main , your source file may have been badly written.

Automatic Compilation of Dependent Classes [ edit | edit source ]

In Java, if you have used any reference to any other java object, then the class for that object will be automatically compiled, if that was not compiled already. These automatic compilations are nested, and this continues until all classes are compiled that are needed to run the program. So it is usually enough to compile only the high level class, since all the dependent classes will be automatically compiled.

Main class compilation

However, you can’t rely on this feature if your program is using reflection to create objects, or you are compiling for servlets or for a «jar», package. In these cases you should list these classes for explicit compilation.

Main class compilation

Packages, Subdirectories, and Resources [ edit | edit source ]

Each Java top level class belongs to a package (covered in the chapter about Packages). This may be declared in a package statement at the beginning of the file; if that is missing, the class belongs to the unnamed package.

For compilation, the file must be in the right directory structure. A file containing a class in the unnamed package must be in the current/root directory; if the class belongs to a package, it must be in a directory with the same name as the package.

The convention is that package names and directory names corresponding to the package consist of only lower case letters.

Top level package [ edit | edit source ]

A class with this package declaration

has to be in a directory named example .

Subpackages [ edit | edit source ]

A class with this package declaration

has to be in a directory named en which has to be a sub-directory of wikibooks which in turn has to be a sub-directory of org resulting in org/wikibooks/en on Linux or org\wikibooks\en on Windows.

Java programs often contain non-code files such as images and properties files. These are referred to generally as resources and stored in directories local to the classes in which they’re used. For example, if the class com.example.ExampleApp uses the icon.png file, this file could be stored as /com/example/resources/icon.png . These resources present a problem when a program is compiled, because javac does not copy them to wherever the .class files are being compiled to (see above); it is up to the programmer to move the resource files and directories.

Filename Case [ edit | edit source ]

The Java source file name must be the same as the public class name that the file contains. There can be only one public class defined per file. The Java class name is case sensitive, as is the source file name.

The naming convention for the class name is for it to start with a capital letter.

Compiler Options [ edit | edit source ]

Debugging and Symbolic Information [ edit | edit source ]

To do:
Complete this section.

To debug into Java system classes such as String and ArrayList, you need a special version of the JRE which is compiled with «debug information». The JRE included inside the JDK provides this info, but the regular JRE does not. Regular JRE does not include this info to ensure better performance.

Symbolic Information : Symbolic resolution is done at class loading time at linking resolution step. It is the process of replacing symbolic references from the type with direct references. It is done by searching into method area to locate the referenced entity

The JIT compiler [ edit | edit source ]

The Just-In-Time (JIT) compiler is the compiler that converts the byte-code to machine code. It compiles byte-code once and the compiled machine code is re-used again and again, to speed up execution. Early Java compilers compiled the byte-code to machine code each time it was used, but more modern compilers cache this machine code for reuse on the machine. Even then, java’s JIT compiling was still faster than an «interpreter-language», where code is compiled from high level language, instead of from byte-code each time it was used.

The standard JIT compiler runs on demand. When a method is called repeatedly, the JIT compiler analyzes the bytecode and produces highly efficient machine code, which runs very fast. The JIT compiler is smart enough to recognize when the code has already been compiled, so as the application runs, compilation happens only as needed. As Java applications run, they tend to become faster and faster, because the JIT can perform runtime profiling and optimization to the code to meet the execution environment. Methods or code blocks which do not run often receive less optimization; those which run often (so called hotspots) receive more profiling and optimization.

Essentials, Part 1, Lesson 1: Compiling Running a Simple Program

The computer age is here to stay. Households and businesses all over the world use computers in one way or another because computers help individuals and businesses perform a wide range of tasks with speed, accuracy, and efficiency. Computers can perform all kinds of tasks ranging from running an animated 3D graphics application with background sound to calculating the number of vacation days you have coming to handling the payroll for a Fortune 500 company.

When you want a computer to perform tasks, you write a program. A program is a sequence of instructions that define tasks for the computer to execute. This lesson explains how to write, compile, and run a simple program written in the Java language (Java program) that tells your computer to print a one-line string of text on the console.

But before you can write and compile programs, you need to understand what the Java platform is, and set your computer up to run the programs.

A Word About the Java Platform

The Java platform consists of the Java application programming interfaces (APIs) and the Java 1 virtual machine (JVM).

Java APIs are libraries of compiled code that you can use in your programs. They let you add ready-made and customizable functionality to save you programming time.

The simple program in this lesson uses a Java API to print a line of text to the console. The console printing capability is provided in the API ready for you to use; you supply the text to be printed.

Java programs are run (or interpreted) by another program called the Java VM. If you are familiar with Visual Basic or another interpreted language, this concept is probably familiar to you. Rather than running directly on the native operating system, the program is interpreted by the Java VM for the native operating system. This means that any computer system with the Java VM installed can run Java programs regardless of the computer system on which the applications were originally developed.

For example, a Java program developed on a Personal Computer (PC) with the Windows NT operating system should run equally well without modification on a Sun Ultra workstation with the Solaris operating system, and vice versa.

Setting Up Your Computer

Before you can write and run the simple Java program in this lesson, you need to install the Java platform on your computer system.

The Java platform is available free of charge from the Java web site. You can choose between the Java® 2 Platform software for Windows 95/98/NT or for Solaris. The download page contains the information you need to install and configure the Java platform for writing and running Java programs.

Note: Make sure you have the Java platform installed and configured for your system before you try to write and run the simple program presented next.

Writing a Program

The easiest way to write a simple program is with a text editor. So, using the text editor of your choice, create a text file with the following text, and be sure to name the text file ExampleProgram.java . Java programs are case sensitive, so if you type the code in yourself, pay particular attention to the capitalization.

Here is the ExampleProgram.java source code file if you do not want to type the program text in yourself.

Compiling the Program

A program has to be converted to a form the Java VM can understand so any computer with a Java VM can interpret and run the program. Compiling a Java program means taking the programmer-readable text in your program file (also called source code) and converting it to bytecodes, which are platform-independent instructions for the Java VM.

The Java compiler is invoked at the command line on Unix and DOS shell operating systems as follows:

Note: Part of the configuration process for setting up the Java platform is setting the class path. The class path can be set using either the -classpath option with the javac compiler command and java interpreter command, or by setting the CLASSPATH environment variable. You need to set the class path to point to the directory where the ExampleProgram class is so the compiler and interpreter commands can find it.

Interpreting and Running the Program

Once your program successfully compiles into Java bytecodes, you can interpret and run applications on any Java VM, or interpret and run applets in any Web browser with a Java VM built in such as Netscape or Internet Explorer. Interpreting and running a Java program means invoking the Java VM byte code interpreter, which converts the Java byte codes to platform-dependent machine codes so your computer can understand and run the program.

The Java interpreter is invoked at the command line on Unix and DOS shell operating systems as follows:

At the command line, you should see:

I’m a Simple Program

Here is how the entire sequence looks in a terminal window:

Common Compiler and Interpreter Problems

If you have trouble compiling or running the simple example in this lesson, refer to the Common Compiler and Interpreter Problems lesson in The Java Tutorial for troubleshooting help.

Code Comments

Code comments are placed in source files to describe what is happening in the code to someone who might be reading the file, to comment-out lines of code to isolate the source of a problem for debugging purposes, or to generate API documentation. To these ends, the Java language supports three kinds of comments: double slashes, C-style, and doc comments.

Double Slashes

Double slashes ( // ) are used in the C++ programming language, and tell the compiler to treat everything from the slashes to the end of the line as text.

C-Style Comments

Instead of double slashes, you can use C-style comments ( /* */ ) to enclose one or more lines of code to be treated as text.

Doc Comments

To generate documentation for your program, use the doc comments ( /** */ ) to enclose lines of text for the javadoc tool to find. The javadoc tool locates the doc comments embedded in source files and uses those comments to generate API documentation.

HTML javadoc Home Page javadoc API Documentation

The Java platform installation includes API Documentation, which describes the APIs available for you to use in your programs. The files are stored in a doc directory beneath the directory where you installed the platform. For example, if the platform is installed in /usr/local/java/jdk1.2 , the API Documentation is in /usr/local/java/jdk1.2/doc/api . More Information

See Common Compiler and Interpreter Problems lesson in The Java Tutorial for troubleshooting help.

The javadoc Home Page has more information on the javadoc command and its output.

1 As used on this web site, the terms «Java virtual machine» or «JVM» mean a virtual machine for the Java platform.

Java Compiling and Running Process

amirreza lotfi

Hello to Readers !! If you are a Java Developer, you may not have noticed that how Java code compile and run, or you may not have a good understanding of the overall process because of its complexity. In this article, for better understanding, I will ignore some complexities of JDK processes and I will explain Java compiling and running process in the simple words, and also I will say about :

◼ Difference between JDK, JVM, JRE, JIT
◼ Explanation about “.class” file
◼ Description of ClassLoader and Bytecode Verified

Before we deep dive in compiling processes, we have to know about JDK:

What Is JDK?

JDK, or Java Development Kit, consist of tools that we use them to develop and run Java applications. Before develop and run Java code, you should install it in your computer or system. The below picture, represent structure of JDK:

As you see, JDK has consists of JRE and Java development tools like An interpreter/loader, compiler, debugger, An archiver (jar) and other development tools.

What is JRE ?

JRE or Java Runtime Environment is a package that provides an environment to only run (not develop) the Java program (or application) on your machine. It is only used to run Java programs.

The most important part of JRE is Java Virtual Machine.

What is JVM or Java Virtual Machine?

JVM (Java Virtual Machine) acts as a run-time engine to run Java applications. Its responsibility is execution code line-by-line. It's also knowing as Interpreter. In the following, we will get more acquainted with it.

How JDK Compile and Run Java code?

At first, Java compiler (Javac, that is in Development tools), convert Java files (with .java extension) to an executable file. This executable file cannot be directly ran in the operating system. In fact, this file is an intermediate file. This file is called Bytecode and its extension is .class.

The Bytecode has supported in all operating systems (like Mac, Windows, and Linux). Thats why java programs called WORA (write once, run anywhere)

To run this Bytecode file, we need JVM. So, Java Compiler pass Bytecode files to JVM. JVM in each OS is different and to running Java, We require an JVM compatible with the operating system.
Then, In JVM, three stage performed:

◼ Class Loader
◼ Bytecode Verified
◼ Java-In-Time Compiler

ClassLoader in Java is a class that is used to load class files in Java. It is an object that accept Bytecode (files with .class extensions) and uploads java classes (don't confuse!! Here, classes means object-oriented classes) in Heap Area. Heap Area is part of JVM memory and information of all objects is stored in it. There is also one Heap Area per JVM. It is also a shared resource.

Class Loader run 3 process:

1- Loading
2- Linking
3- Initializing

In the Loading, Bytecodes saves in Method Area and loading classes to memory happened. Method Area is part of JVM memory and all class level information like class name, immediate parent class name, methods, and variables information are stored. There is only one Method Area in JVM and it is a shared resource.

In the Linking process, the classes and interfaces combined into runtime state of JVM, so it can be executable.

In the Initialization process, Linking classes in previous section execute.

To say better about the process of class loader, at first it looks for class object in Heap Memory. If it is available, it returns it. But if it does not find in Heap, it looks for .class file. In the other hand, if .class file not founded, it returns an Exception, otherwise it creates class object in Heap Memory.

Then, class loader is checked by Bytecode Verified. In this process, problem and dangers of class loader is checked. For example, if in the program, we use a variable that has not been declared, or if the run time stack overflows, it will throw an Exception and the compiling process will stop.

Final Execution Step

If our Code doesn't have any issue, the Execution Engine in JVM reads bytecode line by line, uses data and information stored in different memories and executes instructions. Execution Engine can be classified into three parts:

Interpreter: It interprets the bytecode line by line and then executes
Just-In-Time Compiler: It compiles the entire bytecode and changes it to machine code.
Garbage Collector: It destroys unreferenced objects.

The compile process is done!!

Machine code is a low-level programming language, consisting of machine language instructions, used to control a computer’s central processing unit (CPU). Each instruction causes the CPU to perform a very specific task, such as a load, a store, a jump, or an arithmetic logic unit (ALU) operation on one or more units of data in the CPU’s registers or memory.

Node : As I say at the beginning of the article, These steps do not go through all the JDK steps to run the program. To better understand, we ignored some steps. Compiling Java code is more complicated than that. This article gives you a brief overview about compiling process in JDK. To read more, read the mentioned sources.

Кроссплатформенность Java

Данный урок посвящен кроссплатформенности Java — чем и как она обеспечивается. Перед прочтением статьи рекомендуется базово знать о JDK, JRE и JVM.

Перед началом важно дать определения следующим терминам:

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

Компилятор и интерпретатор — это разновидности транслятора. Виртуальная машина — это разновидность интерпретатора.

Компилятор либо преобразует код программы в машинный код, либо переводит код программы в промежуточное представление (например, байт-код).

Интерпретатор построчно переводит код программы в машинный код, который сразу же выполняется процессором.

Виртуальная машина — это интерпретатор, который построчно переводит промежуточное представление программы (например, байт-код) в машинный код.

Пошаговое выполнение Java-программы

Компиляция: Исходный код Java-программы компилируется с помощью Java-компилятора (javac) в байт-код, который представляет собой промежуточное представление программы. Результатом компиляции являются бинарные файлы классов формата .class, которые содержат в себе байт-код в бинарном представлении (состоят из последовательностей 0 и 1 ).

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

Кроссплатформенность Java

В основе кроссплатформенности Java лежит JVM, которая выполняет байт-код Java-приложения на любой платформе, на которой установлена. Однажды скомпилированная в байт-код Java-программа может распространяться и выполняться на любых аппаратных платформах и ОС благодаря JVM. Именно поэтому Java считается кроссплатформенной (платформенно-независимой).

Много программ пишется на высокоуровневых языках программирования, которые могут прочитать и понять программисты. Но программы в таком виде совсем непонятны процессору, который понимает только машинные инструкции. Эту проблему решают компиляторы, которые принимают на вход исходный код приложения на высокоуровневом языке, а возвращают машинный код, который напрямую выполняется процессором.

Для компилируемых языков программирования (таких как С/C++, Go, Rust, Swift) компиляторы превращают высокоуровневый код программы в машинный код, который затем может быть выполнен процессором (он же «ЦПУ», «CPU»).

Однако интерпретируемые языки программирования (такие как Python, JavaScript, R, Ruby, Perl, PHP) выполняются интерпретатором. Простой интерпретатор читает исходный код программы построчно и на ходу переводит его в машинные инструкции, которые затем немедленно выполняются ЦПУ. Некоторые интерпретируемые языки программирования для повышения производительности используют промежуточный формат, называемый байт-кодом. Например, в Python процессы компиляции в байт-код и интерпретации выполняются последовательно самим интерпретатором языка. Интерпретатор языка Python содержит в себе и PVM (сокр. от англ. «Python Virtual Machine», Виртуальная Машина Python), и компилятор в байт-код такие интерпретаторы называются интерпретаторами компилирующего типа.

Стоит отметить, что термины «компилируемый» и «интерпретируемый» не являются взаимоисключающими. Яркими примерами языков программирования, которые используют раздельные этапы компиляции в байт-код и интерпретации являются Java и C#. Однако байт-код Java выполняется JVM с задействованием JIT-компилятора и интерпретатора, в то время как С# для интерпретации использует только JIT-компилятор, который компилирует байт-код C# при запуске программы по мере необходимости.

У каждого языка программирования есть своя собственная специфика выполнения, инфраструктура, особенности и средства оптимизации.

Почему JVM платформенно-зависимая?

JVM — это именно виртуальная машина, фактически это такое же ПО, как и компилятор. Чтобы выполняться на какой-то операционной системе — ПО должно быть скомпилировано под эту операционную систему. Например, если скомпилировать программу на С++ (которая не использует какие-либо зависимости) на Windows в .exe-файл, этот файл нельзя будет запустить на macOS или Linux-based системе на этом же компьютере. Дело в том, что исполняемые файлы не являются просто «сырым» машинным кодом, а содержат дополнительную информацию, связанную с ОС и другими системными компонентами. Поэтому, хотя, фактический машинный код будет одинаковым для всех ОС, работающих на одном компьютере (машинный код зависит только от архитектуры аппаратной части компьютера), каждая ОС будет привносить свой специфичный характер с помощью системных вызовов и различий в формате исполняемых файлов. ОС — это главная прослойка между физической аппаратной частью компьютера (железом) и программами. Все программы должны «общаться» с аппаратной частью компьютера через ОС. Отсюда и появляется зависимость от операционной системы, помимо зависимости от архитектуры процессора.

Поэтому JVM, как и любое программное обеспечение, должна быть специализирована для каждой ОС. При этом JVM, независимо от того, на какой ОС она установлена, всегда предоставляет одинаковый интерфейс для байт-кода, который она выполняет. Байт-код зависит только от виртуальной машины, которая его выполняет, а специфика работы этого байт-кода на какой-либо ОС лежит на виртуальной машине.

Так и получается, что JVM — платформенно-зависимая, а байт-код Java — JVM-зависимый. Но в связи с тем, что все реализации одной версии JVM предоставляют одинаковый интерфейс для байт-кода, байт-код называют кроссплатформенным (платформенно-независимым).

Следовательно, можно говорить о JVM, как о своеобразном переходнике к операционной системе для байт-кода Java.

Ключевые моменты

Кроссплатформенность Java: Благодаря JVM, байт-код Java-программы может выполняться на любой платформе, на которой установлена JVM. Это делает Java кроссплатформенным языком программирования.

Независимые этапы компиляции и интерпретации: В Java разделены процессы компиляции и интерпретации, что дает возможность распространять Java-приложения сразу в виде скомпилированного байт-кода.

Платформенная зависимость JVM: JVM является платформенно-зависимой, так как должна быть специализирована для каждой операционной системы. Однако байт-код Java остается платформенно-независимым благодаря единому интерфейсу, предоставляемому JVM.

JVM как переходник к операционной системе: JVM выполняет роль «переходника» между байт-кодом Java и операционной системой, обеспечивая интерфейс для выполнения байт-кода на разных платформах.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *