Formatting
Stream objects that implement formatting are instances of either PrintWriter , a character stream class, or PrintStream , a byte stream class.
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 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:
Here is the output:
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.
Here's the output:
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:
Java 8 | Print and Println Method + \t
Print/Println — The methods that display the text on the console.
Hi y’all! It’s been a while to post something that’s not a practice session! Today I’m going to explain the different way to print things on the console.
[Println()]
This is the basic printing method we’ve been using, and as we all know, it moves the cursor to the next line after printing the result.
On the example above, it printed “Hi.” and then moved it’s cursor to the next line and printed “It’s Student Kim.”
[Print()]
On the other hand, print method retain cursor at the end of the same line of the former text.
Like this, you can see them printed on the same line. If I use this method to print 0 to 10 with the for loop, it will be printed like below.
When you want some gap between the numbers you can just put some space that are enclosed in the double quotes, or you can also use the “\t”. \ is the backslash, so don’t get confused with the normal slash / . The backslash is usually located above the Enter key.
Ta-da! Now there’s a gap between the numbers! When you use \t, it should be enclosed in the double quotes. Now let’s move to solve a practice question of it!
Question) Print the multiplication table like below.
We’ve already done the multiplication tables, but this time we have to make the tables printed next to each other. If you haven’t been practiced generating multiplication table, checkout my last post!
Java 8 | Nested Loop Practice — Multiplication Table
Nested Loop — If there’s a loop inside of another loop, it’s called nested loop.
The answer of this question is right on below.
I put the nested loop, and the variable i in the first loop goes from 1 to 9, and the j in the second loop goes from 2 to 9. So when the variable i is 1, j will be started from 2 and ended with 9. So on the first line, j*i will be 2*1 , 3*1 , 4*1 , 5*1 , 6*1 , 7*1 , 8*1 , 9*1 . On the next line i will get bigger. you see?
I hope you could solve this question by yourself, Cause I’ll give you some of the advanced practice questions on our next session! Well done today guys. See ya!
Вывод на экран
Тело метода состоит из команд . Можно даже сказать, что метод — это команды , объединенные в группу, которой дали имя (имя метода). И так, и так будет верно.
Команды бывают разные. В языке Java есть команды на все случаи жизни. Каждая команда описывает какое-то определенное действие. В конце каждой команды ставится точка с запятой .
| Команда | Описание (что делает) |
|---|---|
| Выводит на экран число: | |
| Выводит на экран надпись: | |
| Выводит на экран надпись: |
На самом деле это одна команда – System.out.println . А в круглых скобках в нее передаются параметры . В зависимости от значений параметров, одна команда может выполнять разные действия. Это очень удобно.
В Java размер имеет значение: имеет значение, большими или маленькими буквами написаны команды. Команда S ystem.out.println() работать будет , а s ystem.out.println() — нет .
Если вы хотите вывести на экран текст, его нужно с двух сторон обозначить двойными кавычками .
Одинарная кавычка выглядит вот так ‘ , а двойная — вот так » . Двойная кавычка — это не две одинарных: просьба не путать.
Двойная — это та, которая рядом с кнопкой Enter . На ней еще обычно находится русская буква Э .
2. Отличия println() и print()
Есть две вариации команды вывода на экран: System.out. println () и System.out. print ()
Если вы пишете команду System.out. println () несколько раз, каждый раз переданный в нее текст будет выводиться с новой строки . Если System.out. print () , текст будет выводиться на той же строке . Пример:
| Команды | Что выведется на экран |
|---|
Небольшое примечание. Команда println() не выводит текст с новой строки – она выводит текст на текущей строке, но делает так, чтобы следующий текст выводился с новой строки.
Команда println() выводит на экран текст и затем добавляет специальный невидимый символ перевода строки , в результате чего следующий текст будет отображаться с начала новой строки .
Так будет выглядеть полностью написанная программа вместе с объявлением класса Amigo и методом main . Внимание на экран:
Чем отличаются команды print и println
In Java, we have the following functions to print anything in the console.
- System.out.print() and
- System.out.println()
But there is a slight difference between both of them, i.e.
System.out.println() prints the content and switch to the next line after execution of the statement whereas
System.out.print() only prints the content without switching to the next line after executing this statement.
The following examples will help you in understanding the difference between them more prominently.