Intellij idea как создать проект java

от admin

Create your first Java application

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

Prepare a project

Create a new Java project

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

Launch IntelliJ IDEA.

If the Welcome screen opens, click New Project .

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

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

Name the project (for example HelloWorld ) and change the default location if necessary.

We’re not going to work with version control systems in this tutorial, so leave the Create Git repository option disabled.

Make sure that Java is selected in Language , and IntelliJ is selected in Build system .

To develop Java applications in IntelliJ IDEA, you need the Java SDK ( JDK ).

If the necessary JDK is already defined in IntelliJ IDEA, select it from the JDK list.

If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory (for example, /Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk ).

If you don’t have the necessary JDK on your computer, select Download JDK . In the next dialog, specify the JDK vendor (for example, OpenJDK), version, change the installation path if required, and click Download .

Leave the Add sample code option disabled as we’re going to do everything from scratch in this tutorial. Click Create .

After that, the IDE will create and load the new project for you.

Create a package and a class

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

In the Project tool window, right-click the src folder, select New (or press Alt+Insert ), and then select Java Class .

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

IntelliJ IDEA creates the com.example.helloworld package and the HelloWorld class.

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

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

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

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

Write the code

Add the main() method using live templates

Place the caret at the class declaration string after the opening bracket < and press Shift+Enter .

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

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

As you type, IntelliJ IDEA suggests various constructs that can be used in the current context. You can see the list of available live templates using Ctrl+J .

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

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

Call the println() method using code completion

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

Type Sy and select the System class from the list of code completion suggestions (it’s from the standard java.lang package).

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

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

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

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

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

Basic code completion analyses the context around the current caret position and provides suggestions as you type. You can open the completion list manually by pressing Ctrl+Space .

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

Call the println() method using a live template

You can call the println() method much quicker using the sout live template.

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

Type sout and press Enter .

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

Build and run the application

Valid Java classes can be compiled into bytecode. You can compile and run classes with the main() method right from the editor using the green arrow icon in the gutter.

Click in the gutter and select Run ‘HelloWorld.main()’ in the popup. The IDE starts compiling your code.

When the compilation is complete, the Run tool window opens at the bottom of the screen.

The first line shows the command that IntelliJ IDEA used to run the compiled class. The second line shows the program output: Hello, World! . And the last line shows the exit code 0 , which indicates that it exited successfully.

If your code is not correct, and the IDE can’t compile it, the Run tool window will display the corresponding exit code.

When you click Run , IntelliJ IDEA creates a special run configuration that performs a series of actions. First, it builds your application. On this stage, javac compiles your source code into JVM bytecode.

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

After that, the JVM runs the bytecode.

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

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

IntelliJ IDEA automatically analyzes the file that is currently opened in the editor and searches for different types of problems: from syntax errors to typos. The Inspections widget at the top-right corner of the editor allows you to quickly see all the detected problems and look at each problem in detail. For more information, refer to Current file.

Package the application in a JAR

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

Create an artifact configuration for the JAR

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

Click , point to JAR and select From modules with dependencies .

To the right of the Main Class field, click and select HelloWorld (com.example.helloworld) in the dialog that opens.

IntelliJ IDEA creates the artifact configuration and shows its settings in the right-hand part of the Project Structure dialog.

Apply the changes and close the dialog.

Build the JAR artifact

From the main menu, select Build | Build Artifacts .

Point to HelloWorld:jar and select Build .

Building an artifact

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

Run the packaged application

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

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

Create a run configuration for the packaged application

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

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

In the Run/Debug Configurations dialog, click and select JAR Application .

Name the new configuration: HelloWorldJar .

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

Scroll down the dialog and under Before launch , click , select Build Artifacts | HelloWorld:jar .

Doing this means that the HelloWorld.jar is built automatically every time you execute this run configuration.

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

Execute the run configuration

On the toolbar, select the HelloWorldJar configuration and click to the right of the run configuration selector. Alternatively, press Shift+F10 if you prefer shortcuts.

