A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.


"Are you already here, Amigo? I know you have already learned a lot of Java commands. You've almost reached my level!"

"Is that true, Diego?"

"Of course not, ha-ha. You still have lots of studying and learning to do. Still, you already know enough to write fairly complex programs. 10, 20, 30 lines of code in a program is not a very big program, right?"

"I guess you're right. Especially if you put curly braces on separate lines."

"But a program of 100+ lines, now that's big. Even us robots have quite a difficult time understanding such code. What do you think, is there anything you can do to somehow simplify writing and reading programs that have a lot of code?

"I sincerely hope so!"

"Your hopes are not in vain. It is possible to simplify programs, and methods are here to help us with this. They are sometimes called functions.

"Functions, methods... Uh, what are they?"

"Putting it very simply, a method is a group of commands that has a unique name. In other words, we just put several commands into one group and give it a unique name. And that's it — boom — we have a method. Most often, these commands are grouped according to some rationale in order to solve a small and specific task. For example, 'a method for printing lines from a file'. Or 'a method for raising a number to an exponent'.

"So, we split the program into methods?"

"Yes, and it simplifies the code.

Example:

Without a method With a method
class Solution
{
   public static void main(String[] args)
   {
     System.out.print("Wi-");
     System.out.println("Fi");
     System.out.print("Wi-");
     System.out.println("Fi");

     System.out.print("Wi-");
     System.out.println("Fi");
   }
}
class Solution
{
   public static void main(String[] args)
   {
     printWiFi();
     printWiFi();
     printWiFi();
   }
   public static void printWiFi()
   {
     System.out.print("Wi-");
     System.out.println("Fi");
   }
}

"In the program in the left column, we repeat the same code three times — we did this intentionally to illustrate a point. But in the program on the right, we moved the repeated code into a separate method and gave it a unique name — printWiFi.

And instead of the relocated code, we call the printWiFi() method 3 times.

"When the program in the column on the right is run, each time the printWiFi() method is executed, all the commands inside the printWiFi() method are executed. We just created a new command (method), combining several commands into a single group.

"Any code can be split into separate methods. This is done to simplify things: the idea is that it is better to have many small methods than one large one.

"It's a great idea to split a program into methods.

"Soon you'll recall with wonder how you used to write programs without making your own methods."

"I'm ready to listen and attempt to write methods! Just tell me how to do it."

Declaring a method in Java

"How can we declare the simplest method? Here's how:

public static void name()
{
  method body
}

Where name is the unique name of the method and method body represents the commands that make up the method. The meaning of the words public, static, and void will be discussed later.

"After we've created a method, we can call it in our other methods. A method call looks like this:

name();

"Where name is the unique name of the method we want to call, i.e. the method whose commands we want to execute when we arrive at the method call.

"When the program reaches the method call, it will simply step into the method, execute all its commands, return to the original method, and continue execution.

"And now, Amigo, look with new eyes at the commands that you have already learned. For example, System.out.println(). Does anything come to mind regarding what this really is?"

"Are you saying that all these commands are just methods written by other programmers?"

"Not all, but many of them. Yes, exactly! Others wrote them to make our lives easier."

"So public static void main(String[] args) is also a method... Now it makes more sense!"

"Of course, it does! It's programming! It turns out that the main method — the alpha and omega of the program — can contain calls to other methods:

Code Note
class Solution
{
   public static void main(String[] args)
   {
     printWiFi10Times();
   }

   public static void printWiFi10Times()
   {
     for (int i = 0; i < 10; i++)
       printWiFi();
   }

   public static void printWiFi()
   {
     System.out.print("Wi-");
     System.out.println("Fi");
   }
}




We call the print10TimesWiFi() method


We declare the print10TimesWiFi method


We call the printWiFi() method 10 in a loop


We declare the printWiFi method

We display "Wi-Fi" on the screen

Facts about methods

"I have set aside some useful facts about methods for you. Here, enjoy:

Fact 1. A method is always part of a class.

A method can only be declared in a class. A method cannot be declared inside another method. A method cannot be declared outside a class.

