The function naming style in Java is the same as the variable naming style: lowerCamelCase. But when choosing the words themselves there is an important difference.
A function is an action, a function call is always similar to the instructions “go,” “take,” “type,” “put” and so on. Recall what features were in previous lessons:
The variable is an entity, so we use nouns:
Adopt the following structure: function — verb, variable — noun.
(We also had a
parentFor function, and this name is not a verb. One could call it
getParentFor, but names like
max are common forms. “Function — verb” — not an iron rule, but it is almost always better to stick with it).
In the lesson about variables, we asked you to come up with the name of the variable and write it in a notebook or send it to your email. Find this title and take a fresh look at it: is it understandable? Describes the essence unequivocally or requires understanding?
The programmer’s life is filled with such moments: open the old code and try to understand it. Be kind to the future yourself and to your colleagues, let the variables and functions have clear names.
Java has an interesting feature
System.out.printf. It prints a string based on a template and data.
System.out.printf("Today is %s %d", "February", 8);
Today is February 8
The first argument in
System.out.printf is a template string, in which, in addition to the text itself, there may be special placeholders. These are “stubs” for information that is passed by the following arguments.
%s means stub for string,
%d for number. Therefore, the following two arguments in our example are a string and a number.
The order and type of values must match the order and type of the stubs.
When displaying dates, it is sometimes necessary to fix the number of digits, say, always write zeros before the number if the number is less than 10.
System.out.printf allows you to solve this problem:
System.out.printf("Today is %s %02d", "February", 8);
Today is February 08
%02d - make two digits and fill the remaining space with zeros.
%03d - three digits, and so on:
System.out.printf("Today is %s %04d", "February", 8);
Today is February 0008
printFormattedBirthday function, which takes three parameters as input: day, month, and year of birth, and returns them as a string in a formatted form, for example:
The day and month must be formatted so that, if necessary,
0 is added to the left. For example, if the month came the number
7, then in the output line it should be represented as
As usual, the function needs to be public static, not just static, so that we can call it from another class.
Please sign in with your GitHub account, this is necessary to track the progress of the lessons. If you do not have an account yet, now is the time to create an account on GitHub.