As before, the Run tool window opens and shows you the application output.

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

Intellij idea как создать проект java

В прошлой теме мы рассмотрели, как создавать первую программу с последующим ее запуском в командной строке. Однако в реальности, как правило, крупные программы разрабатываются не при помощи простого текстового редактора, а с использованием таких средств как IDE или интегрированные среды разработки, которые упрощают и ускоряют написание кода и создание приложений. На данный момент одной из самых популярных сред разработки для Java является IntelliJ IDEA от компании JetBrains. Рассмотрим, как использовать данную среду.

Прежде всего загрузим установочный дистрибутив с официального сайта https://www.jetbrains.com/idea/download. По этому адресу можно найти пакеты для Windows, MacOS, Linux. Кроме того, сама среда доступна в двух версиях — Ultimate (платная с триальным бесплатным периодом) и Community (бесплатная). В данном случае выберем бесплатную версию Community .

Установка IntelliJ IDEA

Конечно, Community-версия не имеет ряда многих возможностей, которые доступны в Ultimate-версии (в частности, в Community недоступны опции для веб-приложений на Java). Но Community-версия тоже довольно функциональна и тоже позволяет делать довольно много, в том числе приложения на JavaFX и Android.

После установки запустим IntelliJ IDEA и создадим первый проект. Для этого на стартовом экране выберем New Project :

Создание проекта в IntelliJ IDEA

Далее откроется окно создания проекта. В левой части в качестве типа проекта выберем Java.

Создание проекта Java в IntelliJ IDEA

В поле Name укажем имя проекта. В моем случае проект будет называться HelloApp.

В поле Location можно указать путь к проекту, если не устраивает путь по умолчанию.

Поскольку мы будем работать с языком Java, в поле Language выберем пункт Java

Кроме того, в поле JDK можно указать путь к Java SDK, который будет использоваться в проекте. Как правило, это поле по умолчанию уже содержит путь к JDK, который установлен на локальном компьютере. Если это поле пусто, то его надо установить.

После этого нажмем на кнопку Create. После этого среда создаст и откроет проект.

Первый проект на Java в IntelliJ IDEA

В левой части мы можем увидеть структуру проекта. Все файлы с исходным кодом помещаются в папку src . По умолчанию эта папка пуста, никаких файлов кода у нас в проекте пока нет. Поэтому добавим файл с исходным кодом. Для этого нажмем на папку src правой кнопкой мыши и в контекстном меню выберем пункт New -> Java Class :

Добавления файла с кодом в проект на Java в IntelliJ IDEA

После этого нам откроется небольшое окошко, в которое надо ввести имя класса. Пусть класс будет называться Program :

Добавления класса в проект на Java в IntelliJ IDEA

После нажатия на клавишу Enter в папку src будет добавлен новый файл с классом java (в случае выше класс Program). А в центральной части откроется его содержимое — собственно исходный код:

Создание класса на Java в IntelliJ IDEA

Изменим код класса следующим образом:

С помощью зеленой стрелки на панели инструментов или через меню Run -> Run. запустим проект.

запуск проекта на Java на выполнение в IntelliJ IDEA

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

Java Core для самых маленьких. Часть 1. Подготовка и первая программа

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

Начало разработки языка было положено еще в 1991 году компанией Sun Microsystems, Inc. Вначале язык был назван Oak (Дуб), но в 1995 он был переименован в Java. Публично заявили о создании языка в 1995 году. Причиной создания была потребность в независящем от платформы и архитектуры процессора языке, который можно было бы использовать для написания программ для бытовой электротехники. Но поскольку в таких устройствах применялись различные процессоры, то использование популярных на то время языков С/С++ и прочих было затруднено, поскольку написанные на них программы должны компилироваться отдельно для конкретной платформы.

