Can you explain methods in Java

Chapter 4: Functions

Programming in Java: Introduction



This book is licensed under a Creative Commons license.


4.1 Methods

Summarize commands

A function is a combination of several commands. Instead of calling each command individually in a program when it is needed, a corresponding function can be called that contains the commands to be executed. When the function is called, all of the commands grouped together are executed step-by-step, as if they had been called individually.

Strictly speaking, there are no functions in Java, only methods. A method is nothing more than a function that belongs to a class. In Java, all functions must belong to classes - there cannot be any functions outside of classes. In this respect there are only methods and no functions in Java. While object-oriented programmers differentiate between functions and methods linguistically, there is no difference in technical terms. Since there are only methods in Java, from now on this book will only speak of methods and not functions.

import java.applet. *; import java.awt. *; public class MyApplet extends Applet {public void init () {showStatus ("Hello, world!"); setBackground (Color.blue); }}

You have already learned about several methods: For Java applets, the method is always called when the browser loads the Java applet for the first time. For example, if you see the text "Hello, World!" and also want to set the background color of the applet to blue, you simply have to put the two corresponding instructions in the method as above. When the browser calls up, all instructions within the method are executed one after the other. First the text of the status bar is set and then the background color in the applet. This is done using the two methods and.


4.2 Method definition

First step: create a method

How are methods defined? First of all, it is important that you always write method definitions within classes. By definition, methods must belong to a class and must therefore also appear within the two curly brackets of the class.

import java.applet. *; public class MyApplet extends applet {public void init () {} public void start () {} public void stop () {} public void destroy () {}}

You have already learned about four methods that are important for Java applets. A method definition always begins with an access attribute. Access attributes determine to what extent other classes have access to the method. You have already learned about access attributes briefly in connection with classes. In fact, the access attributes are the same each time. You can use access attributes to define the extent to which other classes can access your own class and methods in the class. In addition, access attributes can also be applied to properties. You will learn exactly how this mechanism works in Chapter 5, Access attributes know.

The return value of the method follows the access attribute. The return value of the method is either a primitive data type (,,,,,, or), a class from a class hierarchy, a self-programmed class or the special keyword. The data type determines what kind of information is returned by the method as a result. It can therefore be a primitive data type, it can be an object of the type of a class or it can be. means that the method will not return any result at all. So methods don't necessarily have to return results.

In Java, as in C # or C ++, it is not possible to receive more than one return value from a method. Methods return exactly one or no return value.

The method name is specified after the data type of the return value. You can use any name here, but it should be as descriptive as possible and should indicate what the method actually does. Method names like and are good examples.

Make sure that there are method names that have a special meaning. If you name your method, that method will be called automatically when the browser loads your applet. If, on the other hand, you want to prevent your method from acting as an event handler and being called when certain events occur, you must give the method a different name.

The parameter list follows the method name. A parameter list is always given in round brackets. Even if no parameter list is given, the round brackets must be written - they are then empty. This is the case with the four special methods of applets that we have already learned about.

What are parameters? Parameters are variables - regardless of whether they are of primitive data types or reference variables - that are passed to the method as a type of input. The method accepts the transferred variables and works with them within the method.

Just as methods can return a value as a result, they can receive parameters as input values. In contrast to the return value, a method can also expect several parameters.

public class MyApplication {public static void main (String [] args) {int x = 5; int y = 10; int result = add (x, y); System.out.print (result); } public static int add (int a, int b) {int r = a + b; return r; }}

A method named is defined in the above Java application. The method name is chosen so that you can immediately see what this method does: It performs additions.

The method is defined to return a value of type. A parameter list is also given: The method expects two parameters, both of which are of the type. Parameter lists look like this that variable definitions are given between the two round brackets. Several variable definitions are separated by commas. In this case the parameter list of the method consists of the two variables and, both of which are of the type.

The definition of now says the following: When the method is called, exactly two values ​​or variables must be transferred, both of which are of the type. The result is a value that is also of the type.

How is it defined, what happens within the method? The two parameters that the method receives are added with the operator. The result of the addition is stored in a local variable, which is also of the type. In the next line the method is ended with the help of the keyword and a value or a variable is returned at the same time. The value or the variable must be specified after. In this case, the variable is returned as the result.

Looking at the whole thing again with due distance: The method expects two values ​​to be added. The result of the addition is then returned by the method. The method enables the addition of two numbers - more precisely: two values ​​of the type.

