About system out println in java

What is System, out, println in System.out.println() in Java [duplicate]

System is a built-in class present in java.lang package. This class has a final modifier, which means that, it cannot be inherited by other classes. It contains pre-defined methods and fields, which provides facilities like standard input, output, etc.

out is a static final field (ie, variable)in System class which is of the type PrintStream (a built-in class, contains methods to print the different data values). static fields and methods must be accessed by using the class name, so ( System.out ).

println() is a public method in PrintStream class to print the data values. Hence to access a method in PrintStream class, we use out.println() (as non static methods and fields can only be accessed by using the refrence varialble)

In another page i find another contrasting definition as

System.out.print is a standard output function used in java. where System specifies the package name, out specifies the class name and print is a function in that class.

I am confused by these. Could anybody please exactly tell me what they are?

I think the first explanation is somewhat clearer, and you can always browse the source to see for yourself, e.g. public final static PrintStream out = nullPrintStream();

@Less The second explanation is wrong, since System is a class, not a package and out is a field, not a class.

Читайте также:  Два foreach в одном php

3 Answers 3

System is a final class from the java.lang package.

out is a class variable of type PrintStream declared in the System class.

println is a method of the PrintStream class.

Whenever you’re confused, I would suggest consulting the Javadoc as the first place for your clarification.

From the javadoc about System , here’s what the doc says:

public final class System extends Object The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array. Since: JDK1.0 
public static final PrintStream out The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user. For simple stand-alone Java applications, a typical way to write a line of output data is: System.out.println(data) 

Источник

System.out.println

Java-университет

System.out.println - 1

С чего начинается изучение языка программирования? С написания первой программы. Традиционно первая программа называется “Hello world”, и весь её функционал состоит из вывода на консоль фразы “Hello world!”. Такая простая программа дает возможность новому программисту почувствовать, что что-то да заработало.

“Hello world” на разных языках программирования

 begin writeln ('Hello, world.'); end. 
 static void Main(string[] args)
 public static void main(String[] args)
  • Pascal — writeln ;
  • C — printf ;
  • C# — System.Console.WriteLine ;
  • Java — System.out.println .

Подробнее о выводе на консоль в Java

Как вы уже поняли, чтобы вывести текст на консоль, в Java необходимо воспользоваться командой System.out.println() . Но что значит этот набор символов? Для тех, кто знаком с языком Java и основными терминами ООП (для студентов, которые прошли курс JavaRush примерно до 15 уровня), ответ очевиден: “Для вывода текста на консоль мы обращаемся к статическому полю out класса System , у которого вызываем метод println() , и в качестве аргумента передаем объект класса String ”. Если для вас смысл сказанного выше туманный, значит, будем разбираться! Данная команда состоит из трех слов: System out println . Каждое из них представляет собой какую-то сущность, которая предоставляет необходимый функционал для работы с консолью. System — сущность (в Java это называется классом), которая выполняет роль “моста”, соединяющего вашу программу со средой, в которой она запущена. out — сущность, которая хранится внутри System . По умолчанию ссылается на поток вывода на консоль. Подробнее о потоках ввода/вывода в Java можно прочитать здесь. println — метод, который вызывается у сущности out, чтобы обозначить способ, с помощью которого информация будет выведена на консоль. Давай разберемся с каждым элементом из этой цепочки подробней.

System

Возвращает значение переменной окружения JAVA_HOME, которая устанавливается в системных настройках ОС. При установке Java ты наверняка с ней сталкивался;

  • out — уже знакомая нам ссылка на сущность потока вывода информации на консоль;
  • in — ссылка на сущность, которая отвечает за чтение вводимой информации с консоли.
  • err — очень похожа out , но предназначена для вывода ошибок.

out

  • print() — вывод переданной информации. В качестве аргументов может принимать числа, строки, другие объекты;
  • printf() — форматированный вывод. Форматирует переданный текст, используя специальные строки и аргументы;
  • println() — вывод переданной информации и перевод строки. В качестве аргументов может принимать числа, строки, другие объекты;
  • Некоторые другие методы, которые нам не интересны в контексте этой статьи.
 Hello World!Hello World!Hello World! 
 Hello World! Hello World! Hello World! 

Для вызова метода у объекта используется знакомый нам оператор “.”. Таким образом, вызов метода println() у сущности out выглядит так:

println