Особенностью Java, которая решила эту проблему, стало то, что компилятор Java выдает не машинный исполняемый код, а байт-код — оптимизированный набор инструкций, которые выполняются в так называемой виртуальной машин Java (JVM — Java Virtual Machine). А на соответствующую платформу предварительно устанавливается JVM с необходимой реализацией, способная правильно интерпретировать один и тот же байт-код. У такого подхода есть и слабые стороны, такие программы выполняются медленнее, чем если бы они были скомпилированы в исполняемый код.

Читать:
Breezip что это за программа

Установка программного обеспечения — JDK

В первую очередь, нам нужно установить на компьютер так называемую JDK (Java Development Kit) — это установочный комплект разработчика, который содержит в себе компилятор для этого языка и стандартные библиотеки, а виртуальную машину Java (JVM) для вашей ОС.

Для того чтобы скачать и установить JDK открываем браузер, и в строке поиска Google вводим “download JDK” или переходим по этой ссылке.

Скролим ниже и находим таблицу с вариантами скачивания JDK. В зависимости от нашей операционной системы выбираем файл для скачивания.

Процесс установки для ОС Windows имеет несколько этапов. Не стоит пугаться, все очень просто и делается в несколько кликов. Вот здесь подробно описан процесс установки. Самое важное для пользователей Windows это добавить системную переменную JAVA_HOME. В этой же статье достаточно подробно расписано как это сделать (есть даже картинки).

Для пользователей MacOS также стоит добавить переменную JAVA_HOME. Делается это следующим образом. После установки .dmg файла JDK переходим в корневую папку текущего пользователя и находим файл .bash_profile. Если у вас уже стоит zsh то ищем файл .zshenv. Открываем этот файл на редактирование и добавляем следующие строки:

Здесь обратите внимание на версию JDK указанную в пути — jdk1.8.0_271.jdk. Могу предположить, что у вас она будет отличаться, поэтому пройдите по указанному пути и укажите свою версию. Сохраняем изменения и закрываем файл, он нам больше не понадобится.

Теперь важно проверить правильность установки JDK. Для этого открываем командную строку, в случае работы на Windows, или терминал для MacOS. Вводим следующую команду: java -version Если вы все сделали правильно, вы увидите версию установленного JDK. В ином случае вы, скорее всего, допустили где-то ошибку. Советую внимательно пройтись по всем этапам установки.

Установка IDE

Теперь нам нужно установить среду разработки, она же IDE (Integrated development environment). Что собой представляет среда разработки? На самом деле она выглядит как текстовый редактор, в котором мы можем вводить и редактировать текст. Но помимо этого, этот текстовый редактор умеет делать проверку синтаксиса языка на котором вы пишете. Делается это для того чтобы на раннем этапе подсказать вам о том, что вы допустили ошибку в своем коде.

Также среда разработки содержит в себе компилятор. Компилятор — это специальный инструмент, который будет превращать код, который вы пишете, в машинный код или близкий к машинному коду.

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

Для начала нам нужно выбрать и среду разработки. Их довольно таки много, и самыми популярными из них являются: IntelliJ IDEA, NetBeans, Eclipse. Для себя я выбираю IntelliJ IDEA. Она является самой удобной на мой взгляд, и хоть она и платная, на официальном сайте можно найти бесплатную версию которая называется Community. Этой версии будет вполне достаточно для изучения основ Java. Вообщем будем работать в IntelliJ IDEA.

Итак, открываем браузер, в поисковой строке вводим «Download IntelliJ IDEA Community» или переходим по этой ссылке. Выбираем версию ОС и качаем версию Community.

В установке IntelliJ IDEA нет ничего военного. На крайний случай на ютубе есть множество видео о том, как установить эту программу.

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

Теперь мы готовы создать нашу первую программу. В окошке запустившийся IDE нажимаем New Project.

В новом окошке в левой панели выбираем Java.

