Package main java lang

The java.lang package. General information. Overview of classes and interfaces

The java.lang package is the main package used to develop Java programs. The package contains the most widely used interfaces and classes, without which it is impossible to write a program in Java.

This package is automatically imported into all programs. Therefore, in order to access the tools of a package, it is not necessary to include this package in the program using the line

import java.lang.*;

The package includes tools for expanding the capabilities of primitive data types, constituent elements of the language, working with strings, streams, and more.

2. The java.lang package classes

The java.lang package contains the following classes:

  • Boolean – wrapper class (wrapper class) for the boolean type;
  • Byte – a wrapper class for the byte type;
  • Character – a wrapper class for the char type;
  • Character.Subset – defines specific character sets of the Unicode set;
  • Class – encapsulates the runtime state of a class or interface;
  • ClassLoader – defines an object that is responsible for the order of loading classes;
  • ClassValue – used to associate a value with a type;
  • Compiler – provides the creation of environments in which the bytecode is compiled into the executive code;
  • Double – a wrapper class for the double type;
  • Enum – a class that serves as a superclass for all enumerations in the program;
  • Float – a wrapper class for the float type;
  • InheritableThreadLocal – designed to create local variables of threads of execution that can be inherited;
  • Integer – wrapper class for int type;
  • Long – a wrapper class for the long type;
  • Math – contains functions and constants for performing mathematical calculations on numeric types;
  • Number is an abstract superclass for the classes Byte , Short , Integer , Long , Float , Double ;
  • Object – the superclass for all Java classes;
  • Package – contains information about the package version;
  • Process – a class that encapsulates a process. The process is the executable program;
  • ProcessBuilder – provides one of the ways to start processes (programs) and manage them;
  • ProcessBuilder.Redirect – encapsulates the source or destination of the I/O that is associated with the process;
  • Runtime – encapsulates the runtime environment;
  • RuntimePermission – provides a security mechanism in Java;
  • SecurityManager – provides a subclass inheritance mechanism for creating a security manager;
  • Short – a wrapper class over the short type;
  • StackTraceElement – is intended to describe an individual element of the stack trace;
  • StrictMath – provides a set of methods for performing mathematical calculations with increased accuracy;
  • String – a class containing tools for working with immutable character strings;
  • StringBuffer – defines a mutable string (as opposed to String );
  • StringBuilder – defines a mutable string. Objects of type StringBuilder are not safe for use in many threads, in which case it is better to use StringBuffer ;
  • System – defines a set of useful static methods and variables;
  • Thread – designed to create a new thread of execution;
  • ThreadGroup – used to create a group of threads of execution;
  • ThreadLocal – used to create local variables for threads of execution;
  • Throwable – a class that is a superclass for all exception classes;
  • Void – contains a field that stores a reference to an object of the Class type for the void type.
Читайте также:  Php include files root
3. The interfaces of java.lang package

The java.lang package defines a number of basic interfaces:

  • Appendable – designed to implement methods for adding characters or character sequences to objects;
  • AutoCloseable – provides support for the try statement with resources (automatic resource management);
  • CharSequence – defines methods that give read-only access to character sequences;
  • Cloneable – used in classes where you need to perform bitwise copying of objects (cloning);
  • Comparable – provides comparison of objects of classes according to some criterion. Used in methods of sorting (ordering) objects;
  • Iterable – for a set of objects, provides a for loop implementation in the for each style;
  • Readable – provides the use of an object as a source for reading characters;
  • Runnable – used for implementation in the class of the thread of execution;
  • Thread.UncaughtExceptionHandler – implemented by classes that need to handle unhandled exceptions.

Источник

Package main java lang

Как правило, в 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() , которая возвращает квадратный корень числа, является статической. (Позже мы рассмотрим статические члены класса).

Читайте также:  Java map class to object

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

Источник

How do I run a Java class in a package?

If you put the source in an appropriate directory hierarchy matching the package name ( D:\javaTest\java\java\package1\App1.java ), and compile/run from the root of the hierarchy ( D:\javaTest ), you wouldn’t have this problem:

D:\javaTest>javac java\java\package1\App1.java D:\javaTest>java java.java.package1.App1 App2 hello world. 

You can also compile using the -d option so that the classes are moved into such a directory hierarchy:

javac -d . App2.java java java.java.package1.App2 

Note you shouldn’t use a package name starting with java , and later versions of the JDK will throw a SecurityException. See this question for more information.

In addition to what Chuck Norris said: When you compile and you’re at the root of the directory hierarcy, you must use / instead of . . When you run the program, it’s reversed: use . instead of / .

You create a new directory. This is the directory containing your work, and is not the start of your packages.

For instance, I create folder /terri to start.

I then create the folder structure /clarie/andrea under it. My package is going to be called claire.andrea in this example. Normal package names start with com and then a company name or something like that (or java for standard java packages, so don’t use that: like java.lang.*).

In the andrea folder, I create a java file called Saluton.java with the class Saluton (which just print hello). The class name and the filename must match.

To compile, from the terri/ folder: javac .\claire\andrea\Saluton.java This will create a Saluton.class in the \terri\claire\andrea\Saluton.class

To run: (again from /terri), I do: java -cp . claire.andrea.Saluton Which says, use class path from my current directory.
My main program is in the package claire.andrea and the Class name is Saluton.

Here’s the run: \terri java -cp . claire.andrea.Saluton

To sum it up, the package name much match the underlying directory structure. The file (if it references a package) must live inside the directory stucture it is refering. If I compile Saluton.java in /terri with package claire.andrea I have not found a way to run it, it does compile fine.

Also, the filename for the class must match the public class in that file.

To run, package.Class. In general, packages are not capitalized and Classes are.

Источник

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