Как создать проект в intellij idea java
Перейти к содержимому

Как создать проект в intellij idea java

  • автор:

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-20.0.1.jdk ).

Creating the new project and adding the 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 Control+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 Control+. to insert the selection with a trailing period.

Type o , select out , and press Control+. 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 analyzes the context around the current caret position and provides suggestions as you type. You can open the completion list manually by pressing Control+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 in 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 ( Control+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 Control+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 Control+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.

Write Hello World in Java Using Intellij and Maven

czetsuya

Learn how to code Hello World in Java using IntelliJ and Maven.

1. Introduction

This blog will teach you how to create a Hello World application using a Maven archetype in Java using IntelliJ IDE.

2. Requirements

You must have the following installed on your local machine.

  • OpenJDK 11
  • Maven
  • IntelliJ community edition

3. Creating a new Java project from a Maven archetype

3.1 Creating the project

Open IntelliJ and you should be greeted with IntelliJ’s Welcome screen.

If this is your first time running IntelliJ then the projects’ panel should be empty.

Click New Project and select Maven. In the right panel, click “Create from archetype” and find and select “maven-archetype-quickstart”.

*archetype is a project template that automatically includes dependencies depending on the purpose of the project. The particular template that we have selected includes JUnit dependency.

*You can search for dependency signature from https://mvnrepository.com.

In the next screen, you must enter the project’s artifact coordinates:

In this case, our project name is hello-intellij-training, normally you should use the same for artifact id.

GroupId: must be something unique to your organization, here we are using this blog’s domain name. Doesn’t really need to be a domain name nor must it exists as an active URL. But this is the standard.

Click Next and a project summary should be presented.

Click Finish. Give it some time to download the archetype and initialize your project.

This is how our project should look like. Notice that it’s using Java 1.7 (<maven.compiler.source>1.7</maven.compiler.source>) by default? We should replace it with 11.

3.2 Setting the correct Java version in IDE

Before we could print our hello world message, we should first configure the Java version for the project.

Select hello-intellij-training in the Project’s panel and click File in the top menu, select Project Structure.

There are two things to check here related to Java.

3.2.1 Under Project Structure / Project Settings / Project, left panel Project SDK select 11. If the dropdown is empty click Edit and finds the directory where you installed OpenJdk 11.

3.2.2 This time open, Project Structure / Project Settings / Module and select hello-intellij-training. In this case, we only have one module. But if you are working on a multi-project then you should have several entries here. In the rightmost panel, under Sources / Language level, select 11. This is the common source of compilation issues. Always make sure that you are compiling and running on the same version of Java.

Now we are ready to print our very first hello world message.

4. Printing our Hello World message

By default, the archetype should already make available an App class that prints the hello world message. Let’s change it to “Hello IntelliJ!”.

5. Running the application

Let’s build the application first.

In the right panel, toggle Maven, expand hello-intellij-training / Lifecycle. Right-click on install and select Run Maven Build.

This should build our project. Whenever you have revisions on your project select install. If you remove some files run “clean” first followed by install.

Another approach to building the module is by using IntelliJ’s builder.

You can right-click on the module, and select Build Module hello-intellij-training.

You can also do the same using the main navigation. Build project or module.

By default IntelliJ uses ant, to delegate the building process using Maven we need to do the following.

In the main menu, select File / Settings.

Expand Build, Execution, Deployment / Build Tools / Maven and select Runner. In the right panel, click Delegate IDE build/run actions to Maven. Click Ok.

Now try building the module again and in the Build log, you should see maven logs.

There are several ways to run the maven application.

5.1 In your App class, there should be a green arrow in the gutter, click it and it should show a popup where you can either select Run or Debug.

You could also, put the cursor in the class and press the Run shortcut Ctrl + Shift + F10.

The Run panel should show at the bottom.

5.2 If you run 5.1 first, then you should see App in the top right run configuration. Otherwise, it should be empty.

From here, you can click the dropdown (whether you have App or not).

If you already run the App class, it should look like this:

But in some cases, you might want to create a Run Configuration from a template. For example, Spring Boot.

In the Run/Debug Configurations panel, click the plus icon and select Add New Configuration.

You should be presented with a list of IntelliJ’s supported Run/Debug configuration templates.

Chapter 3 A first IntelliJ project

This course uses the IntelliJ Idea Integrated Development Environment (IDE) to develop Java programs. This chapter deals with using IntelliJ Idea to create Java applications.

3.1 Dependency management

As you probably already know by now, code you write is always dependent on other code. This can be code native to the platform (such as the integer “class” in R, or the str class in Python) but it can also be code that is not distributed with the standard platform (such as ggplot2 in R, or numpy in Python). These “non-core” dependencies need to be managed. Many tools exist for dependency management; in Python this can be pip or conda , in R you use install.packages() and in Java there are also several technologies for this. In this course we’ll use Gradle. It does much more than dependency management but for now this is the only relevant aspect.

Let’s dive in and see the different players in a Java coding project work together.

3.2 A first project

Start IntelliJ and select “ + Create New Project ” from the start screen (or New → Project from the File menu).

In the New Project wizard, select Gradle on the left menu and then a project SDK (Standard Development Kit) — this example shows Java 10. Only check Java in the Additional Libraries section.

Click “Next”. In the next window, give your project a Name and Location. Expand the Artifact Coordinates section which is hidden by default and give your project a GroupId, an ArtifactId and a Version.

The group ID should be a unique identifier; in Java this is usually the web domain of you or your employer, reversed and with a project name appended. It is a way to guarantee a unique name space. Note the underscores; in Java you specify package names with underscores and lowercase letters. The artifact ID is the name of your project, also in lowercase but usually with hyphens between words. Give it version 0.0.1.

Click “Finish”. A brand new Gradle-managed Java project will be created with a layout as shown below.

Several folders and files have been created. The src folder is where the magic is going to happen of course: that’s where your code is going to live. The other folders are for project management ( ./.gradle , ./gradle , ./.idea ) and deployment ( ./build which is not present yet).

At the root of the project there is a file called build.gradle . It contains the configuration of your project. One dependency has been added: JUnit 4, which is a unit testing framework. Since JUnit 4 is an older version, we’ll immediately change this into JUnit 5. You should modify the build.gradle file so it looks exactly like this (except for the group declaration):

As you can see this is programming code (Groovy) that configures a programming project (Java).

Whenever you make changes to build.gradle you should refresh your project via the small pop-up that appears in the editor pane, or via the Gradle Tool Window on the right (Re-import All Gradle Projects).

Finally, let’s create some Java code. Right-click on the src/main/java folder in the Project panel (left side) and select “New” → “Package” and give it the same name as your group ID (it is also in build.gradle ).

Select the new package , right-click it and select “New” -> “Java Class”. Name it HelloWorld (do not give any file extension!).

The class file will open in an editor. Within the class, put the caret below the line public class HelloWorld . Next, type “psvm” and press tab.

A brand new main() method is created using this keyboard shortcut. Here is another extremely useful shortcut, assuming the caret is within main() . Type “sout” followed by the tab.

Generate console output

The statement System.out.println(); appears. Within this print call, type “Hello, World”. Your class should look like this, except that your package will be named differently:

Click the green triangle within the editor border and select «run ‘HelloWorld.main()’ Note there is also a shortcut for running main() : ^ + shift + R .

In the console output on the lower pane, you will see this output, including the “Hello, World” message:

The “Tasks” are gradle stuff. It says, amongst others, that the source is compiled (Java is a compiled language!) and main() is run. You may notice that a new folder has appeared at the root of your project: build . Have a look at what’s inside.

If you get any errors (e.g. Error: LinkageError occurred while loading main class nl.bioinf.nomi.my_first_project.HelloWorld ), you need to make sure your specified Java version in build.gradle corresponds to the one configured for your project in IntelliJ (sometimes they get mixed up). Go to File → Project Structure and check under Project Settings/Project and Platform Settings/SDKs . The project SDK should have a version at least as high as the language level specified in build.gradle (in this case, Java 11):

3.3 Distribute an executable

The final step is getting the app to your users. In Java you use a jar (Java ARchive) for that.

Gradle can do the whole build-to-executable process. You first need to specify where your “main class” is located: the class which contains the main() method that you want to use as “entry point” of your application.

Since we use Gradle for the build process, the place to do this is the build.gradle file; open it again and add this section at the bottom:

The Main-Class line specifies for the JVM -when your application is going to be executed- to go look in class HelloWorld for a main() method to run when the application starts up. You can in fact have many main() methods in your application, but only one can serve as entry point in an executable. (Yes, you can make different executables with a single code base by simply specifying different entry points!)

Refresh your project as before. Next, Go to the right Gradle Tool Window on the right (make it visible if required: View → Tool Windows → Gradle) and expand the panel.

Select Tasks → build → double click “jar”. Your jar will be build under build/libs ; go there with a terminal application (IntelliJ also has one) and type java -jar my-first-project-0.0.1.jar .

You should see as output

3.4 Wrap-up

That’s it. This is how you create, run and build a Gradle-managed Java project.

Знакомство с IntelliJ IDEA: установка, создание Java-проекта и первая Java-программа

IntelliJ IDEA — одна из самых популярных интегрированных сред разработки (IDE) для языка Java. Благодаря мощному инструментарию и удобному интерфейсу, IntelliJ IDEA позволяет быстро и эффективно создавать, и отлаживать Java-приложения разной сложности.

В этой статье мы рассмотрим процесс установки IntelliJ IDEA на такие операционные системы, как: Windows, Linux и macOS. Также создадим Java-проект и выполним первую Java-программу.

Загрузка и установка IntelliJ IDEA

Скачать IntelliJ IDEA для Windows, Linux и macOS можно с официальной страницы JetBrains (компания-разработчик IntelliJ IDEA).

Существуют две вариации IntelliJ IDEA: Community Edition и Ultimate. Ultimate является более профессиональным решением с дополнительными возможностями, отсутствующими в Community Edition. Однако Ultimate-версия доступна только по платной подписке, в то время как Community Edition полностью бесплатна. Более подробно про различия между этими двумя редакциями можно прочитать здесь.

Далее показаны шаги для загрузки и установки IntelliJ IDEA Community Edition на Windows, Linux и macOS.

Установка IntelliJ IDEA в Windows

Шаг №2: Выберите раздел Windows.

Шаг №3: Под редакцией Community Edition выберите желаемый способ установки — с помощью установщика (.exe) или архива (.zip). Установщик для архитектуры х86-64 — .exe, для 64-битной архитектуры ARM — .exe (ARM64). Дальнейшие шаги основаны на использовании установщика.

Шаг №4: Запустите установщик и нажмите Next:

Шаг №5: Выберите/подтвердите конечный путь установки IntelliJ IDEA:

Шаг №6: Рекомендуется установить флажок возле пункта Add «bin» folder to the PATH, чтобы система могла находить и запускать исполняемые файлы IntelliJ IDEA без необходимости указывать полный путь к ним. Чтобы создать ярлык IntelliJ IDEA на рабочем столе, установите флажок возле пункта IntelliJ IDEA Community Edition. Также рекомендуется выбрать пункт Add «Open Folder as Project», чтобы открывать папки в IntelliJ IDEA и работать с ними как с проектами. Создание ассоциации с .java-файлами позволит IntelliJ IDEA стать стандартным инструментом для открытия .java-файлов.

Шаг №7: Определите название папки, в которой будет размещен ярлык IntelliJ IDEA. По умолчанию IntelliJ IDEA предлагает создать папку JetBrains и разместить ярлык программы внутри нее.

Шаг №8: Если вы ставили флажок напротив пункта Add «bin» folder to the PATH, для завершения установки вам необходимо перезагрузить компьютер. Если вы хотите выполнить перезагрузку сейчас, выберите Reboot now. Если же вы планируете выполнить перезагрузку позже, выберите I want to manually reboot later.

Установка IntelliJ IDEA в Linux

Шаг №2: Выберите раздел Linux.

Шаг №3: Для архитектуры х86-64 под редакцией Community Edition выберите .tar.gz, для ARM64 — .tar.gz (ARM64). Затем нажмите на кнопку Download.

Шаг №4: Распакуйте архив в нужную директорию, например, /opt/ . Для этого введите команду типа:

sudo tar -xzf путь-к-скачанному-архиву -C /opt/

Замените путь-к-скачанному-архиву на фактический путь к скачанному архиву. Если вы хотите распаковать архив в другую директорию, замените /opt/ соответствующим путем. Например:

Шаг №5: Рекомендуется изменить владельца для IntelliJ IDEA с помощью следующей команды:

sudo chown -R $USER:$USER путь-к-распакованному-архиву

Замените путь-к-распакованному-архиву на фактический путь к распакованному архиву. Эта команда изменит права доступа для текущего пользователя. Если вы хотите изменить права доступа для другого пользователя системы, замените $USER на имя (username) этого пользователя.

Шаг №6: Выполните следующую команду, чтобы запустить IntelliJ IDEA:

Не забудьте заменить путь-к-распакованному-архиву , например, /opt/idea-IC-231.9011.34/bin/idea.sh

Шаг №7: Нажмите на значок шестеренки внизу слева в открывшейся программе и выберите пункт Create Desktop Entry, чтобы добавить ярлык IntelliJ IDEA в меню приложений:


Установка IntelliJ IDEA в macOS

Шаг №2: Выберите раздел macOS.

Шаг №3: Для архитектуры х86-64 под редакцией Community Edition выберите .dmg (Intel), для Apple Silicon — .dmg (Apple Silicon). Затем нажмите на кнопку Download.

Шаг №4: Запустите скачанный файл и перетащите иконку IntelliJ IDEA в каталог Applications.

Создание Java-проекта

Важной особенностью любой интегрированной среды разработки (IDE) является то, что она предоставляет возможность управлять целым проектом, состоящим из множества файлов. IDE предоставляет инструменты для создания, редактирования, компиляции, отладки и управления проектом, что отличает ее от простых редакторов кода.

Для создания Java-проекта нужно открыть IntelliJ IDEA и нажать на кнопку New Project:

После этого должно открыться окно настройки проекта:

В поле Name введите название проекта (оно может быть любым).

В поле Location нужно указать расположение проекта. Если вы не знаете, что такое Git, снимите флажок возле пункта Create Git repository.

В пункте Language выберите Java.

В пункте Build system выберите IntelliJ.

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

Снимите флажок возле пункта Add sample code.

Нажмите на кнопку Create.

Первая Java-программа в IntelliJ IDEA

После создания проекта, если вы сняли флажок с пункта Add sample code, должна создаться структура проекта без файлов исходного кода. В Java программы пишутся в файлах с расширением .java. Единицами структуры любой Java-программы или целого Java-приложения являются Java-классы, которые размещаются в .java-файлах. Обычно каждый Java-класс находится в отдельном .java-файле, причем название Java-класса должно совпадать с названием .java-файла.

Для создания Java-класса нажмите ПКМ по папке src в окне инструментов проекта (англ. «Project tool window»; область интерфейса, где отображаются все файлы и структура каталогов проекта). Затем наведите курсор на пункт New и выберите Java Class.

В появившемся окне введите название Java-класса и нажмите Enter. Например:

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

Обратите внимание, что на данном этапе программу нельзя запустить, так как отсутствует точка входа в программу — главный метод main():

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

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