Обратите внимание! В верхнем окошке, справа, возле надписи «Project SDK:» должна находится версия Java, которую вы установили вместе с JDK. Если там пусто, то вам нужно будет указать путь к вашему JDK вручную. Для этого в выпадающем списке нажмите «Add JDK. « и укажите путь к вашему JDK, который был предварительно установлен.

Теперь можем нажать на кнопку Next. В следующем окошке, вверху, поставьте галочку “Create project from template” и выберите “Command Line App”. И снова нажимаем Next.

Дальше нам нужно указать имя программы. У меня это будет Hello World, желательно чтобы имя проекта было введено латиницей, и на английском языке.

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

После указываем путь к проекту программы.

Далее, нам нужно указать базовый пакет нашей программы. О пакетах я расскажу вам позже, обычно компании используют свое имя Интернет-домена в обратном порядке, но вы можете написать, например, свои имя и фамилию через точку в нижнем регистре (маленькими буквами), тоже латиницей. Я же использую псевдоним. Когда все поля будут заполнены — нажимаем “Finish”.

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

Это окно, то что вы будете видеть 80-90%, а иногда и 100% времени, работая программистом.

Для того чтобы закончить ваше первое приложение, останется добавить строчку кода System.out.print(«Hello world!»); как показано на скриншоте.

Чтобы скомпилировать и запустить на выполнение вашу программу, вам нужно нажать кнопочку с зеленым треугольничком на верхней панели справа, или в меню найти пункт Run -> Run “Main”. И внизу на нижней панели, под окном редактора, в консоли, вы увидите результат выполнения вашей программы. Вы увидите надпись Hello World! Поздравляю, вы написали свою первую программу на Java.

Разбираем первую программу

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

Пройдемся по порядку:

В начале мы видим package com.zephyr.ventum; — это объявление пакета, и это постоянный атрибут файлов с исходным кодом в Java. Простыми словами, это локация вашего файла в проекте и любой .java файл должен начинаться с подобной строки.

Ключевое слово — это слово зарезервированное языком программирования. Например, package — это тоже ключевое слово.

Фигурные скобки <> у метода main обозначаю начало и конец тела метода, весь код метода должен располагаться между этими скобками. Аналогичные скобки есть и у класса Main.

Следующая строка является // write your code here однострочным комментарием.

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

Многострочный комментарий будет выглядеть следующим образом:

Мы просто располагаем несколько строк между символами /* и */

System.out.print(«Hello world!»); — строка которая находится внутри метода main является командой, которая выводит в консоль строку «Hello world!»

Обратите внимание что в конце стоит точка с запятой, в языке Java команды должны заканчиваться точкой с запятой.

Затем мы закрываем тело нашего метода main > а также закрываем класс Main > .

На этом статья подходит к концу. Автором конкретно этого материала является Егор и все уменьшительно ласкательные формы слов сохранились в первозданном виде.

Java Spring Boot + IntelliJ IDEA

Java and spring boot logo with a plus sign followed by intellij idea logo

To those who develop in java nowadays, it’s almost impossible to miss Spring framework and more specifically Spring Boot. Using this development stack, we gain more productivity and agility from small to large sized java projects. In this guide I’ll demonstrate how to install, configure IntelliJ IDEA and create a simple Hello-World using java, IntelliJ IDEA and spring boot.

The github repository of the example project of this post, can be found at: https://github.com/danielpadua/java-spring-idea-example

Requirements

  • Java JDK 8 or higher

Installing IntelliJ IDEA

Use the following sections based in which operational system you’ll be using:

Windows

In Windows we have 2 options:

Go to jetbrains download page, select the latest version (on the writing date of this guide is the 2019.1.1) and install it using NNF (next, next and finish).

If you don’t know Chocolatey, take a look at this post.

Open powershell and install IntelliJ IDEA using the following command line:

Linux

In Linux we also have 2 options:

Go to jetbrains download page, select the latest version (on the writing date of this guide is the 2019.1.1), extract the .tar.gz file and execute the /bin/idea.sh file.

