The concepts of function and method

Lecture



Methods

The concepts of function and method

A function is a part of a program that has its own name. This name can be used in the program as a command (this command is called a function call). When a function is called, the commands of which it consists are executed. A function call can return a value (similar to an operation) and therefore can be used in an expression along with operations.

Functions are used in programming to reduce its complexity:

  1. Instead of writing a continuous sequence of commands in which you soon cease to orient yourself, the program is divided into subroutines, each of which solves a small completed problem, and then a large program is composed of these subroutines (this technique is called decomposition).
  2. The total amount of code decreases because, as a rule, one function is used in the program several times.
  3. Written once and comprehensively tested function, can be included in the library of functions and used in other programs (it does not need to remember how this function was programmed, it is enough to know what it does). There are many useful libraries of functions that can be used by all programmers, and some libraries come bundled with a programming language (for example, everyone who programmed in Pascal used the library function writeln() to display on the screen, and in Java for these purposes the System.out.println() method is available, which is included in one of the standard libraries).

A method is a function that is part of a class that can perform operations on data of this class. In Java, the entire program consists only of classes, and functions can be described only inside them. That is why all functions in Java are methods.

The essence of the concept method is considered in the next lesson. In the meantime, we can use it as a synonym for the familiar (in other programming languages) notions of function.

Method declaration

In order to use your own method in a program, you must declare it.

When declaring a method, you must specify the type of value that will be returned after the method is executed in the program. If the value does not need to be returned, the keyword void is specified. Then comes an arbitrary id - the name of the method. After the name of the method in parentheses indicates the list of parameters (may be empty), and then - in curly brackets - the commands that make up the body of the method.

Parameters are the data that the method needs to work. For example, a method that draws a circle should get the radius and coordinates of the center of the circle. (Of course, it would be possible to develop a method without parameters that draws a circle of unit radius with the center at the origin, but it would be much less useful).

The description of each parameter is similar to the declaration of a variable (type, and then the identifier is the name of the parameter). Parameters are separated by commas.

In the body of the method that returns a value, there must be a return command, after which an expression of the appropriate type is indicated with a space. This command ends the method and passes the specified expression as a return value to the main program - to the place where the method was called from *.

As an example, create a method to calculate the sum of squares of two integers. As in the case of the program, it is important to first determine the input and output data. Input data are method parameters. The output is its return value.

Note: in the object-oriented concept, the emphasis is somewhat different. Methods can get data to work by referring to the attributes of their class, and the result of their work may be to change these attributes. However, in the framework of this section, we consider methods as classical functions - subprograms.

The input data for the method in question will obviously be two integers. The output (result) is an integer representing the sum of their squares.

The simplest version of the method will look like this:

long squearSum(int x, int y) { return x*x + y*y; }

One or more modifier keywords are specified before the return type (which will be studied later). We need to add a static modifier to the declaration of the squearSum() method, since we are going to access it from the main() method that has this modifier.

The description of the squearSum() method must be inside the only class that our simple program consists of, but not inside the main() method, but on the same level as it. I.e:

package mainPack; public class MyClass { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } static long squearSum(int x, int y) { return x*x + y*y; } }

As a result, there are now two methods in the MyClass class, one of which, main() , is executed when the program starts. To execute the second method, it must be called.

Method call

To call a method from another method of the same class, you must specify its name, and then the list of actual parameters in parentheses (if the method does not require parameters, the parentheses are still set).

For example, we can refer to the squearSum () method described by us, passing in two parameters as integers 10 and 20 as follows:

System.out.println(squearSum(10,20)+1);

The number 501 will be displayed in the console.

Note that the method call is used as an operation, which can be combined with other operations (in this case, the sum) in the expression.

To call a method of another class, you must have an object of this class *. The method name is indicated by a period after the object name.

For example, the class String (string) has a length() method that returns the length of the string. This method can only be accessed through an object of the String class (which is quite logical, the method is called for the string whose length we want to know).

String S = "Привет"; // Создание объекта класса String, подробнее см. ниже String S = "Привет"; // Создание объекта класса String, подробнее см. ниже int x = S.length(); // Вызов метода length() для объекта S. В результате x = 6 int x = S.length(); // Вызов метода length() для объекта S. В результате x = 6

More details about calling methods from other classes will be discussed later.

In the future, talking about any methods, we will call them not only by name, but also for clarity, indicate the method parameters in parentheses, for example сharAt(int i) . As a result, it becomes easy to explain the purpose of the method: "The method charAt(int i) returns the character of the string with the index i ." The type of the return value we will specify only when necessary.

Exercise 1

Write a method, toUSD(int rur, double course) , which toUSD(int rur, double course) rubles into dollars at a given rate. Call it twice in the main () method with any parameters, type the result in the console.

Arrays

Definitions

An array is a collection of variables of the same type that have a common name. Each such variable is called an array element. Each element is associated with an integer - an index that is used (along with the name of the array) to refer to it.

Creating an array

Creating an array occurs in two stages.

1. Declaring an array. At this stage, a variable of type reference to the array is created , with which we can then access the array. To do this, specify the type of the elements of the array, then the square brackets (they show that we are dealing with an array, and not with the usual data type) and the identifier is the name of the array. There may be several identifiers (as is the case with variables of simple types).

Examples:

int[] a; // Создается ссылка на массив типа int int[] a; // Создается ссылка на массив типа int double[] b, c; // Создаются две ссылки на массивы типа double double[] b, c; // Создаются две ссылки на массивы типа double

2. Creating an array. Creating an array means allocating enough space in memory to store all its elements. To do this, specify the length of the array - the number of elements in it. In addition, the reference variable declared in the previous step will now “point” not to void (in Java, this “void” is called null), but to a specific array, with elements of which you can work.

The array is created with the new operation, which allocates a chunk of memory and returns a pointer to that chunk. After the keyword new, the data type of the array and its length in square brackets should be specified:

a = new int[5]; // В памяти выделяется место под массив из пяти целочисленных элементов, переменная a будет указывать на этот массив a = new int[5]; // В памяти выделяется место под массив из пяти целочисленных элементов, переменная a будет указывать на этот массив b = new double[4]; // В памяти выделяется место под массив из четырех действительных элементов, на него указывает переменная b b = new double[4]; // В памяти выделяется место под массив из четырех действительных элементов, на него указывает переменная b

In this case, the array elements are assigned default values ​​*. You can immediately initialize the array with the desired values, if you list them separated by commas in curly brackets (the length of the array is not specified):

c = new double[]{2.3, 1.02, 8}; // В памяти выделяется место под массив из трех действительных элементов, на него указывает переменная с, элементы массива сразу получают нужные значения

Work with array

After declaring an array, you can work with it. For example, assign values ​​to array elements and generally treat them as normal variables. To refer to a specific element, you must specify the name of the variable pointing to the array, and its index in square brackets. The numbering of the elements of the array starts from zero.

Examples:

a[0] = 5; // Первому элементу массива a, присваивается значение 5 a[0] = 5; // Первому элементу массива a, присваивается значение 5 a[3] = 17; // Четвертому элементу массива a, присваивается значение 17 a[3] = 17; // Четвертому элементу массива a, присваивается значение 17 a[1] = a[0] – a[3]; // Второму элементу массива a присваивается значение -12 a[1] = a[0] – a[3]; // Второму элементу массива a присваивается значение -12

about fast creation of arrays and features of variables of type "link to array"

The declaration, creation, and initialization of an array can be placed. For example:

int[] a = new int[5];

and even:

int[] a = new int[] {5, -12, 0, 17, 0}; // длина массива не указывается

We emphasize once again that the variables a , b and c are not actually arrays, but only references to arrays. This means that you can force the link to show to another array (if it is of the appropriate type). This is done by the assignment command:

b = c;

As a result of such a command, the variables b and c will refer to (point to) the same array. That is, for example, b[0] and c[0] - this is now the same element. And the array, to which the variable b previously pointed out, is no longer accessible (since no references point to it) and will be removed from memory by the so-called Java garbage collector .

You can assign the reference “empty value” to null and then it will not refer to any memory area:

b = null;

Notice that nothing happens to the array that the variable b pointed to, now you can only access it via the variable c . But if we had assigned null to the variable a , its integer array would have been destroyed.

The length of the array can be determined using the entry:

идентификатор_массива.length

For example, a.length will be 5.

It is very convenient to iterate over all the elements of an array in a for type loop. The following form is usually used:

for (int i = 0; i < a.length; i++) { // здесь можно что-нибудь сделать с элементом a[i] }

For example, the following code assigns numbers from 1 to 4 to all elements of array b (since there are four elements in array b):

for (int i = 0; i < b.length; i++) { b[i] = i; }

It is impossible to go beyond the array. That is, if there are five elements in array a, then accessing the sixth or eighth elements will result in an error (more precisely, the excitation of the exception).

a[5] = 8; // Нельзя, в массиве a только 5 элементов: a[0], a[1], a[2], a[3], a[4]

about multidimensional arrays

Multidimensional arrays

Array elements in Java may be other arrays. For example, you can declare:

char[][] d;

Then the memory area for the external array is allocated:

d = new char[3][];

The size of the internal arrays is not necessary, it is done in the next step:

d[0] = new char[3]; d[1] = new char[3]; d[2] = new char[2];

Now you can refer to the elements of a multidimensional array using two indices: first the index of the external, and then the internal array: d[1][2] , d[0][0] , d[0][1] , etc.

Note that multidimensional arrays in Java do not have to be rectangular (internal arrays can have different lengths).

Exercise 2

Write a method that increases the elements of the array by 10%.

Hint: Think about the input and output data for this method. Decide for yourself whether the method should change the original array, or as a result of the work a new one will be created. Justify your decision to the teacher. Write comments to the method.

Working with strings

Creating strings

Strings are also variables of the reference type, or rather, references to objects from one of several Java string classes. We will look at the String class.

The most common way to create a string is to organize a String reference to a constant string:

String s = "Это строка"

You can simply declare a variable (which will receive a null value), and then force it to refer to a constant string, another string, or use the command new to explicitly allocate memory for the string:

String s1, s2, s3; // Объявление трех переменных, которые пока не связаны ни с какой строкой String s1, s2, s3; // Объявление трех переменных, которые пока не связаны ни с какой строкой s1 = "Да здравствует день танкиста"; // Переменная s1 теперь ссылается на область памяти, в которой хранится строка "Да здравствует день танкиста" s1 = "Да здравствует день танкиста"; // Переменная s1 теперь ссылается на область памяти, в которой хранится строка "Да здравствует день танкиста" s2 = s1; // Теперь обе переменные s1 и s2 ссылаются на одно и то же место памяти s2 = s1; // Теперь обе переменные s1 и s2 ссылаются на одно и то же место памяти s3 = new String(); // s3 ссылается на место в памяти, где хранится пустая строка s3 = new String(); // s3 ссылается на место в памяти, где хранится пустая строка

String concatenation

Linking lines produced by the + command. It corresponds to the operator + =, which is often very convenient:

String S = "Привет"; String S1 = "мир"; S += ", " + S1 + "!"; // Теперь S ссылается на строку “Привет, мир!”

Line length

You can determine the length of a string using the length() method:

int x = S.length(); // Переменная x получит значение 12

Note that the String is a class (the classes are discussed in more detail in the next lesson), and length() is its method, and therefore is indicated through the period after the variable name. Other methods of the String class are written in the same way.

Receiving individual characters of a string

about how to get individual characters string

The charAt(int i) method returns the character of the string with the index i . The index of the first character of a string is 0 (that is, characters of a string are indexed (numbered) in the same way as array elements. For example:

char ch = S.charAt(2); // Переменная ch будет иметь значение 'и'

The toCharArray() method converts a string into an array of characters:

char[] ch = S.toCharArray(); // ch будет иметь представлять собой массив {'П','р','и','в','е','т',' ',',',' ','м','и','р','!'}

The getChars(int begin, int end, char dst[], int i) method getChars(int begin, int end, char dst[], int i) takes string characters that have indices from begin to end-1 inclusive, and puts them into the dst array starting at index i , and returns the resulting array as a result . For example:

char[] ch = {'М','а','с','с','и','в','.'}; ch = S.getChars(1, 4, ch, 3); // Теперь ch = {'М','а','р','и','в','в','.'}

Replacing a single character

The replace(int old, int new) method returns a new string in which all occurrences of the old character are replaced with the new character.

String SS = S.replace('и', 'ы'); // SS = "Прывет, мыр!"

Receiving a substring

The substring(int begin, int end) method returns a fragment of the source string from the character with the begin index to the character with the end-1 index inclusive. If you do not specify end , a fragment of the original string is returned, starting with the character with the begin index and to the end:

String S2 = S.substring(4,7); // S2 = "ет," String S2 = S.substring(4,7); // S2 = "ет," S2 = S.substring(4); // S2 = "ет, мир!" S2 = S.substring(4); // S2 = "ет, мир!"

Splitting a string into substrings

The split(String regExp) method split(String regExp) splits a string into fragments using the characters included in the regExp parameter as regExp and returns a reference to an array composed of these fragments. The delimiters themselves are not part of any substring.

String parts[] = S.split(" "); // Разбили строку S на отдельные слова, используя пробел в качестве разделителя, в результате получили массив parts, где parts[0] = "Привет,", а parts[1] = "мир!" String parts[] = S.split(" и"); // Разбили строку S на отдельные слова, используя в качестве разделителя пробел и букву и, в результате parts[0] = "Пр", parts[1] = "вет,", parts[2] = "м", parts[3] = "р!"

String comparison

If you compare strings using the logical operation == , then its result will be true only if the string variables point to (refer to) the same object in memory.

If you need to check two strings for a match, you should use the standard equals(Object obj) method. It returns true if the two strings are completely identical up to the letter case, and false otherwise. It should be used as follows:

S1.equals(S2); // Вернет true, если строки S1 и S2 идентичны S1.equals(S2); // Вернет true, если строки S1 и S2 идентичны S2.equals(S1); // Абсолютно то же самое S2.equals(S1); // Абсолютно то же самое boolean b = S.equals("Привет, мир!"); // b = true boolean b = S.equals("Привет, мир!"); // b = true

The equalsIgnoreCase(Object obj) method works in the same way, but the strings written in different registers are considered coincident.

Substring search

The indexOf(int ch) method returns the index of the first occurrence of the character ch in the source string. If you use this method in the form of indexOf(int ch, int i) , that is, you specify two parameters when invoked, the search for the entry will begin with the character with the index i . If there is no such character in the string, the result is -1.

int pos = S.indexOf('в'); // pos = 3 int pos = S.indexOf('в'); // pos = 3 pos = "Вася".indexOf('с'); // pos = 2 pos = "Вася".indexOf('с'); // pos = 2 pos = "Корова".indexOf('о', 2); // pos = 3 pos = "Корова".indexOf('о', 2); // pos = 3 pos = "Корова".indexOf('К', 2); // pos = -1, поиск ведется с учетом регистра pos = "Корова".indexOf('К', 2); // pos = -1, поиск ведется с учетом регистра

The last occurrence of a character can be found using the lastIndexOf(int ch) or lastIndexOf(int ch, int i) method, which works similarly, but looks at a string from the end.

All the listed methods have variants of the same name, which take as a parameter a string instead of a symbol and check if this string is contained in the source string.

pos = "Корова".indexOf("ор"); // pos = 1 pos = "Корова".indexOf("ор"); // pos = 1 pos = "Барабанщик барабанил в барабан".indexOf("барабан", 5); // pos = 11 pos = "Барабанщик барабанил в барабан".indexOf("барабан", 5); // pos = 11 pos = "Корова".indexOf("Вася"); // pos = -1 pos = "Корова".indexOf("Вася"); // pos = -1

Changing the case of characters in a string

The toLowerCase() method returns a new line in which all letters are lowercase. The toUpperCase() method returns a new line in which all letters are made in uppercase.

S = S.toUpperCase(); // S = "ПРИВЕТ, МИР!"

Exercise 3

Write a method that replaces all occurrences of the word “byaka” with “cut by censorship” in the line.

Hint: there is a very simple way ...

Header of main () method

Now we can finally understand most of the description of the main() method (except for the public and static keywords.

The public static void main(String[] args) header means that the main() method does not return values ​​(and indeed, we have never used the return command in its body), and takes an array of args strings as the only parameter.

The args parameter of the main() method is passed to the so-called command line arguments. The fact is that each program can be launched not just by clicking on its icon. You can enter the name of the executable file of the program in the command line (press the Windows + R combination to see the Windows command line if you are working on this operating system), and after the name, specify one or more additional parameters (command line arguments) after the name.

Thus, in the main() method, you can refer to the elements of the args array and see which additional arguments the user specified when starting the program. You can teach the program to respond to some of these arguments.

It is not necessary to run the program from the command line. In the Run -> Run dialog box ... there is a tab (x) = Arguments, by clicking on which you can list the command line arguments you are interested in and, depending on them, test the reaction of the program. Unless, of course, this is necessary: ​​most programs do not respond to command line arguments.


additional literature

1. Vyazovik N.A. Java programming. (chapter 9)

2. Khabibullin I.Sh. Tutorial Java 2. (Chapters 1, 5)

The task

Create a new project (name it MainTask). There should be two projects in your workspace. In one, you will try examples and perform exercises while studying a new topic. In the MainTask project, you will work on your main task.

Get acquainted with the task.

Сформулируйте требования к методу, с помощью которого можно было бы решить вашу задачу. Какие входные и выходные данные должен иметь этот метод? Используйте конструкции языка (примитивные типы, массивы, строки), изученные на первых двух занятиях. Напишите заголовок метода и покажите его преподавателю.

Приступайте к программированию этого метода параллельно с дальнейшим изучением пособия. Вы должны отчитаться по достигнутому результату на пятом занятии.

Для примера сформулируем требования к методу, с помощью которого решается задача определения суммы выигрыша на тотализаторе (см. задание №3):

Написать метод для подсчета суммы выигрыша на тотализаторе. В качестве параметров метод принимает массив строк (имена лошадей), упорядоченный по результатам забега и перечень ставок, заданный с помощью трех массивов равной длины. Первый массив — имя игрока, второй — кличка лошади, на которую он поставил и третий — сумма, которую игрок поставил на эту лошадь (то есть, игрок gamers[i] поставил на лошадь horses[i] сумму sums[i]). Метод должен возвращать массив строк, где каждая строка содержит имя игрока-победителя и выигранную им сумму.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

OOP and Practical JAVA

Terms: OOP and Practical JAVA