Jdk что это за программа
Перейти к содержимому

Jdk что это за программа

  • автор:

 

Java Platform Standard Edition 6 Development Kit Readme

Thank you for downloading this release of the Java Platform, Standard Edition Development Kit (JDK ). The JDK is a development environment for building applications, applets, and components using the Java programming language.

The JDK includes tools useful for developing and testing programs written in the Java programming language and running on the Java platform.

System Requirements & Installation

System requirements, installation instructions and troubleshooting tips are located on the Java Software web site at:

JDK Documentation

The on-line Java Platform, Standard Edition (Java SE) Documentation contains API specifications, feature descriptions, developer guides, reference pages for JDK tools and utilities, demos, and links to related information. This documentation is also available in a download bundle which you can install on your machine. To obtain the documentation bundle, see the download page. For API documentation, refer to the The Java Platform, Standard Edition API Specification This provides brief descriptions of the API with an emphasis on specifications, not on code examples.

Release Notes

See the Java SE 6 Release Notes on the Java Software web site for additional information pertaining to this release. Please check the on-line release notes occasionally for the latest information as they will be updated as needed.

Compatibility

See Compatibility with Previous Releases on the Java Software web site for the list of known compatibility issues. Every effort has been made to support programs written for previous versions of the Java platform. Although some incompatible changes were necessary, most software should migrate to the current version with no reprogramming. Any failure to do so is considered a bug, except for a small number of cases where compatibility was deliberately broken, as described on our compatibility web page. Some compatibility-breaking changes were required to close potential security holes or to fix implementation or design bugs.

Bug Reports and Feedback

The Bug Database web site lets you search for and examine existing bug reports, submit your own bug reports, and tell us which bug fixes matter most to you. To directly submit a bug or request a feature, fill out this form:

Note — Please do not seek technical support through the Bug Database or our development teams.

Contents of the JDK

This section contains a general summary of the files and directories in the JDK . For details on the files and directories, see the JDK File Structure section of the Java SE documentation for your platform.

Development Tools

(In the bin/ subdirectory) Tools and utilities that will help you develop, execute, debug, and document programs written in the Java programming language. For further information, see the tool documentation.

Runtime Environment

(In the jre/ subdirectory) An implementation of the Java Runtime Environment (JRE ) for use by the JDK. The JRE includes a Java Virtual Machine (JVM ), class libraries, and other files that support the execution of programs written in the Java programming language.

Additional Libraries

(In the lib/ subdirectory) Additional class libraries and support files required by the development tools.

Demo Applets and Applications

(In the demo/ subdirectory) Examples, with source code, of programming for the Java platform. These include examples that use Swing and other Java Foundation Classes, and the Java Platform Debugger Architecture.

Sample Code

(In the sample subdirectory) Samples, with source code, of programming for certain Java API’s.

C header Files

(In the include/ subdirectory) Header files that support native-code programming using the Java Native Interface, the JVM Tool Interface , and other functionality of the Java platform.

Source Code

(In src.zip ) Java programming language source files for all classes that make up the Java core API (that is, sources files for the java.*, javax.* and some org.* packages, but not for com.sun.* packages). This source code is provided for informational purposes only, to help developers learn and use the Java programming language. These files do not include platform-specific implementation code and cannot be used to rebuild the class libraries. To extract these file, use any common zip utility. Or, you may use the Jar utility in the JDK’s bin/ directory: jar xvf src.zip

The Java Runtime Environment (JRE )

The Java Runtime Environment (JRE ) is available as a separately downloadable product. See the download web site.

The JRE allows you to run applications written in the Java programming language. Like the JDK , it contains the Java Virtual Machine (JVM ), classes comprising the Java platform API, and supporting files. Unlike the JDK, it does not contain development tools such as compilers and debuggers.

You can freely redistribute the JRE with your application, according to the terms of the JRE license. Once you have developed your application using the JDK, you can ship it with the JRE so your end-users will have a Java platform on which to run your software.

Redistribution

NOTE — The license for this software does not allow the redistribution of beta and other pre-release versions.

Subject to the terms and conditions of the Software License Agreement and the obligations, restrictions, and exceptions set forth below, You may reproduce and distribute the Software (and also portions of Software identified below as Redistributable), provided that:

you distribute the Software complete and unmodified and only bundled as part of Your applets and applications («Programs»),

your Programs add significant and primary functionality to the Software,

your Programs are only intended to run on Java-enabled general purpose desktop computers and servers,

you distribute Software for the sole purpose of running your Programs,

you do not distribute additional software intended to replace any component(s) of the Software,

