JavaRush /Java Blog /Random EN /Methods in Java

Methods in Java

Published in the Random EN group
There is one interesting principle that many have heard about. It's called "Divide and Conquer." This principle is used in many areas of human life, for example, in politics. It denotes the division of a large number of heterogeneous parts in the state, inciting and using hostility between these parts. In other words: create conflict between those who potentially pose a threat to power. But we are programmers, so we are only interested in the technical interpretation of this principle. And it goes like this: “The principle of “Divide and Conquer” is to break a large problem into smaller ones until they become elementary. Then you need to solve them sequentially and combine everything into one whole system. This program should solve the given problem” That is, you simply break a large problem into smaller ones, which are not a problem for you to solve. And then you collect the solution into one big one. To follow this simple and useful principle, Java programming uses methods. Methods in Java - 1For example, we are creating a robot boxer. It is important for us that he moves well, carries out accurate strikes, and also watches the enemy in search of weak points. It would be awkward to write all this in one main method , wouldn't it? If we describe everything in one method, it will be something like this:
метод main() {
// Описание действий шага вперед
подача напряжения в отдельные модули;
поднятие ноги;
перевод в другую точку;
поставить ногу;
перенести вес на другую ногу;
если (противникАтакует()) {
        	// Описание действий уклонения робота.
        	...
} еслиНет {
        	// Описание действий обманного атакующего удара.
        	...
}
// Описание действий шага назад
...
}
What if we need to use a step forward or kick elsewhere in the program? Describe all the actions again? Doesn't fit. There are too many repeated lines that are easy to get lost in. We need to place the description of the details of the action in a separate module, which will perform the robot step. And we can call the method in one line. Something like this:
метод шагВперед() {
// Описание действий шага вперед
  	подача напряжения в отдельные модули;
  	поднятие ноги;
  	перевод в другую точку;
  	поставить ногу;
  	перенести вес на другую ногу;
}

метод уклонение() {
  	// Действия для уклонения
  	...
}

метод обманныйАтакующийУдар() {
  	// Действия для удара
  	...
}

метод шагНазад() {
  	// Действия для шага назад
  	...
}

метод противникАтакует() {
	// Робот проверяет атакует ли противник
}

метод main() {
	шагВперед();
	если (противникАтакует()) {
        	уклонение();
	} еслиНет {
  	  обманныйАтакующийУдар();
	}
	шагНазад();
}
Now we have separated robot functionality, as well as a compact and clear main() method . The rest of the methods can also be divided into any functionality, for example, deceptiveAttackingStrike can be divided into methods deceptiveMovement , Leg movement , attack . And they, in turn, are assigned to simpler tasks in order to ultimately get a set of elementary ones. Okay, now let’s write it all beautifully in a form that Java will accept.
public static void stepForward() {
  	    // Многострочный code, описывающий
  	    // действия робота для выполнения шага
  	    System.out.println("The robot takes a step forward");
}

public static void evasion() {
  	    // Действия для уклонения
  	    System.out.println("Robot shy of impact");
}

public static void deceptiveAttackBlow() {
  	    // Действия для удара
  	    System.out.println("The robot performs a deceptive strike");
}

public static void stepBack() {
  	    // Действия для шага назад
  	    System.out.println("The robot takes a step backwards");
}

public static void main(String[] args) {
    	stepForward();
    	if (isEnemyAttacked()) {
        		evasion();
    	} else {
  	    	deceptiveAttackBlow();
    	}
    	stepBack();
}

public static boolean isEnemyAttacked() {
    	// Метод проверяет, атакует ли враг. returns логическое meaning.
    	return true;
}
I understand that this code may be a little unclear to you now, especially some words like void , return and so on. Don’t rush to throw tomatoes, I’ll explain everything now. The general idea of ​​the “Divide and Conquer” paradigm should be clear to you. Methods will help us with this. The general structure of method declarations is as follows:
модификатор_доступа возвращаемое_meaning Name_метода(принимаемые_параметры) {
   	//Тело метода
}

Access modifier

