Java util package import

java util Package — java.util Package in Java

The java.util package provides Java collections framework classes, internationalization support classes, a service loader, properties, random number generation, string parsing and scanning classes, base64 encoding and decoding, a bit array, and several miscellaneous utility classes. This package also contains legacy collection classes and legacy date and time classes.

Package java.util

Package java.util contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).

What is java.util Package ?

The java.util package is a Java package like other packages in Java. Like java.lang package, Java util package also a package which contains Java collections framework classes. Assuming you mean the packages that include the class libraries like java.lang.* and java.util.*, these live in the «lib» directory under wherever your Java Runtime Environment (JRE) is installed.

What is import java.util.* in Java ?

The import is a java keyword which is used for importing a Java class or entire Java package. For example import java.util.Calendar; means you are importing a single Calendar class. If you want to import all the classes from any Java package, your import statement must be like this import java.util.* that means you are importing entire java.util package.

Читайте также:  Java android upload files

java.util Package Import Statement Example

What does import java.util.* do in Java ?

Java util ( java.util.* ) package contains collection framework . Java collections framework contains collection classes , classes related to date and time , event model , internationalization , and miscellaneous utility classes . On importing this ( java.util ) package , you can do access all these classes and methods .

What is the use of java.util Package in Java ?

The use of java.util package is as follows

  1. It can be use for Java collections.
  2. It can be use for internationalization support by using the internationalization supported classes from java.util package.
  3. It can be use for random number generation.
  4. It can be use for string parsing.
  5. It can be use for base64 encoding and decoding.

java util Package - java.util Package in Java, java.util package provides Java collections framework, internationalization, service loader, properties, random number generation, string parsing and scanning., Complete Tutorial on java.util Package.

What is Collections Framework in Java ?

A collection sometimes called a container is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data in Java .

  • A collection is the same as the intuitive, mathematical concept of a set. A set is just a group of unique items, meaning that the group contains no duplicates.
  • Java Collections Framework provides a set of interfaces and classes for storing and manipulating groups of data as a single unit, a collection.
  • The framework provides a convenient API to many of the abstract data types maps, sets, lists, trees, arrays, hashtables, and other collections.
  • Because of their object-oriented design, the Java classes in the Collections Framework encapsulate both the data structures and the algorithms associated with these abstractions.
  • With the Java Collections Framework the programmer easily define higher level data abstractions, such as stacks, queues, and thread safe collections.
Читайте также:  Python отследить нажатие мыши

java.util package contains Java Collections Framework classes as follows.

Java Collections Framework Classes

AbstractCollection

The AbstractCollection class provides a skeletal implementation of the Collection interface, to minimize the effort required to implement this interface.

AbstractList

The AbstractList class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a «random access» data store (such as an array).

AbstractMap

The AbstractMap class provides a skeletal implementation of the Map interface, to minimize the effort required to implement this interface.

AbstractQueue

The AbstractQueue class provides skeletal implementations of some Queue operations.

AbstractSequentialList

The AbstractSequentialList class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a «sequential access» data store (such as a linked list).

AbstractSet

The AbstractSet class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface..

ArrayDeque

The ArrayDeque class Resizable-array implementation of the Deque interface.

ArrayList

The ArrayList class Resizable-array implementation of the List interface.

Arrays

The Arrays class contains various methods for manipulating arrays (such as sorting and searching).

Collections

The Collections class consists exclusively of static methods that operate on or return collections.

EnumMap

The EnumMap class A specialized Map implementation for use with enum type keys.

EnumSet

The EnumSet class A specialized Set implementation for use with enum types.

HashMap

The HashMap class Hash table based implementation of the Map interface.

HashSet

The HashSet class implements the Set interface, backed by a hash table (actually a HashMap instance).

HashTable

The HashTable class implements a hash table, which maps keys to values.

IdentityHashMap

The IdentityHashMap class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values).

LinkedHashMap

The LinkedHashMap class Hash table and linked list implementation of the Map interface, with predictable iteration order.

LinkedHashSet

The LinkedHashSet class Hash table and linked list implementation of the Set interface, with predictable iteration order.

LinkedList

The LinkedList class Doubly-linked list implementation of the List and Deque interfaces.

PriorityQueue

The PriorityQueue class An unbounded priority queue based on a priority heap.

TreeMap

The TreeMap class A Red-Black tree based NavigableMap implementation.

TreeSet

The TreeSet class A NavigableSet implementation based on a TreeMap.

Vector

The Vector class implements a growable array of objects.

WeakHashMap

The WeakHashMap class Hash table based implementation of the Map interface, with weak keys.

Internationalization I18N Supported Classes in Java

Create application that can be adapted to different languages and regions is known as Internationalization I18N. Which provides support for various countries, various languages and various currency formates without performing any change in the application.

Internationalization is also abbreviated as I18N because there are total 18 characters between the first letter ‘I’ and the last letter ‘N’.

