JavaRush /Java Blog /Random EN /Methods in Java
articles
Level 15

Methods in Java

Published in the Random EN group
Methods in Java - 1In Java, an application consists of classes. Classes, in turn, consist of variables. They are responsible for storing data and methods that are responsible for the behavior of the class: in other words, the logic that it can provide (for example, processing some data, calling other methods, etc.). We can talk about such components as variables for a long time, but that is not why we have gathered today. Let's better talk about such a component of the class as a method. Methods in Java - 2A method is a named block of code declared within a class. It contains a certain complete sequence of actions (instructions) aimed at solving a separate problem, which can be reused. In other words, a method is a function: something that your class can do. Other languages ​​also have functions. Only in Java they are members of classes and, according to OOP terminology, are called methods. But before we continue, let's look at a small example:

public String constructHelloSentence(String name) {
  String resultSentence = "Hello world! My name is " + name;
  System.out.println(resultSentence);
  return resultSentence;
}
There’s nothing complicated here: a Java method whose task is to generate a greeting string with the name that we pass to it. Like for example - Hello world! My name is Bobby Let's understand the construction of a method properly by looking at each keyword in the method declaration (from left to right). Our first keyword is public, and it denotes an access modifier:

Access modifiers

They indicate the permissible scope of visibility for class members, that is, the restriction of the places in which a variable or method is allowed to be used. Methods in Java - 3The following access modifiers are used in Java:
  • public : public. Methods or fields with this modifier are public, visible to other classes (or rather, their methods and fields) from the current package and from external packages. This is the broadest level of access known;

  • protected : methods or variables with this modifier can be accessed from anywhere in the current class or package, or in classes that inherit this one, as well as methods or fields, even if they are in other packages

    
    protected String constructHelloSentence(String name) {...}
  • Default modifier. If a class field or method does not have a modifier, the default modifier is applied. In this case, the fields or methods are visible to all classes in the current package (like protected , but with no visibility when inheriting).

    
    String constructHelloSentence(String name) {...}
  • private : the opposite of the public modifier . A method or variable with such a modifier is only available in the class in which it is declared.

    
    private String constructHelloSentence(String name) {...}
Next we have Stringin the method signature (the first line of the method describing its properties).

Return value

The return value is the data (some result of the method execution) that comes in its place after the call. Every method has a return value. Or not?

Return Value Methods

This value can be any type of data: a variable of a simple type or a reference type. In this example, we indicate that the method must return an object of type String, which, as we remember, is a class that describes a string. The second point here is the word return. It has a direct relationship to the return value: the value after it will be sent back to the place where the method was called, and the method itself will then returnclose. This word usually appears in the last line of the method (except for methods with various branches like if, else...). If you write the code on the next line after return:

private String constructHelloSentence(String name) {
  String resultSentence = "Hello world! My name is " + name;
  return resultSentence;
  System.out.println(resultSentence);
}
then we will get curses from the compiler, which is not very good (the compiler will not recommend nonsense). You also need to remember that the data type after сmust match the one declared in the method signature. returnRead more about here .

void

What is it used for voidin Java? Not all methods have a return value. Some either have nothing or don’t need to return anything. What to do then? Then in the method signature we write void. What would our method look like without a return value?

protected void constructHelloSentence(String name) {
  String resultSentence = "Hello world! My name is " + name;
  System.out.println(resultSentence);
}
You probably noticed that along with the return value, the word returnSo it is has disappeared, because our method should not return anything. However, it can be placed here, but without any meaning, just return; in the last line. This is generally useless, so voidit is optional in methods with. However, it can be used usefully in voidmethods, such as branches or loops, where you want to exit the method immediately. Next in the method declaration we had constructHelloSentence.

Method names

constructHelloSentence - the name of the method, a distinctive feature by which we can distinguish one or another method. And, accordingly, call one or another method. Methods in Java - 4Method names must begin with a small letter, but also use camel case (CamelCase, camel case): i.e. Each next word in the name is adjacent to the previous one and is written with a capital letter. Method names should describe the method (the best comment is proper naming). To do this, use verbs or combinations with verbs: getCat, delete, createCar, and so on. Within one class, method names must be unique (not counting method overloading, which we’ll talk about a little later). Let's look further at the method we are analyzing and see ( String name)