What you have got to know so far is called a method definition. A method definition is always the first step that is necessary before the method can be used. As just seen, a method definition consists of a method head - return value, method name and parameter list - and the method body. The instruction block, which is delimited by the curly brackets and is located after the method head, is referred to as the method body.

The meaning and purpose of the keyword in the method head of is explained at the end of this chapter. At this point you can just ignore it.


4.3 Method call

Second step: use the method

Defining the method was the first step. How is this method actually used and applied?

public class MyApplication {public static void main (String [] args) {int x = 5; int y = 10; int result = add (x, y); System.out.print (result); } public static int add (int a, int b) {int r = a + b; return r; }}

A method is called by specifying the method name followed by two round brackets. Depending on the definition of the method, one or more parameters must be placed between the round brackets. is defined in such a way that two parameters of the type are expected. That is why two variables must be passed when calling. This is done by placing the names of the variables to be transferred in round brackets, separated by commas. In this case, the two local variables and are passed to the method.

What is happening now in this program? When the Java application is started, the method is called automatically. In this method, two variables of the type are defined, which are set once to the value 5 and once to the value 10. Then the method is called. The definition of is that two parameters of the type are expected. Therefore, the two variables and are specified in the round brackets when calling.

Now the following happens: The value of the variable - namely 5 - is copied over into the variable. The value of the variable - namely 10 - is copied into the variable. Which value is copied where depends on where the variables are specified. is the first variable when calling. The first parameter in the definition of is. Therefore the value is copied from to. The copying process is carried out accordingly for the variable and the parameter.

It is important: When the method is called, the transferred values ​​are copied. The method does not work with the original variables and, but only with copies. This concept is called call by value. When calling methods in Java, parameters are always passed as a copy, as a value, not as the original variable itself.

The return value of is saved in a variable. This variable is displayed on the screen with the help of the class that enables access to standard functions of the computer. offers, among other things, access to the standard output. is a reference variable, a static property of the class. By specifying the access operator afterwards, a method can be accessed, among other things. The value or the variable that is passed to the method as a parameter is displayed on the screen.


4.4 Optimizing the handling of methods

Nest method calls

You now know the basics of using methods: first you have to define methods, and then you can call them. In addition, there are a few tricks that can simplify the use of methods. At the same time, the following examples illustrate the use of methods.

public class MyApplication {public static void main (String [] args) {int x = 5; int y = 10; System.out.print (add (x, y)); } public static int add (int a, int b) {int r = a + b; return r; }}

The example application has now been modified. The call to now takes place between the round brackets of the method. The variable that previously received the return value from has been deleted.

What happens now in the program? You see a nested method call here. The method is called in the round brackets from. Java handles nested method calls in such a way that inner method calls are executed first. That is, the method is executed first, then the method.

The two variables and are passed back to the method, the values ​​of which are copied over to the parameters and. When the calculation has finished and the result of the addition is returned, then this return value is not saved in a variable, but passed on to the method directly between the round brackets as a transfer value.

You can save yourself the need to define variables by using nested method calls. Instead of storing the result of a method call in a variable and then passing this variable as a parameter to another method in the next step, you simply call the method at the point at which the return value of the method is to be passed as a parameter to another method . The return value of one method is passed on directly as a transfer value to the other method without being saved in a variable in the meantime.

The example application can be simplified elsewhere.

public class MyApplication {public static void main (String [] args) {int x = 5; int y = 10; System.out.print (add (x, y)); } public static int add (int a, int b) {return a + b; }}

Instead of saving the sum of the parameters and in a new variable in the method and then also returning this variable, the addition can be carried out directly after the method. The result of this addition is no longer saved in a variable, but passed on directly as the return value of the method.

Another code reduction could look like this.

public class MyApplication {public static void main (String [] args) {System.out.print (add (5, 10)); } public static int add (int a, int b) {return a + b; }}

Now the numerical values ​​5 and 10 are no longer stored in two variables and, which in turn are passed as parameters to the method, but 5 and 10 are placed directly between the brackets of. This notation is also completely okay. The two numerical values ​​are copied as usual into the parameters and the method, in which these copied values ​​are then used for further calculations.


4.5 Foreign methods

Calling methods of other classes

Take a closer look at the example from just now.

public class MyApplication {public static void main (String [] args) {System.out.print (add (5, 10)); } public static int add (int a, int b) {return a + b; }}

In this example, two methods are called, namely and. However, while it can be called simply by specifying the method name, must also be specified before calling the method. Why is such an additional information necessary for, but apparently not?

Methods that are defined as in the same class can basically be called simply using the method name. However, the method is not defined in the class. It is in a different class - namely the one on which it is based. Therefore, in order to be able to access, you must prefix this method call.