Depending in which Linux distro you are using, you’ll use a different package manager. For instance, debian based distros, like the popular ubuntu, use apt-get. For Red Hat (or RHEL) based distros use yum or dnf. Search the best way to install IntelliJ IDEA using your package manager.

macOS

In macOS we have 2 options again:

Go to jetbrains download page, select the latest version (on the writing date of this guide is the 2019.1.1) and install it as usual, dragging the app from the .dmg file to the apps folder of your mac.

If you don’t know Homebrew, take a look at this post

Open your favorite terminal and install IntelliJ IDEA using the following command line:

Configuring IntelliJ IDEA

With IntelliJ IDEA installed, the configuration is pretty simple. When you execute IDEA you will be questioned about some configurations like: theme color, shortcut key mapping and plugins. Let’s leave default config and begin.

Creating the project

As soon as it starts, you’ll see the following screen:

IntelliJ IDEA initial screenIntelliJ IDEA initial screen

For this example, we’ll be using Maven as build-tool.

Unfortunately using IntelliJ IDEA Community, according to the documentation, there’s no support to create Spring Boot projects using Spring Initializr through the IDE in Community version, only in the Ultimate Edition. So, we have two choices that we can explore:

Use Spring Initializr Web

Access: https://start.spring.io, and fill the fields like below:

Configuring project creation in Spring InitializrConfiguring project creation in Spring Initializr

Don’t forget to select Web as dependency. Click Generate Project to download the project zip file. Extract it to a directory of your choice, go back to IntelliJ IDEA and select Import Project. Navigate to project’s directory and select the pom.xml file. You’ll see a window that is responsible for importing the Maven project, leave the defaults configs:

Import Spring Initializr projectImport Spring Initializr project

Select the project to import and click next:

Select the projectSelect the project

In the next screen, set the JDK version that you installed:

Select the JDK version for the projectSelect the JDK version for the project

In the next screen confirm the project name and click finish.

Creating a Maven project and add Spring manually

In IntelliJ IDEA’s initial screen, select Create New Project, located on the left side tab and select Maven, on the right side, select the JDK version and click next:

Creating a Maven projectCreating a Maven project

When selecting the archetype, IntelliJ IDEA will assume that you will use Quickstart archetype, which is ok for our goal.

In the next screen specify the GroupId, ArtifactId and the Version and click next:

Maven configurationMaven configuration

After you just have to name your project and click finish:

Naming the projectNaming the project

With the project created, configure pom.xml according to the following snippet:

After updating pom.xml a notification will pop-up at the bottom right corner of the screen:

Import pom.xml changesImport pom.xml changes

Click Import Changes for Maven refresh all project dependencies.

Now we’ll create a class that will contain the main function of the project. Remember that creating a class in default package is not a good java practice, so, click in source folder main/java and create a package:

Creating a packageCreating a package

Write the name of the package, in my example was: br.com.danielpadua.java_spring_idea_example , and create a class inside this package named ExampleApplication.java , and write the following code:

Don’t forget the unit tests main class too, repeat package creation step and create a class named: ExampleApplicationTests.java and write the code:

At this moment we’ll have basically the same project structure that is generated by Spring Initializr at the section above.

Completing the project

With the basic project skeleton created, we just have to create a package to nest the controller that will contain Hello World endpoint. Right click the root package:

Creating a package for the controllersCreating a package for the controllers

Write: controllers and confirm. Inside the generated package, create a class named: ExampleController.java and write the code:

Run the project by right clicking over the main class Application.java and select the option Run ‘Application.main()’ :

Running the appRunning the app

After clicking run, you should see the output in the Run tab located at screen’s bottom:

Spring initialization logSpring initialization log

To test the app, you only have to open your favorite browser and access: http://localhost:8080/api/example/hello-world, and you should see the Hello World message:

VoiláVoilá

Conclusion

IntelliJ IDEA is the most used IDE for java nowadays and it’s probably the most complete in the opinion of many developers. Community version is a great alternative to traditional eclipse.

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