Internationalization I18N Supported Classes in Java as follows.

  1. Locale : A Java Locale class represents a specific geographical, political, or cultural region.
  2. Locale.Builder : Builder is used to build instances of Locale from values configured by the setters.
  3. ResourceBundle : Resource bundles contain locale-specific objects.

ServiceLoader Class in Java

A facility to load implementations of a service. A service is a well-known interface or class for which zero, one, or many service providers exist. A service provider (or just provider) is a class that implements or subclasses the well-known interface or class.

Properties Class in Java

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

HTML5 Tutorial How to store byte array in SQL Server using Java what is coronavirus covid-19 Java byte Array Python Keywords Java Collections Framework Java Basics Java double Array Java JDBC Tutorial - Java Database Connectivity Python Data Types How to store byte array in MySQL using Java 9 Best Father’s Day 2023 Gifts The Python Tutorial Father Java Arrays Happy Father HTML5 Tags Tutorial

© 2010 — 2023 HudaTutorials.com All Rights Reserved.

Источник

Java util package import

Как правило, в Java классы объединяются в пакеты. Пакеты позволяют организовать классы логически в наборы. По умолчанию java уже имеет ряд встроенных пакетов, например, java.lang , java.util , java.io и т.д. Кроме того, пакеты могут иметь вложенные пакеты.

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

Чтобы указать, что класс принадлежит определенному пакету, надо использовать директиву package , после которой указывается имя пакета:

Как правило, названия пакетов соответствуют физической структуре проекта, то есть организации каталогов, в которых находятся файлы с исходным кодом. А путь к файлам внутри проекта соответствует названию пакета этих файлов. Например, если классы принадлежат пакету mypack, то эти классы помещаются в проекте в папку mypack.

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

Например, создадим в папке для исходных файлов каталог study . В нем создадим файл Program.java со следующим кодом:

package study; public class Program < public static void main(String[] args) < Person kate = new Person("Kate", 32); kate.displayInfo(); >> class Person < String name; int age; Person(String name, int age)< this.name = name; this.age = age; >void displayInfo() < System.out.printf("Name: %s \t Age: %d \n", name, age); >>

Директива package study в начале файла указывает, что классы Program и Person, которые здесь определены, принадлежат пакету study.

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

Для компиляции программы вначале в командной строке/терминале с помощью команды cd перейдем к папке, где находится каталог study.

Например, в моем случае это каталог C:\java (то есть файл с исходным кодом расположен по пути C:\java\study\Program.java).

Для компиляции выполним команду

После этого в папке study появятся скомпилированные файлы Program.class и Person.class. Для запуска программы выполним команду:

Компиляция пакетов в Java

Импорт пакетов и классов

Если нам надо использовать классы из других пакетов, то нам надо подключить эти пакеты и классы. Исключение составляют классы из пакета java.lang (например, String ), которые подключаются в программу автоматически.

Например, знакомый по прошлым темам класс Scanner находится в пакете java.util , поэтому мы можем получить к нему доступ следующим способом:

java.util.Scanner in = new java.util.Scanner(System.in);

То есть мы указываем полный путь к файлу в пакете при создании его объекта. Однако такое нагромождение имен пакетов не всегда удобно, и в качестве альтернативы мы можем импортировать пакеты и классы в проект с помощью директивы import , которая указывается после директивы package:

package study; import java.util.Scanner; // импорт класса Scanner public class Program < public static void main(String[] args) < Scanner in = new Scanner(System.in); >>

Директива import указывается в самом начале кода, после чего идет имя подключаемого класса (в данном случае класса Scanner).

В примере выше мы подключили только один класс, однако пакет java.util содержит еще множество классов. И чтобы не подключать по отдельности каждый класс, мы можем сразу подключить весь пакет:

import java.util.*; // импорт всех классов из пакета java.util

Теперь мы можем использовать любой класс из пакета java.util.

Возможна ситуация, когда мы используем два класса с одним и тем же названием из двух разных пакетов, например, класс Date имеется и в пакете java.util , и в пакете java.sql . И если нам надо одновременно использовать два этих класса, то необходимо указывать полный путь к этим классам в пакете:

java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date();

Статический импорт

В java есть также особая форма импорта — статический импорт. Для этого вместе с директивой import используется модификатор static :

package study; import static java.lang.System.*; import static java.lang.Math.*; public class Program < public static void main(String[] args) < double result = sqrt(20); out.println(result); >>

Здесь происходит статический импорт классов System и Math. Эти классы имеют статические методы. Благодаря операции статического импорта мы можем использовать эти методы без названия класса. Например, писать не Math.sqrt(20) , а sqrt(20) , так как функция sqrt() , которая возвращает квадратный корень числа, является статической. (Позже мы рассмотрим статические члены класса).

То же самое в отношении класса System: в нем определен статический объект out , поэтому мы можем его использовать без указания класса.

Источник

Оцените статью