Как и в многих других языках программирования, в Java println — это сокращение от “print line”. Мы уже знаем, что println() — это метод, который необходимо вызвать у сущности out . Если ты новичок в Java и в программировании в целом, то методы — это некий набор команд, которые логически объединены. В нашем случае, println() — это блок команд, который направляет текст в поток вывода и в конце добавляет перевод строки. В Java методы могут получать аргументы. Когда мы вызываем метод, аргументы передаются внутрь круглых скобок.

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

Построим логическую цепочку

  1. Обратиться к сущности, которая способна соединить наше приложение и консоль — System ;
  2. Обратиться к потоку вывода на консоль — System.out ;
  3. Вызвать метод, который записывает информацию на консоль — System.out.println ;
  4. Передать текст, который необходимо записать — System.out.println(“Hello World!”);

Подведем итоги

Обычный вывод информации на консоль в Java запускает целую цепочку обращения к различным объектам и методам. Понимание того, что происходит во время вызова самой используемой команды в Java, делает нас немного ближе к статусу Джава-Гуру!

Источник

Formatting

Stream objects that implement formatting are instances of either PrintWriter , a character stream class, or PrintStream , a byte stream class.

Note: The only PrintStream objects you are likely to need are System.out and System.err . (See I/O from the Command Line for more on these objects.) When you need to create a formatted output stream, instantiate PrintWriter , not PrintStream .

Like all byte and character stream objects, instances of PrintStream and PrintWriter implement a standard set of write methods for simple byte and character output. In addition, both PrintStream and PrintWriter implement the same set of methods for converting internal data into formatted output. Two levels of formatting are provided:

  • print and println format individual values in a standard way.
  • format formats almost any number of values based on a format string, with many options for precise formatting.

The print and println Methods

Invoking print or println outputs a single value after converting the value using the appropriate toString method. We can see this in the Root example:

Here is the output of Root :

The square root of 2 is 1.4142135623730951. The square root of 5 is 2.23606797749979.

The i and r variables are formatted twice: the first time using code in an overload of print , the second time by conversion code automatically generated by the Java compiler, which also utilizes toString . You can format any value this way, but you don’t have much control over the results.

The format Method

The format method formats multiple arguments based on a format string. The format string consists of static text embedded with format specifiers; except for the format specifiers, the format string is output unchanged.

Format strings support many features. In this tutorial, we’ll just cover some basics. For a complete description, see format string syntax in the API specification.

The Root2 example formats two values with a single format invocation:

The square root of 2 is 1.414214.

Like the three used in this example, all format specifiers begin with a % and end with a 1- or 2-character conversion that specifies the kind of formatted output being generated. The three conversions used here are:

  • d formats an integer value as a decimal value.
  • f formats a floating point value as a decimal value.
  • n outputs a platform-specific line terminator.

Here are some other conversions:

  • x formats an integer as a hexadecimal value.
  • s formats any value as a string.
  • tB formats an integer as a locale-specific month name.

There are many other conversions.

Except for %% and %n , all format specifiers must match an argument. If they don’t, an exception is thrown.

In the Java programming language, the \n escape always generates the linefeed character ( \u000A ). Don’t use \n unless you specifically want a linefeed character. To get the correct line separator for the local platform, use %n .

In addition to the conversion, a format specifier can contain several additional elements that further customize the formatted output. Here’s an example, Format , that uses every possible kind of element.

3.141593, +00000003.1415926536

The additional elements are all optional. The following figure shows how the longer specifier breaks down into elements.

Elements of a Format Specifier.

The elements must appear in the order shown. Working from the right, the optional elements are:

  • Precision. For floating point values, this is the mathematical precision of the formatted value. For s and other general conversions, this is the maximum width of the formatted value; the value is right-truncated if necessary.
  • Width. The minimum width of the formatted value; the value is padded if necessary. By default the value is left-padded with blanks.
  • Flags specify additional formatting options. In the Format example, the + flag specifies that the number should always be formatted with a sign, and the 0 flag specifies that 0 is the padding character. Other flags include — (pad on the right) and , (format number with locale-specific thousands separators). Note that some flags cannot be used with certain other flags or with certain conversions.
  • The Argument Index allows you to explicitly match a designated argument. You can also specify < to match the same argument as the previous specifier. Thus the example could have said: System.out.format("%f, %

Источник

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