java 32 | Packages in java | In built packages | How to use packages in java
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
Using packages, it is easier to provide access control and it is also easier to locate the related classes
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and namespace management.
Some of the existing packages in Java are −
java.lang − bundles the fundamental classes
java.io − classes for input , output functions are bundled in this package
These packages consist of a large number of classes which are a part of Java API.
Some of the commonly used built-in packages are:1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported.2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support for Date / Time operations.4) java.applet: Contains classes for creating Applets.5) java.awt: Contain classes for implementing the components for graphical user interfaces (like button , menus etc).6) java.net: Contain classes for supporting networking operations
user defined
Programmers can define their own packages to bundle group of classes/interfaces, etc.
It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related.
using packages The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment.
The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
import package_name.Class; // Import a single class import import package_name.*; // Import the whole package
import a class
If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code:
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation
example
In our example, we will use the nextLine() method, which is used to read a complete line
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); System.out.println("Enter username");
String userName = myObj.nextLine(); System.out.println("Username is: " + userName); }
}
import package
There are many packages to choose from.
In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*).
import java.util.*;
This will import ALL the classes in the java.util package:
summary
A package in Java is used to group related classes. Think of it as a folder in a file directory.
We use packages to avoid name conflicts, and to write a better maintainable code.
Packages are divided into two categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)
To use a class or a package from the library, you need to use the import keyword:
suggested reading
https://www.geeksforgeeks.org/packages-in-java/
Java: The Complete Reference Book by Herbert Schildt
https://www.youtube.com/watch?v=WZub7Oc3HDo&list=PLA3taA2THXpy0q0TxYd4i5dpk76HpsZ_n
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «java 32 | Packages in java | In built packages | How to use packages in java», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.