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. The 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) {...}
String
in 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 typeString
, 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 return
close. 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. return
Read more about here .
void
What is it used forvoid
in 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 return
So 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 void
it is optional in methods with. However, it can be used usefully in void
methods, 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. Method 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 objectString
with a name arrives name
and 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 String
and cannot be overridden. final
You 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? Every 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 codethis
, as in setters:
public void setValue(Long value) {
this.value = value;
}
And what does it mean? this
in Java, this is a reference to the current object of this class. For example, if we created an object:
StringConstructor stringConstructor = new StringConstructor();
then this
inside the object stringConstructor
there will be a link to the same object. this
is 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 this
we 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 aHello world
! instead world
we 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. Method 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.
GO TO FULL VERSION