you do not remove or alter any proprietary legends or notices contained in or on the Software,

you only distribute the Software subject to a license agreement that protects Oracle’s interests consistent with the terms contained in this Agreement, and

you agree to defend and indemnify Oracle and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys’ fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software.

The term «vendors» used here refers to licensees, developers, and independent software vendors (ISVs) who license and distribute the Java Development Kit (JDK ) with their programs.

Vendors must follow the terms of the Java Development Kit Binary Code License agreement.

Required vs. Optional Files

The files that make up the Java Development Kit (JDK ) are divided into two categories: required and optional. Optional files may be excluded from redistributions of the JDK at the vendor’s discretion.

The following section contains a list of the files and directories that may optionally be omitted from redistributions of the JDK. All files not in these lists of optional files must be included in redistributions of the JDK.

Optional Files and Directories

The following files may be optionally excluded from redistributions. These files are located in the jdk1.6.0_<version> directory, where <version> is the update version number. Solaris and Linux filenames and separators are shown. Windows executables have the «.exe» suffix. Corresponding files with _g in the name can also be excluded. The corresponding man pages should be excluded for any excluded executables (with paths listed below beginning with bin/ , for the Solaris Operating System and Linux).

Character conversion classes

sunjce_provider.jar — the SunJCE provider for Java Cryptography APIs localedata.jar — contains many of the resources needed for non US English locales ldapsec.jar — contains security features supported by the LDAP service provider dnsns.jar — for the InetAddress wrapper of JNDI DNS provider

bin/rmid and jre/bin/rmid

Java RMI Activation System Daemon

bin/rmiregistry and jre/bin/rmiregistry

Java Remote Object Registry

bin/tnameserv and jre/bin/tnameserv

Java IDL Name Server

bin/keytool and jre/bin/keytool

Key and Certificate Management Tool

bin/kinit and jre/bin/kinit

Used to obtain and cache Kerberos ticket-granting tickets

bin/klist and jre/bin/klist

Kerberos display entries in credentials cache and keytab

bin/ktab and jre/bin/ktab

Kerberos key table manager

bin/policytool and jre/bin/policytool

Policy File Creation and Management Tool

bin/orbd and jre/bin/orbd

Object Request Broker Daemon

bin/servertool and jre/bin/servertool

Java IDL Server Tool

bin/javaws , jre/bin/javaws , jre/lib/javaws/ and jre/lib/javaws.jar

Java DB, Oracle’s distribution of the Apache Derby database (only with file based distributions of the JDK).

Demo Applets and Applications

Archive of source files

Redistributable JDK Files

The limited set of files and directories from the JDK listed below may be included in vendor redistributions of the Java Runtime Environment (JRE ). They cannot be redistributed separately, and must accompany an identically versioned JRE distribution. All paths are relative to the top-level directory of the JDK. The corresponding man pages should be included for any included executables (with paths listed below beginning with bin/ , for the Solaris Operating System and Linux).

Color profile. This file is required only if one wishes to convert between the PYCC color space and another color space.

All .ttf font files in the jre/lib/fonts/ directory.

Note that the LucidaSansRegular.ttf font is already contained in the JRE, so there is no need to bring that file over from the JDK.

This MIDI soundbank is present in the JDK, but it has been removed from the JRE in order to reduce the size of the JRE download bundle. However, a soundbank file is necessary for MIDI playback, and therefore the JDK’s soundbank.gm file may be included in redistributions of the JRE at the vendor’s discretion. Several versions of enhanced MIDI soundbanks are available from the Java. These alternative soundbanks may be included in redistributions of the JRE.

The javac bytecode compiler, consisting of the following files:

bin/javac [Solaris Operating System and Linux]
bin/sparcv9/javac [Solaris Operating System (SPARC(R) Platform Edition)]
bin/amd64/javac [Solaris Operating System (AMD)]
bin/javac.exe [Microsoft Windows]
lib/tools.jar [All platforms]

The Annotation Processing Tool, consisting of the following files:

lib/tools.jar [All platforms]
bin/apt [Solaris Operating System and Linux]
bin/sparcv9/apt [Solaris Operating System (SPARC(R) Platform Edition)]
bin/amd64/apt [Solaris Operating System (AMD)]
bin/apt.exe [Microsoft Windows]

The Jconsole application. NOTE: The Jconsole application requires the dynamic attach mechanism.

The dynamic attach mechanism consisting of the following files:

