Module: (Java) Variables. Output formats


Problem

6/7

Output specifiers

Theory Click to read/hide

*** Advanced material (printf() in Java)***

How to output the value of a variable on the screen?
For this, inside the format string in the output operator, you must specify a certain template, in the place of which the variable value will be outputed.
Which format specifier to use depends on the type of variable.
These patterns are called output format specifiers and are presented in the table. A large enough quantity is given by the specifier. Remembering all of them is optional.
In most cases, we will use qualifiers to output integers, real numbers, as well as characters and strings. But you can return to this lesson at any time and see the format specifier you need.

Here’s a quick summary of the available printf format specifiers:

%c character
%d decimal (integer) number (base 10)
%e exponential floating-point number
%f floating-point number
%i integer (base 10)
%o octal number (base 8)
%s a string of characters
%u unsigned decimal (integer) number
%x number in hexadecimal (base 16)
%% print a percent sign
\% print a percent sign

Additions:
To output variables of type short int, the h specifier is used (for example, \(\%hd\))
To output the values of variables of type long int, the l specifier is used (for example, \(\%ld\))
The specifier L can be used as a prefix before the specifiers e, f, g. It means that the screen outputs a value of type long double. (eg, \(\%Lf\))

Try it in practice!

 

Problem

This is an optional task for those who want to learn more about the Java-output operator.

Let's analyze a program that outputs various values on the screen
public class Main {
    public static void main(String[] args) {
            int a=5;
            System.out.printf("Number is %d!\n", 10);   //instead of the %d pattern, the value 10 is substituted 
            System.out.printf("Number is %d!", a);      //instead of the template %d, the value of the variable a is substituted 
        }
}
1. Run the program, see what it displays. Do not pay attention to the fact that you have not passed the test. We will fix the program now.

2. In the 4th line, instead of the number 10, write the arithmetic expression 10 + a. The computer itself will calculate the result and output the result. Run the program, make sure that the test is 100% passed