Take a look at the following example briefly introduced at the beginning of this chapter.

import java.applet. *; import java.awt. *; public class MyApplet extends Applet {public void init () {showStatus ("Hello, world!"); setBackground (Color.blue); }}

In this case no application is created, but an applet. As usual with applets, the corresponding class, here, must be derived from and subordinated to it.

Two methods and are called in the method. As you can see, neither the one nor the other method is defined in the class. Nevertheless, both methods can be called directly by specifying the method name without the need for additional information in front of the method name. How is that possible?

The class becomes a child of the parent class. The purpose of this subordination is that the class inherits the functionality of the parent class. The definitions of the two methods and are in the parent class. By submitting to the class, it inherits all method definitions from this parent class. This means that the method definitions are available directly in the child class, as if you had specified them there. This means that you can call the methods directly using the method name without having to enter any additional information.

With this example you can already see a great advantage of inheritance: Through inheritance, methods that are defined in a parent class can be inherited and are available in the child class without the programmer having to develop any of these inherited methods himself.

Strictly speaking, the class does not define a method. While the method is actually specified directly in the class, it is defined in a parent class of. It is passed on to the class through inheritance and ultimately also arrives in the class.


4.6 Overloading methods

Same method name, different parameters

Overloading is the definition of several methods that differ in that they expect different numbers of parameters or parameters with different types.

public class MyApplication {public static void main (String [] args) {System.out.print (add (5, 10, 15)); } public static int add (int a, int b) {return a + b; } public static int add (int a, int b, int c) {return a + b + c; }}

Two methods are now defined in the Java application, both of which are called. As long as the parameter lists differ, this is also not a problem.In one case it expects exactly two parameters of the type, in the other case exactly three parameters of the type. Which method is called in each case depends not only on the method name, but also on the number of parameters. In the example above, the method is called that expects three parameters - after all, three numbers are specified when called.

public class MyApplication {public static void main (String [] args) {System.out.print (add (5.2, 10.3)); } public static int add (int a, int b) {return a + b; } public static double add (double a, double b) {return a + b; }}

Two methods are now defined in the application, which do not differ in the number of parameters, but in the data type of the parameters. This time the second method expects two values ​​of the type as parameters. The point numbers 5.2 and 10.3 are transferred when the method is called. Note that point numbers are written with a period. These decimal numbers are copied into the parameters and the method that expects decimal numbers as parameters. This method also performs an addition and returns the sum of the decimal numbers as the result.

The overloading of methods works in two ways: Either the methods have a different number of parameters. Or the parameters of the methods differ in the data type. Overloading methods using different data types of the return value alone is not possible in Java.

By the way, you already know overloaded methods from another example.

import java.applet. *; import java.awt. *; public class MyApplet extends Applet {String Text = new String ("Hello, World!"); public void paint (Graphics g) {g.drawString (Text, 0, 10); }}

When creating objects, the class from which an object is to be created must be specified after the keyword. Strictly speaking, the class is not specified, but a constructor - that is, a method that has the same name as the class. Constructors can pass parameters. For example, it is possible to initialize an object of the type with a certain character string by passing the character string as a parameter to the constructor. If you do not pass a string to the constructor of, a new object is created that is not initialized.

String Text1 = new String (); String Text2 = new String ("Hello, World!");

While an object of the type is created in the first line by calling the standard constructor - i.e. the constructor that does not expect a parameter - an object of the type is created in the second line via a constructor call that expects exactly one parameter in the form of a character string . The reference variable refers to an object that is empty. The reference variable refers to an object in which the string "Hello, World!" lies.

Here you can clearly see an overload again: same method name, different number of parameters. It is always a constructor - a method that has the same name as the class. However, one time it is passed a parameter, the other time not.

Almost all classes from the official Java class hierarchy offer overloaded constructors. So you can initialize objects that you create in a variety of ways, by passing different numbers of parameters or parameters of different types to constructors. What is possible and what is not naturally depends on each class definition. So you have to look again in the documentation to find out which constructors are offered by the respective class and what parameters you can pass.


4.7 Static methods

Methods without objects

Do you still know the difference between instance and class variables? Instance variables exist within objects, class variables belong to classes and are shared by all objects of a class. In addition, class variables can also be accessed without objects using the familiar access operator. The keyword made class variables out of instance variables.

The keyword can also be applied to methods - and has exactly the same effect there as with variables. A method that is also defined is called a class method. As with class variables, class methods can be accessed without the need for an object. They had already actively used a class method.