lib/tools.jar [All platforms]
jre/lib/sparc/libattach.so [Solaris Operating System (SPARC(R) Platform Edition) and Linux]
jre/lib/sparcv9/libattach.so [Solaris Operating System (SPARC(R) Platform Edition) and Linux]
jre/lib/i386/libattach.so [Solaris Operating System (x86) and Linux]
jre/lib/amd64/libattach.so [Solaris Operating System (AMD) and Linux]
jre\bin\attach.dll [Microsoft Windows]

The Java Platform Debugger Architecture implementation consisting of the files shown in the dynamic attach section above, and the following files:

lib/tools.jar [All platforms]
lib/sa-jdi.jar [All platforms]
jre/lib/sparc/libsaproc.so [Solaris Operating System (SPARC(R) Platform Edition) and Linux]
jre/lib/sparcv9/libsaproc.so [Solaris Operating System (SPARC(R) Platform Edition) and Linux]
jre/lib/i386/libsaproc.so [Solaris Operating System (x86) and Linux]
jre/lib/amd64/libsaproc.so [Solaris Operating System (AMD) and Linux]

On Microsoft Windows platforms, the JDK includes both the Java HotSpot Server VM and Java HotSpot Client VM. However, the JRE for Microsoft Windows platforms includes only the Java HotSpot Client VM. Those wishing to use the Java HotSpot Server VM with the JRE may copy the JDK’s jre\bin\server folder to a bin\server directory in the JRE. Software vendors may redistribute the Java HotSpot Server VM with their redistributions of the JRE.

Unlimited Strength Java Cryptography Extension

Due to import control restrictions for some countries, the Java Cryptography Extension (JCE) policy files shipped with the JDK and the JRE allow strong but limited cryptography to be used. These files are located at

An unlimited strength version of these files indicating no restrictions on cryptographic strengths is available on the JDK web site for those living in eligible countries. Those living in eligible countries may download the unlimited strength version and replace the strong cryptography jar files with the unlimited strength files.

The cacerts Certificates File

Root CA certificates may be added to or removed from the Java SE certificate file located at

For more information, see The cacerts Certificates File section in the keytool documentation.

Java Endorsed Standards Override Mechanism

From time to time it is necessary to update the Java platform in order to incorporate newer versions of standards that are created outside of the Java Community Process SM (JCP SM http://www.jcp.org/) ( Endorsed Standards), or in order to update the version of a technology included in the platform to correspond to a later standalone version of that technology ( Standalone Technologies).

The Endorsed Standards Override Mechanism provides a means whereby later versions of classes and interfaces that implement Endorsed Standards or Standalone Technologies may be incorporated into the Java Platform.

For more information on the Endorsed Standards Override Mechanism, including the list of platform packages that it may be used to override, see

Java DB
  • Solaris: /opt/SUNWjavadb
  • Linux: /opt/sun/javadb
  • Windows: C:\Program Files\Sun\JavaDB

For information on Java DB and Derby, including user and API documentation, the capabilities of Java DB and further resources, see the index.html file in the above directories.

Note that file based distributions of the JDK on Solaris and Linux include Java DB in the $/db directory.

Web Pages

For additional information, see the following web pages:

The Java Software web site, with the latest information on Java technology, product information, news, and features.

Установка JDK

До недавнего времени вы писали программы просто на сайте JavaRush. Это было просто, удобно и понятно. Но не думаете же вы, что будете делать так всегда? Настало время начать писать программы по-взрослому, прямо как настоящие программисты. Как-то же писались программы до создания JavaRush!

Чтобы написать программу на своем компьютере без JavaRush, вам нужно сделать две вещи:

  1. Установить Java JDK
  2. Установить Java IDE

Что же это за вещи-то такие?

Java JDK
Программа, написанная на языке Java, отличается от обычной программы на компьютере. Обычная программа содержит машинный код , который сразу может быть выполнен процессором компьютера и не требует никаких дополнительных телодвижений для запуска.

Программа, написанная на языке Java, не содержит машинного кода: вместо него она содержит специальный байт-код . Процессор не умеет выполнять байт-код , поэтому при выполнении Java-программы, сначала запускается специальная программа — JVM . А эта JVM уже понимает байт-код и знает, как его исполнять. Так вот, JVM входит в состав JDK .

Java IDE

Современные программы содержат миллионы строк кода. Было бы невозможно писать такие программы если бы для их написания использовался обычный текстовый редактор. Вместо этого используют мощные программные инструменты, которые значительно ускоряют и облегчают работу программистов.

Такие программы для создания программ принято называть IDE . IDE — это Integrated Development Environment — Интегрированная Среда Разработки.

Для написания Java-программ существуют 3 популярные IDE :

  1. IntelliJ IDEA
  2. Eclipse
  3. Net Beans

Почти все программисты отдают предпочтение IntelliJ IDEA . И когда вы с ней познакомитесь, поймете почему. Но сначала нужно разобраться с JVM и JDK .

2. Что такое JDK

JVM — это сокращенное название от Java Virtual Machine — Виртуальная Машина Java. Обычный процессор выполняет машинный код, а JVM выполняет байт-код . Поэтому JVM — это как бы виртуальный процессор/машина.

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

JVM вещь хорошая, но одну JVM никто не использует. Голый процессор тоже никому не нужен. Обычно вместе с JVM идет еще набор стандартных библиотек: коллекции там всякие, списки и другие классы. В стандартной библиотеке, кстати, несколько тысяч классов.

JVM совместно со стандартными Java-библиотеками образует JRE — Java Runtime Environment — Среду Выполнения Java.

JRE достаточно для запуска многих Java-программ, но не для программистов. Java-компилятор , например, в JRE не входит. И где же его взять?

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

JDK содержит JRE + инструменты для Java-разработчиков.

 

JRE содержит JVM + набор стандартных Java-библиотек.

JVM — это виртуальная машина Java .

3. Разновидности JDK

Прошло то время, когда раз в 3-5 лет выходила новая версия Java, и это было целым событием. Сейчас новая версия JDK выходит раз в полгода. Пример Google Chrome оказался заразительным 🙂 Кроме того, свои JDK выпускают разные компании.

Первой это сделала Microsoft в конце 90-х, чтобы задавить набирающую популярность Java-платформу, дарящую программам независимость от Windows. Правда, Microsoft проиграла суд и была вынуждена выпустить свои более независимые аналоги Java: платформу .NET и язык C#.

Да, да, платформа .NET — это аналог JRE, а первые версии языка C# были один в один похожи на язык Java. Хотя с тех пор много воды утекло.

В любом случае, сейчас есть несколько популярных JDK , из которых нам интересны две:

  • Oracle JDK — официальная JDK от компании-разработчика Java. Уже частично платная для компаний, но по-прежнему бесплатная для частного использования и разработчиков.
  • Open JDK — бесплатная JDK , тоже выпускается Oracle. Очень любимая разработчиками и компаниями, которые не хотят платить Oracle деньги.

Принципиальной разницы для разработчиков нет, поэтому можете смело использовать Open JDK.

4. Установка JDK

Вам нужно загрузить себе на компьютер Open JDK 13 или более позднюю версию. Для начала, зайди на сайт https://jdk.java.net/ и посмотри актуальную версию JDK.

current JDK

На момент написания этой лекции была версия 16, поэтому покажем на ее примере.

Нажми на текущую актуальную версию. В разделе Builds кликни на версию JDK для своей ОС, чтобы началась загрузка.

JDK download

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

Важно! В пути к JDK не должно быть символов кириллицы. Из-за кириллицы будут проблемы с запуском программ.

5. Видео по установке JDK

Мы сделали специальное видео, чтобы закрыть все возможные вопросы по этому процессу.

Если какие-то вопросы у вас все же остались, вы всегда можете задать их на нашем Форуме.

Jdk что это за программа


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегистатьи IT, java, Java App Dev, Средства разработки, jdk

  • JDK Temurin: https://adoptium.net/index.html
  • Средство сборки и запуска задач Gradle: https://gradle.org/
  • Среда разработки Kotlin-приложений IDEA Ultimate: https://www.jetbrains.com/idea/
  • IDEA Community: https://www.jetbrains.com/idea/
  • Eclipse IDE: https://www.eclipse.org/
  • Visual Studio Code: https://code.visualstudio.com/
  • GNU Emacs: https://www.gnu.org/software/emacs/
  • Vim: https://www.vim.org/

adoptium/temurin-build

These scripts can be used to build OpenJDK anywhere but are primarily used by Eclipse Adoptium members (vendors) to build binaries. The scripts default to the use case of building Eclipse Temurin binaries which occurs on the build farm at https://ci.adoptopenjdk.net. Those binaries are then made available for consumption at https://adoptium.net and via the API https://api.adoptium.net.

NOTE In the future, adoptium.net will transition to being a marketplace for other qualifying vendors as well Eclipse Temurin.

Where can I find the release status of Eclipse Temurin™ binaries?

TL;DR: I want to build a JDK NOW

Build jdk natively on your system

To do this you will need to have your machine set up with a suitable compiler and various other tools available. We set up our machines using ansible playbooks from the openjdk-infrastructure repository. You can also look at the dockerfile generator for a list of required packages for Ubuntu.

Once you’ve got all of the prerequisites installed, clone this openjdk-build repository ( git clone https://github.com/adoptium/temurin-build and kick off a build a follows with this script. The -J parameter specifies the «boot JDK» which should generally be one major version prior to the one you are building (although one of the same major version will also work). Note that the build variant defaults to HotSpot if omitted which builds from the same repositories as Temurin.

How do I build OpenJDK in a docker image?

If you do not want to set up your machine with all the prerequisites for building OpenJDK, you can use our docker images under the [docker] directory as follows (first version builds HotSpot, second builds J9 — the final parameter can be adjusted to build whichever version you want as long as we can generate valid dockerfile for it):

We test these dockerfiles on a regular basis in the Dockerfilecheck job to ensure they continue to work in a stable fashion.

This repository contains several useful scripts in order to build OpenJDK personally or at build farm scale.

  1. The build-farm folder contains shell scripts for multi configuration Jenkins build jobs used for building Adoptium OpenJDK binaries.
  2. The docker folder contains tools for generating dockerfiles which can be used as part of building OpenJDK inside a Docker container.
  3. The git-hg folder has now been moved to it’s own separate repository. See openjdk-mirror-scripts.
  4. The pipelines folder has now been moved to a separate repo: https://github.com/adoptium/ci-jenkins-pipelines.
  5. The sbin folder contains the scripts that actually build (Temurin). build.sh is the entry point which can be used stand alone but is typically called by the native-build.sh or docker-build.sh scripts (which themselves are typically called by makejdk-any-platform.sh ).
  6. The security folder contains a script and cacerts file that is bundled with the JDK and used when building OpenJDK: the cacerts file is an important file that’s used to enable SSL connections.

The makejdk-any-platform.sh script

makejdk-any-platform.sh is the entry point for building (Adoptium) OpenJDK binaries. Building natively or in a docker container are both supported. This script (and its supporting scripts) have defaults, but you can override these as needed. The scripts will auto detect the platform and architecture it is running on and configure the OpenJDK build accordingly. The supporting scripts will also download and locally install any required dependencies for the OpenJDK build, e.g. The ALSA sound and Freetype font libraries.

Many of the configuration options are passed through to the configure and make commands that OpenJDK uses to build binaries. Please see the appropriate README-builds.html file for the OpenJDK source repository that you are building.

NOTE: Usage can be found via makejdk-any-platform.sh —help . Here is the man page re-formatted for convenience.

Build Variant Workflow

The main script to build OpenJDK is makejdk-any-platform.sh , which itself uses and/or calls configureBuild.sh , docker-build.sh and/or native-build.sh .

The structure of a build is:

  1. Configuration phase determines what the configuration of the build is based on your current platform and and optional arguments provided
  2. Configuration is written out to config/built_config.cfg
  3. Build is kicked off by either creating a docker container or running the native build script
  4. Build reads in configuration from built_config.cfg
  5. Downloads source, dependencies and prepares build workspace
  6. Invoke OpenJDK build via make
  7. Package up built artifacts
  • Configuration phase is primarily performed by configureBuild.sh and makejdk-any-platform.sh.
  • If a docker container is required it is built by docker-build.sh otherwise native-build.sh.
  • In the build phase sbin/build.sh is invoked either natively or inside the docker container. sbin/build.sh invokes sbin/prepareWorkspace.sh to download dependencies, source and perform general preparation.
  • Rest of the build and packaging is then handled from sbin/build.sh

Building OpenJDK from other locations

Building OpenJDK from a non-Adoptium repository

These scripts default to using Adoptium as the OpenJDK source repository to build from, but you can override this with the -r flag. If you want to run from a non-default branch you can also specify -b e.g.

Building in a custom directory

This would clone OpenJDK source from https://github.com/adoptium/openjdk-jdk11u to $HOME/openjdk-jdk11u/src , configure the build with sensible defaults according to your local platform and then build OpenJDK and place the result in /home/openjdk/target/MyOpenJDK11.tar.gz .

Alongside the built assets a metadata file will be created with info about the build. This will be a JSON document of the form:

The Metadata class is contained in the Metadata.groovy file and the Json is constructed and written in the openjdk_build_pipeline.groovy file.

It is worth noting the additional tags on the SemVer is the build number.

Below are all of the keys contained in the metadata file and some example values that can be present.

  • vendor: Example values: [ Eclipse Adoptium , Alibaba ]

This tag is used to identify the vendor of the JDK being built, this value is set in the build.sh file and defaults to «Adoptium».

  • os: Example values: [ windows , mac , linux , aix , solaris ]

This tag identifies the operating system the JDK has been built on (and should be used on).

  • arch: Example values: [ aarch64 , ppc64 , s390x , x64 , x86-32 , arm ]

This tag identifies the architecture the JDK has been built on and it intended to run on.

  • variant: Example values: [ hotspot , openj9 , corretto , dragonwell , bisheng ]

This tag identifies the JVM being used by the JDK. «dragonwell» and «bisheng» itself are HotSpot based JVMs but are currently considered their own variants for the purposes of build. WARN: This will be changed at a later date when we split out JVM from vendor.

  • variant_version:

This tag is used to identify a version number of the variant being built, it currently is exclusively used by OpenJ9 and has the following keys:

major: Example values: [ 0 , 1 ]

minor: Example values: [ 22 , 23 , 24 ]

security: Example values: [ 0 , 1 ]

tags: Example values: [ m1 , m2 ]

  • version:

This tag contains the full version information of the JDK built, it uses the VersionInfo.groovy class and the ParseVersion.groovy class.

It contains the following keys:

minor: Example values: [ 0 ]

security: Example Values: [ 0 , 9 , 252 272 ]

pre: Example values: [ null ]

adopt_build_number: Example values: [ 0 ]
If the ADOPT_BUILD_NUMBER parameter is used to build te JDK that value will appear here, otherwise a default value of 0 appears.

major: Example values: [ 8 , 11 , 15 , 16 ]

version: Example values: [ 1.8.0_272-202010111709-b09 , 11.0.9+10-202010122348 , 14.0.2+11-202007272039 , 16+19-202010120348 ]

semver: Example values: [ 8.0.202+8.0.202008210941 , 11.0.9+10.0.202010122348 , 14.0.2+11.0.202007272039 , 16.0.0+19.0.202010120339 ]
Formed from the major, minor, security, and build number by the formSemver() function.

build: Example values: [ 6 , 9 , 18 ]
The OpenJDK build number for the JDK being built.

HelloWorld.java — первая программа на Java — введение в Java 001 #

Короткая инструкция, для тех кто нетерпелив #

Для работы с Java в моём курсе нам понадобится:

  1. JDK — Java Development Kit. Без этого Java-код на компьютере не запускается.
  2. IntelliJ IDEA Community Edition. Та программа, в которой я пишу код.

Подробности в длинной инструкции.

Установка JDK #

В интернете существуют тысячи инструкций по установке рабочего окружения для работы в Java.

Я уверен, что вы сможете вбить в Google запрос на английском: “How to Install Java Development Kit” или на русском: “Установка JDK”. Java принадлежит фирме Oracle и можно сразу скачать Java с её страниц, скачав просто JDK, скачав Netbeans вместе с JDK или скачав открытую AdoptOpenJDK (предпочтительнее для новичков).

Если нет, то я попробую рассказать основное: что нам надо, и где это взять.

Java Development Kit #

JDK — это программа, которая будет переводить написанный вами код в понятный для машин. На вашей машине может быть установлено несколько разных версий Java. Одной из них желательно должна быть Java 8.x. Это та версия, на которой базируются все современные версии, и для изучения основ языка и ООП именно оно нам и “нада”.

Скачать JDK можно с AdoptOpenJDK:

Скачать AdoptOpenJDK

Скачать JDK можно с Oracle: JDK download Oracle

JDK download Oracle

Уверен, вы справитесь с установкой этой программы самостоятельно или с помощью Google.

Работа с Java #

Работа с Java “по старинке”.
Во всех языках программирования стало стандартом первым уроком выводить на экране строчки “HelloWorld!”.

Кто я такой, что бы идти против правил? Сегодня мы напишем нашу первую программу и выведем на экран “Привет Мир!”.

Мы создаём файл в редакторе(эдиторе) и сохраняем его под названием HelloWorld.java

Сразу обращаем внимание на два слеша (слэш, слеш, а также slash, с англ. — «разрез, порез», «резкий удар», «косая черта»), которыми в конце строки можно отделить пометки в тексте. Также комментировать код можно, выделив его с двух сторон звёздочкой и слешем вот так: /* комментарий тут */. Комментарии в коде очень важны. Уже пару дней спустя не всегда очевидны некоторые решения и названия переменных. В иной программе может быть с десяток классов и в каждом — по несколько переменных. И все они что-то там считают, куда-то там что-то передают и зачем-то все вот прям здесь, и “кто это вообще написал”. Не стесняйтесь комментировать свой код и свои решения. Привычка писать “понятный” код поможет вам и в учёбе, и в работе.

Запускаем терминал или командную строку под Windows: Cтарт-> CMD-> Выполнить.

Компилируем и запускаем код:

Внимание — параметр -encoding сработал не во всех версиях JDK на 2.07.2020. Версии от Oracle поддерживают код выше.

терминал

С помощью javac мы создаём из нашей программы код, понятный машине. Не считаю нужным углубляться в детали этого процесса, но и ничто не мешает вам почитать о:

  • байт-коде,
  • компиляторе,
  • JVM,
  • SDK,
  • JDK

на других полезных ресурсах. История JVM (Java Virtual Machine) очень интересна, ведь ей уже более 20 лет.

При запуске мы увидим все системные сообщения на экране. Изменяя параметры программы, мы изменяем результаты. Это и есть программирование. И мы только что написали нашу первую программу.

Если у вас не прошла компиляция, как у меня, попробуйте скомпилировать с помощью учёта кодировки. Кириллица до сих пор не всегда хорошо работает в терминалах Windows. Если у вас не прошла компиляция вообще, то проверьте параметры настроек Java под Windows.

Не забывайте, что вы должны находиться в той папке, которая внесена в настройках в рабочие Java_Home.

В AdoptOpenJDK можно при инсталляции пакета указать на установку Java_Home.

Установка Adopt Open JDK: установка AdoptOpenJDK

установка AdoptOpenJDK

Если у вас всё получилось — поздравляю! Вы только что поняли, как именно работали первые Java-кодеры.

Если у вас не всё получилось — не расстраивайтесь. В следующих уроках я подробнее расскажу, как удобнее работать с программами без командной строки и ручной компиляции. Вы можете спокойно переходить ко второму и третьему уроку. С ними всё встанет на свои места.

Среда разработки Java — выбираем IDE программирования #

Среда разработки Java: Android Studio, IntelliJ IDEA, NetBeans IDE, Eclipse Java Neon…

Первую программу на Java я написал в обычном эдиторе на Solaris. Потом компилировал “ручками”. И запускал тоже ручками, примерно так, как было описано выше. И радовался тогда, очень радовался, если компилятор не выдавал ошибки и, уж тем более, испытывал настоящий восторг, если приложение делало, то что я и хотел. Позже я помню дотошную настройку под Windows 95. С внесением рабочей Java-папки в переменную среду пользователя.Поверьте на слово, порой я настраивал эти переменные среды часами.

Было много чего испробовано:

  • UltraEdit
  • Notepad и Notepad++
  • PHP Expert Editor
  • Visual Studio Code
  • Sublime Text
  • и многие другие

Но время редакторов и даже очень хороших редакторов прошло, и если для очень быстрых вещей, особенно за чужим компьютером, я с удовольствием использую портабельный “Notepad++” с флэшки, то дома я работаю в другой среде. Не в редакторе. А именно среде. И с объяснения термина “интегрированная среда разработки” мы и начнём.

Интегрированная среда разработки — IDE #

Программа для написания кода должна упрощать жизнь программиста и ускорять его работу, например:

  • “подсвечивать” нужные фрагменты, скобки, переменные и т.д. и давать возможность настроить или отключить часть подсветки;
  • подсказывать или “автозаполнять” код программисту, угадывать, если хотите, что именно он хочет написать;
  • возможность менять дизайн отображения кода;
  • быстро и чётко показывать результат;
  • быстро переключаться между проектами;
  • “самостоятельно” контролировать версии (например закидывать всё на GIT);
  • помогать найти ошибки в коде и, тем более, синтаксические и орфографические ошибки;
  • и многое другое.

Понятно, что всё это не про Notepad и даже не про Notepad++, хотя с подсветкой справляются многие “мелкие” редакторы. На рынке сейчас есть несколько крупных программ, которые заявляют себя как JAVA-IDE: это Eclipse (Eclipse Java Neon), IntelliJ IDEA (от JetBrains), NetBeans IDE (от Oracle), Android Studio (от Google & JetBrains).

Давайте я скажу по “два слова” о каждой из них:

Android Studio #

Android Studio — основан на IntelliJ IDEA с добавлениями, которые нужны при работе с android приборами. И, на самом деле, это среда разработки под Android на Java. И, говоря о плюсах или минусах, мы всё равно обсуждаем IntelliJ IDEA.

NetBeans IDE #

NetBeans IDE — рабочая среда от владельцев Java. Можно программировать, есть подсказка, есть подсветка. С моей точки зрения, это очень тяжёлый Notepad++ со встроенным компилятором. Но, на самом деле, NetBeans совсем не так уж плох. И не надо забывать, что он бесплатный и предоставляется компанией, которой принадлежат права на Java.

IntelliJ IDEA #

IntelliJ IDEA — редактор, утверждающий, что это IDE для Java и всех JVM-языков. Вполне возможно, что это так. Есть бесплатная версия и платная расширенная версия для Java EE (Java Platform, Enterprise Edition). Думаю, что многим будет важно узнать, что программу делают русскоязычные ребята.

Eclipse #

Eclipse — среда разработки для всего. Всех языков, всех платформ. Очень старая программа. Примерно треть всех разработчиков Java сидят в этой программе. Программа выросла из внутренних разработок фирмы IBM и, действительно, известна всем. На мой взгляд, главный конкурент любой среде разработки.

Visual Studio Code #

Visual Studio Code — изначально этот эдитор не был описан в этой статье. Однако, со временем, я всё чаще и чаще писал программы и документацию именно в нём. Мощный эдитор с огромным комъюнити и огромнейшим количеством полезных плагинов для всех видов разработки.

Я использую на работе NetBeans IDE, а дома IntelliJ IDEA и, на самом деле, вы не всегда можете контролировать то, в какой среде вы будете работать. Бывают ситуации, когда работать приходится просто в блокноте. Я веду к тому, что ознакомиться стоит со всеми программами и быть готовым к тому, что их придётся использовать.

Прежде чем выбирать окончательное решение, стоит поставить, может быть, все IDE и решить самому. Я лично надеюсь, что и Eclipse, и IntelliJ IDEA, NetBeans IDE будут чувствовать себя хорошо и жить долго, чтобы мы могли наслаждаться качеством конкуренции.

Я считаю, что в 2020-м году стоит начать с адекватной программы, и мой выбор падает на бесплатную intellij idea community edition, именно в ней будут даны первые уроки.

Установка и настройка IntelliJ IDEA для работы в Java #

IntelliJ IDEA — среда разработки программного обеспечения, сделанная в Кронштадте Санкт-Петербурге. Отличие среды разработки(IDE) от редакторов в том, что среда разработки должна “предугадывать” мысли и действия программиста. Можно, пожалуй, сравнить обычную бумажную записную книжку с телефонами друзей и электронную в телефоне. Удобство пользования электронной намного выше.

Повторюсь, что, прежде всего, у разработчика должна быть установлена на компьютере восьмая и/или актуальная версия JDK. На данный момент за Java Development Kit отвечает Oracle и у него можно скачать актуальную версию тут. На момент написания статьи это была версия 8.02, и скачать её можно было как отдельно от NetBeans IDE 8.2, так и вместе. Я выбрал JDK 8u111 with NetBeans 8.2. Я очень надеюсь, что будущему разработчику не надо объяснять, какой кнопочкой скачивать из интернета. После установки JDK можно перейти к IntelliJ IDEA.

IntelliJ IDEA можно скачать на сайте www.jetbrains.com/idea/. Пожалуй, стоит знать, что там же качается и PhpStorm для php и PyCharm для Python.

IntelliJ IDEA есть в двух версиях — в бесплатной Community и платной Ultimate. Обе версии бывают только на одном языке, и это не русский. Для введения в Java бесплатная версия ничем не хуже платной. Различия в версиях можно посмотреть на сайте производителя перед скачиванием.

Если вам жизненно необходима Ультимативная версия, то не скачивайте “лекарство”, не ломайте софт и не прописывайте левый сервер в лицензиях. Вы не сможете обновиться, а обновления бывают достаточно часто. Просто скачайте ультимативную версию и закажите себе бесплатные студенческие логины. Подробности студенческой лицензии тут — www.jetbrains.com/student/. IDEA нет на русском языке. Если русский язык очень важен, то у вас есть возможность работать с русским интерфейсом на NetBeans.

При установке можно для начала согласиться со всеми настройками по умолчанию и дойти до создания нового проекта. Проектов может быть множество. Например, игра для андроид-приборов или прошивка для “умного холодильника”. Предположу, что вы не знаете, как будет называться ваша первая программа, поэтому можете назвать проект “myFirstJavaProject”, “JavaBeginner” или “JavaFromAndron13”. Название можно поменять позже, проект можно удалить или перенести файлы из проекта в проект, и поэтому над названием можно особо долго не думать. Желательно, что б оно было говорящее само за себя. На случай если у вас будет 20-30 или даже 1000 проектов.

 

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

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