Method parameters

Methods may (or may not) have certain data that will come from outside, namely from the place where the method was called. In our case, we see that a type object Stringwith a name arrives nameand in the future we use this variable in our method. You can use an unlimited number of parameters in a method, but more than 7 are not recommended. When we do not know the exact number of elements, but all these elements are needed for the same purpose and will be of the same type (for example, String), an ellipsis is used:

public void constructHelloSentence(String...name) {
 ...
}
The appeal to each element will be like this: name[0] Does it remind you of anything? That's right, array! Nothing will change if we write:

protected void constructHelloSentence(String[] name) {
 ...
}
The access to the elements will also be of the form: name[1] And one more thing. Method arguments can be final :

public String constructHelloSentence(final String name) {
  ...
}
This means that the name reference is bound to a specific object Stringand cannot be overridden. finalYou can read about working with reference variables and their interaction with reserved words in the material “ Reference Data Types in Java ”.

Calling Methods

So, we've sorted out the creation of methods, now let's talk about using them. How to call a method in Java? Methods in Java - 5Every method in Java is in a class. To understand how calling methods in Java works, let’s take a class:

public class StringConstructor {
  public String constructHelloSentence(String name) {
     String resultSentence = "Hello world! My name is " + name;
     System.out.println(resultSentence);
     return resultSentence;
  }
}
Since our method is not static (this is a separate topic for discussion that goes beyond the scope of today’s article), to call it you must first create an object and then call the method on it:

class Application{
  public static void main(String[] args) {
     StringConstructor stringConstructor = new StringConstructor();
     stringConstructor.constructHelloSentence("Den");
  }
}
In the arguments of our method, we passed the string (name) that we want to see in the resulting string displayed on the screen:

Hello world! My name is Den
It is also worth remembering that methods can be reused as many times as we need - there are no restrictions.

this

You can often see the keyword in code this, as in setters:

public void setValue(Long value) {
   this.value = value;
}
And what does it mean? thisin Java, this is a reference to the current object of this class. For example, if we created an object:

StringConstructor stringConstructor = new StringConstructor();
then thisinside the object stringConstructorthere will be a link to the same object. thisis used both to refer to an object variable (as in the setter above) and to call some method. We can rewrite our class a little:

public class StringConstructor {
 
  public String constructHelloSentence(String name) {
     String resultSentence = this.getSentence()  + name;
     System.out.println(resultSentence);
     return resultSentence;
  }
 
  private String getSentence() {
     return "Hello world! My name is ";
  }
}
Through thiswe call the method of this object to take the required string. But still, as a rule, this is almost not used for methods, since even without it there is a reference to a method of a given object; it is mainly used for an object variable.

Method Overloading

Let's say we needed a method that performs essentially the same logic, but in a Hello world! instead worldwe want to insert our own word (string). But we already have a method constructHelloSentence. So, do we need to come up with a new name for a method that essentially performs the same functionality? No matter how it is: at this moment method overloading comes to our aid. Methods in Java - 7Method overloading is the use of the same method name more than once when declaring it in a class. From the point of view of language syntax, there cannot be two identical names in some local space. But it is also possible to declare methods with the same names but different arguments. In other words, a class contains overloads when there are two or more methods with the same names but different input data:

public class Constructor {
 
  public String constructHelloSentence(String name) {
     String resultSentence = "Hello world! My name is " + name;
     System.out.println(resultSentence);
     return resultSentence;
  }
 
  protected String constructHelloSentence(String firstName, String secondName) {
     String resultSentence = "Hello " + firstName + "! My name is " + secondName;
     System.out.println(resultSentence);
     return resultSentence;
  }
}
Here we see that methods do not have to contain the same access modifier (as well as the return type). If an overloaded method is called, then from several declared methods the compiler automatically determines the required one based on the parameters that are specified during the call.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION