Пакет Java
В этой статье вы узнаете о пакетах и о том, как их использовать для создания модульного кода на Java.
Пакет Java
Пакет — это просто контейнер, который группирует связанные типы (классы Java, интерфейсы, перечисления и аннотации). Например, в ядре Java ResultSet интерфейс принадлежит java.sql пакету. Пакет содержит все связанные типы, необходимые для SQL-запроса и подключения к базе данных.
Если вы хотите использовать ResultSet интерфейс в своем коде, просто импортируйте пакет java.sql (импорт пакетов будет обсуждаться позже в статье).
Как упоминалось ранее, пакеты — это просто контейнеры для классов Java, интерфейсов и так далее. Эти пакеты помогут вам зарезервировать пространство имен классов и создать поддерживаемый код.
Например, Date в Java можно найти два класса. Однако практическое правило программирования на Java состоит в том, что в проекте Java допускается только одно уникальное имя класса.
Как им удалось включить в JDK два класса с одинаковым именем Date?
Это стало возможным, потому что эти два Date класса принадлежат двум разным пакетам:
- java.util.Date — это обычный класс Date, который можно использовать где угодно.
- java.sql.Date — это дата SQL, используемая для запроса SQL и т.п.
В зависимости от того, определен ли пакет пользователем или нет, пакеты делятся на две категории:
Встроенный пакет
Встроенные пакеты — это существующие пакеты java, которые поставляются вместе с JDK. Так , например, java.lang , java.util , java.io и т.д. Например:
Выход :
ArrayList Класс принадлежит java.util package . Чтобы использовать его, мы должны сначала импортировать пакет с помощью import оператора.
Пользовательский пакет
Java также позволяет создавать пакеты в соответствии с вашими потребностями. Эти пакеты называются пользовательскими пакетами.
Как определить пакет Java?
Чтобы определить пакет в Java, вы используете ключевое слово package .
Java использует каталоги файловой системы для хранения пакетов. Давайте создадим файл Java внутри другого каталога.
Теперь отредактируйте файл Test.java и в начале файла напишите инструкцию пакета как:
Здесь любой класс, объявленный в каталоге test, принадлежит пакету com.test .
Выход :
Здесь класс Test теперь принадлежит пакету com.test .
Соглашение об именах пакетов
Имя пакета должно быть уникальным (например, доменное имя). Следовательно, существует соглашение о создании пакета как доменного имени, но в обратном порядке. Например, com.company.name
Здесь каждый уровень пакета — это каталог в вашей файловой системе. Как это:
И нет никаких ограничений на то, сколько подкаталогов (иерархии пакетов) вы можете создать.
Как создать пакет в Intellij IDEA?
В IntelliJ IDEA можно создать пакет следующим образом:
- Щелкните правой кнопкой мыши исходную папку.
- Перейти к новому, а затем упаковать .
- Появится всплывающее окно, в котором вы можете ввести имя пакета.

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

Как импортировать пакеты в Java?
В Java есть import инструкция, позволяющая импортировать весь пакет (как в предыдущих примерах) или использовать только определенные классы и интерфейсы, определенные в пакете.
The general form of import statement is:
The import statement is optional in Java.
If you want to use class/interface from a certain package, you can also use its fully qualified name, which includes its full package hierarchy.
Here is an example to import a package using the import statement.
The same task can be done using the fully qualified name as follows:
Example: Package and importing package
Suppose, you have defined a package com.programiz that contains a class Helper.
Now, you can import Helper class from com.programiz package to your implementation class. Once you import it, the class can be referred directly by its name. Here’s how:
- the Helper class is defined in com.programiz package.
- класс Helper импортируется в другой файл. Файл содержит класс UseHelper.
- getFormattedDollar() Метод класса Helper вызывается внутри класса UseHelper.
В Java import оператор пишется непосредственно после оператора пакета (если он существует) и перед определением класса.
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 .

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.
Создание и запуск первого Java-приложения (часть 1)

Чтобы получить представление о том, как IntelliJ IDEA поможет вам в разработке и запуске Java-приложений, мы предлагаем вам создать и запустить простейший пример «Hello, World» в данной программе. Таким образом, вы сможете узнать об основных IDE функциях без необходимости вдаваться в детали кода. Пошаговая инструкция поможет вам не запутаться в тонкостях запуска и настройки программы.
Перед началом работы
Создание проекта
Если ни один проект в данный момент не открыт, нажмите кнопку Create New Project на экране приветствия. В противном случае, выберите пункт New Project в меню File. В результате откроется мастер создания проекта.
В левой панели выберите Java Module.
В правой части страницы, в поле Project name, введите название проекта: HelloWorld.
Если до этого вы никогда не настраивали JDK в IntelliJ IDEA в (в таком случае в поле Project SDK стоит <Nоne>), необходимо сделать это сейчас.
Вместо <Nоne> нажмите New и в подменю выберите JDK.
В окне Select Home Directory for JDK выберите директорию, в которую устанавливалось JDK и нажмите ОК.