Fact 2. A method's name has no sacred meaning

It doesn't matter what methods are called — that doesn't affect anything. The main method is a method just like all the others. It's just that this name was chosen for the method from which the Java machine will start execution of the program. There is nothing magical about it. All that said, it is better to choose method names that at least make it a little clear what they are for. I'll talk about this a little later.

Fact 3. The order of methods in a class does not matter

You can write your methods in a class in any order — this will not affect the program's execution in any way. Example:

Code
class Solution
{
   public static void printWiFi10Times()
   {
     for (int i = 0; i < 10; i++)
       printWiFi();
   }
   
   public static void main(String[] args)
   {
     printWiFi10Times();
   }

   public static void printWiFi()
   {
     System.out.print("Wi-");
     System.out.println("Fi");
   }
}
class Solution
{
   public static void printWiFi()
   {
     System.out.print("Wi-");
     System.out.println("Fi");
   }

   public static void printWiFi10Times()
   {
     for (int i = 0; i < 10; i++)
       printWiFi();
   }
   public static void main(String[] args)
   {
     printWiFi10Times();
   }
}

Fact 4. The variables inside one method are not related in any way to the variables of other methods

What happens in Vegas, stays in Vegas. And the variables declared inside a method stay inside the method.

Variables with the same names can be declared in two adjacent methods, and these variables are not related to each other in any way.

Method names

"So... I promised to tell you about method names. It has long been known that the two most difficult problems in programming are choosing the right names for methods and choosing the right names for variables."

"I never thought that was so difficult!"

"You just didn't know much about other's vague code, where variables and methods have arbitrary names. Just try to figure out that code. In fact, almost an entire science has emerged regarding how to correctly name methods. And each programming language has its own standards.

"In Java, it is customary to follow these principles:

Principle 1. A method name should briefly describe what the method does.

Then another programmer reading your code can rely on the name of the method to guess what the code does. He or she won't need to look at the code of called methods every time. And the purpose of the methods is easier to remember.

For example, Thread.sleep() is used to 'put the program to sleep' and Scanner.nextInt() is used to 'read the next integer'. Convenient, huh?

Principle 2. A method name can be multiple words.

However, there are several limitations when doing this:

  • You cannot have spaces in a method name: all words are written together.
  • Each word is capitalized, except for the first.
  • A method name always starts with a lowercase letter

Remember the print10TimesWiFi method. What does that name mean? "Display the word 'WiFi' 10 times". You shouldn't include lots of words in the name of a method: the name should reflect its very essence.

This standard for naming methods is called CamelCase (The uppercase letters are like the humps of a camel).

Principle 3. A method name starts with a verb.

A method always does something, so the first word in a method name is always an action.

Here are some bad names for methods: home, cat, car, train, ...;

Some good names are: run, execute, print, read, write, ...

Principle 4. A method name uses only Latin letters and numbers.

Java has excellent support for different languages. You can write the names of variables, methods and classes in Russian as well as Chinese — everything will work!

But! Imagine how long you would have to study Java, if the System.out.println() method was written in Chinese?

Much longer than now, right? That's the first point.

Second, many software development teams are international. A very large number of Java libraries are used by programmers from all over the world.

Therefore, it is recommended to use only Latin letters and numbers in method names.

Important:

The name of a method must begin with a letter (it cannot begin with a number).

"These are all the basic principles that govern method naming in Java. The lesson is over now. Go solve tasks!"

"I'm already running, Diego!"


A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.


undefined
7
Task
New Java Syntax, level 7, lesson 1
Locked
Separate concepts
The main method prints too many lines of information about various concepts. It would make sense to separate displaying information about hydrogen from displaying information about the island of Java by separating them into different methods. Create a public static void printHydrogenInfo() method, w
undefined
7
Task
New Java Syntax, level 7, lesson 1
Locked
Orderly information
Here is a bad example of using methods: 1. The methods split up a couplet. 2. It's not worth it to wrap a single line of code in a separate method. Rewrite the code so that all text is displayed in the main method, and the rest of the methods are removed. The execution of the program should not chan