public class MyApplication {public static void main (String [] args) {System.out.print ("Hello, world!"); }}

Take a look at the method used in every Java application. This method is defined as a class method. You can tell by the keyword. Why is that the case? Why is it mandatory that it must be static?

When you start the Java VM and run your application, Java looks for a method and tries to call that method on the class. This means that somewhere in the Java system a call similar to the following takes place.

MyApplication.main ();

Java tries to start the method directly for the class. We can ignore the parameter in brackets at this point.

So that the method can actually be called for the class, it must be static. Otherwise it could only be called for objects. This means that a method that is not defined with the keyword could only be started if the method is accessed via an object of the corresponding class.

MyApplication application = new MyApplication (); application.main ();

If the Java system were to create an object from the class with and assign this object to a reference variable, then any method could be accessed via this reference variable and the access operator - regardless of whether it is static or not. In this case it could be called even if it were not static.

However, the procedure of the Java system cannot be changed. Java calls the method for an application via the class and does not automatically create an object. Since the class can only be called if it is a class method, your application will not be able to start if you forget the keyword.

Strangely enough, the browser works the other way around with applets. Take a look at the code of a typical Java applet.

import java.applet. *; import java.awt. *; public class MyApplet extends Applet {String Text = "Hello, World!"; public void paint (Graphics g) {g.drawString (Text, 0, 10); }}

The method - a typical event handler that is called by the browser for the applet when the applet is to be redrawn - does not have to be defined as a class method. It is not necessary, as is the case with the other four known methods for applets,, and.

If the browser loads an applet, an object is automatically created from the corresponding class, which is derived from. The known methods are then automatically called for this object whenever necessary.

MyApplet applet = new MyApplet (); applet.init (); applet.start (); applet.paint ();

Above you can see the typical startup sequence for applets as it runs in the browser. First, an object is created from the class specified in the website's HTML code. Then the methods, and are automatically called for the object.

Since the browser creates an object by default, it is not necessary to define the familiar applet methods as class methods. You can therefore omit the keyword, which is also done in practice.

The keyword is always used when the functionality provided by a method does not apply to a specific object, but is to be provided independently of objects. If a method can do its job without having to be applied to a specific object, then it makes sense to make this method static. Otherwise, you or other developers who use your class will force you to create an object first so that you can then use this object to call the appropriate method. Since the creation of objects is expensive and costs resources - that is, memory and processor time - a direct call to a static method would be advantageous.


4.8 Exercises

Practice creates masters

You can purchase the solutions to all of the exercises in this book as a ZIP file.

  1. Create a Java application that contains a method that expects two point numbers of the type. Both point numbers are multiplied within the method, the result is returned by the method. Test your application by calling the method with two point numbers and outputting the return value of the method to the standard output. To multiply two numbers you have to use the operator.

  2. Modify your solution to exercise 1 so that the method that multiplies the numbers of type is no longer static and the application still works as indicated.

  3. Modify your solution to exercise 1 in such a way that you overload the method that multiplies the numbers of the type in such a way that it expects three parameters of the type. Call the new method and output the result of multiplying any three decimal numbers to the standard output.

  4. Modify your solution to exercise 1 so that the application saves the two point numbers of the type in two properties of the class. Pass the two properties as parameters to the method doing the multiplication and output the result to standard output.

  5. Create a Java application that contains four methods to multiply, divide, add, and subtract two integers. Define a fifth method that reverses the sign of an integer. Call all five methods with any number values ​​and print the result on standard output.

  6. Modify your solution to exercise 5 so that the methods are no longer called with arbitrary numerical values, but rather nested. Multiply the numbers 5 and 10, add 30 to the result of the multiplication and subtract 45 from the result of the addition.Then divide 175 by the result of the subtraction, change the sign of the result of the division, and then enter it on the standard output. Do the entire calculation on a single line of code by nested calling the methods you created for Task 5.

  7. Create a Java applet in which you define a method that concatenates two strings. The method expects two parameters of the type and returns an object of the type as the result. The two parameters passed must also be linked in the method. Define two properties of the type and set them to "Hello," and "World!". Call the method for concatenating strings, pass the two properties as parameters and output the return value of the method in the applet interface.

  8. Modify your solution to exercise 7 so that the application can no longer only be used as a Java applet, but also as a Java application. To do this, create the method required for Java applications, which also includes the two properties with the values ​​"Hello," and "World!" concatenated and outputs the result to standard output. Your solution should therefore be able to be embedded in websites as a Java applet and also to be able to be started as a Java application.


Copyright © 2001-2010 Boris Schäling