Версия JDK, которую вы выбрали, появится в поле Project SDK.

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

Поскольку наше приложение будет «старым добрым приложением Java», мы не нуждаемся в любой из этих технологий. Так что просто нажмите кнопку Finish.
Подождите, пока IntelliJ IDEA создает необходимые структуры проекта. Когда этот процесс завершится, вы можете увидеть структуру Вашего нового проекта в окне Project.
Изучение структуры проекта
HelloWorld. Это узел, содержащий ваш Java модуль. Папки .idea и файлы внутри директории HelloWorld.iml используются для хранения данных конфигурации вашего проекта и модулей соответственно.SRC папки содержат исходный код.
Создание пакета
В окне инструментов Project выберите папку SRC и нажмите ALT + INSERT. (В качестве альтернативы, вы можете выбрать File -> New, или New из контекстного меню для папки SRC).
В меню New выберите Package. (можно использовать стрелки вверх и вниз для навигации по меню, ENTER для выбора выделенного элемента)
В открывшемся окне New Package введите имя пакета (com.example.helloworld). Нажмите кнопку ОК (или клавишу ENTER).

Новый пакет появится окне Project.
Создание класса
Нажмите ALT + INSERT. В окне New из списка доступных действий с выделенным пакетом com.example.helloworld выбираем Java Class и нажимаем Enter.
В появившемся окне Create New Class в поле Name вводим имя HelloWorld. В поле Kind оставляем тип Class и нажимаем Enter, чтобы подтвердить создание класса.

Созданный класс HelloWorld появляется в структуре проекта:

На этом все приготовления закончены. Сам процесс написания нашего первого кода будет разобран во второй части статьи.
Creating the package and class
We recommend putting IntelliJ IDEA into full screen to give you the maximum amount of space for your new Hello World project.
The project window shows all the directories and the files that make up our projects.
Of course, you can use the mouse to navigate the Project window, but you can also use the arrow keys. You can also toggle the display of this tool window with Cmd+1 on macOS, or Alt+1 on Windows/Linux.
Creating Your Package and Class
Next, you're going to create the package and the class. Application packages are used to group together classes that belong to the same category or provide similar functionality. They are useful for organising large applications that might have hundreds of classes.
1) To create a new class, select the blue src folder and press Cmd+N on macOS, or Alt+Insert on Windows/Linux. Select Java Class from the popup.
You can type a simple class name in here, but if you want to create a new class in a particular package, you can type the whole package path separated by dots, followed by the class name. For example com.example.helloworld.HelloWorld .
Here, example might be your preferred domain and HelloWorld is the name of your Java class that IntelliJ IDEA will create.
When you press Enter IntelliJ IDEA will create the package you wanted, and the correct directory structure for this package that you specified. It has also created a new HelloWorld.java file and generated the basic contents of this class file. For example, the package statement and class declaration, the class has the same name as the file.
Coding Your HelloWorld Class
1) You can move on to the next line in a class file by pressing Shift+Enter. This moves the caret to the next line in the correct position and won't break the previous line.
2) To create the standard Java main method, type main . IntelliJ IDEA displays a live template that you can use to generate the full code construct and save a lot of time. You can also use Cmd+J on macOS, or Ctrl+J on Windows/Linux to see all the Live Templates in IntelliJ IDEA that are valid for the current context.
Note: Pressing Escape will always close a drop-down or dialogue without making any changes.
3) Press Enter to select it. IntelliJ IDEA will generate the rest of the code for you.
4) Now, you need to call a method that prints some text to the standard system output.
IntelliJ IDEA offers you code completion. If you type Sy you will see a drop-down of likely classes you might want to call. You want System so you can press Control+dot on the highlighted option.
Note: It's case-sensitive, typing in sy rather than Sy will give you different results!
5) Now type o IntelliJ IDEA will suggest you want to use out as the next function. IntelliJ IDEA is showing you a list of accessible fields and methods on the System class. Those that start with the letter o are listed first, followed by other methods and fields that contain the letter o .
6) press Control+dot and this time IntelliJ IDEA will suggest println . Press Enter to select it.
7) IntelliJ IDEA will also place the caret in the brackets, so you can provide the argument to the method. Type in a quote mark " and IntelliJ IDEA will close the quote mark for you. You can now type your text, Hello World in between the quotes.
Note: Instead of the above steps, you can also type sout to see a live template that will create the code construct for you as well, however we wanted to show you code completion!
Congratulations, you've just created your first Java application! Java files like this one can be compiled into bytecode and run in IntelliJ IDEA. Let's take a look at that in the next step.