The access modifier is several keywords: public , private , package . These words indicate the scope of the method. I’ll explain it simply: with this word you seem to be sharing a tasty treat with others. Yummy is your method. If it's private , you don't share the method with other classes. If package , you only share with classes within the package (classes are collected into specific packages, you'll learn this later). Well, public shows that you are kindness itself and share a delicious treat (method) with the entire program. Something like this. After a few levels you will understand the role of these words much better.

Return value

Look at the example above: all methods are marked with the void keyword , except for one - isEnemyAttacked , which returns a boolean value . If a method is marked void , it may not return anything. This method simply performs a set of actions and that’s it. Now pay attention to the main method . Those methods that return void are called just like that, in the body of the method. But the isEnemyAttacked method is called within the parentheses of the if statement . Due to the fact that it returns a boolean value, we get the opportunity not to use an intermediate variable, but to insert it directly. Returning a value occurs using the return keyword . If a method returns type int , we can call the method from any expression:
public static int getNumber() {
 	    return 5;
}

public static void main(String[] args) {
    	int result = 5 + 6 + getNumber();
    	System.out.println(result);
}
Conclusion:
16
The getNumber method returns an int value , so we can call it from an expression. Also, the method can return any type, including ones you created yourself. If you specified a return type for a method, then you must return something. You can't write it like this:
public static int findMaxNumber(int a, int b) {
 	if(a>b) {
 	    return a;
 	}
}
The compiler will scold you that when the first condition is met, you return something, but when the second condition is met, you do not.

Passing parameters

You can pass parameters to the method that are used during its operation. The most primitive example is the summation of two numbers. But we're not primitive, right? Let's take another example, quite stereotypical. Let's say we have a method chef() - cook. We can pass the soup ingredients to this method in the parameter block, and as a result, this method returns the soup to us. Like this:
public static void main(String[] args) {
    	String[] ingredients;
    	// Инициализация массива ингредиентов
    	Soup soup = chef(ingredients);

}

public static Soup chef(String[] ingredients) {
    	Soup soup = new Soup();
    	// Процесс варки супа
    	return soup;
}
(Let's say we have a pre-created Soup class ) In the main method, we create an array of ingredients and then “give it to the chef” (pass it to the chef method ). “The cook makes the soup” and then returns it to us as an object of the Soup class . Everything is very simple. You can pass any parameters, primitive types, objects, arrays, and so on to the method.

Passing parameters by reference and by value

In the Java programming language, any parameters are passed to a method by their value. However, this mechanism is different for primitive types and for objects. If you pass any primitive type into a method and change it, it will not change in the main method. You simply passed a copy of the value, and the original variable was preserved. The simplest example:
public static void main(String[] args) {
    	int x = 1;
    	System.out.println(x);
    	getNumber(x);
    	System.out.println(x);

	}

	public static void getNumber(int i) {
    	i = i + 100;
	}
Conclusion:
eleven
However, in the case of objects, changes affect the original object:
public class Program
{
	public static void main(String[] args) {
    	WiseMan wiseMan = new WiseMan();
    	wiseMan.setIq(300);
    	System.out.println(wiseMan);
    	changeObject(wiseMan);
    	System.out.println(wiseMan);

	}

	public static void changeObject(WiseMan m) {
    	m.setIq(100);
	}
}

public class WiseMan {
	int iq;

	public void setIq(int iq) {
    	this.iq = iq;
	}

	public int getIq() {
    	return iq;
	}

	public String toString() {
    	return "Our wise man has an IQ "+iq;
	}
}
Conclusion:
Our wise man has an IR 300 Our wise man has an IR 100
We have a WiseMan class that has an iq property . And two methods that control the value of this field. In the main method we create a wiseMan object , set the iq value to 300 . Then we pass our sage with iq 300 to the changeObject method. But in this method he becomes stupid. We set the value of iq to 100. Then in the main method we print the object. You can see that in the changeObject method we are manipulating another sage in the m variable . However, we are modifying our original object. The fact is that the wiseMan object in the main method and the m object in the changeObject method are the same wise man, and a reference to the object is copied into the method as a parameter. Keep this in mind when you edit an object in individual methods.

Finally, a few words about the static modifier

In general, a few words will not do here, but I will try. Regular methods not marked with this modifier belong to the class object. And static methods belong to the class itself. Conventional methods can be used on individual objects. Look at the WiseMan class from the example above. Each sage will have his own getIq and setIq methods , because everyone’s IQ level is different. If we add a static method generateAWisePhrase to this class , then we can call such a method without an object:
WiseMan.generateAWisePhrase();
In general, this information is enough for now, because several lectures can be written about static . Follow a few rules when writing a method to maintain order in your code:
  • Give your methods meaningful names so that it is clear what they do.
  • Try not to write very long methods. The optimal length is 8-15 lines.
  • The number of method parameters should not exceed 4-5.
  • If you have similar functionality twice in your code, think: maybe it’s worth generalizing it and putting it into a separate method?
These techniques will help you improve the performance of your program and, most importantly, make your code more readable.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION