Java Methods
Java Methods
Java methods are where you put the operations on data (variables) in your Java code. Java methods must be located inside a Java class. Java classes are covered in the next text in this Java trail.
Java methods are similar to what is called functions or procedures in other languages (e.g. Pascal). A method is a group of Java statements that perform some operation on some data, and may or may not return a result.
Here is a simple example:
public void writeText(String text) { System.out.print(text); //prints the text parameter to System.out. }
The example above defines a method called
writeText
. The method takes a single parameter calledtext
, which is used in the Java statement inside the method. The method does not return any value. I will get into what each of the elements in the above method definition means.Method Parameters
Method parameters makes it possible to pass values to the method, which the method can operate on. The method parameters are declared inside the parantheses after the method name. In the example below the method parameters are marked in bold:
public void writeText(String text1, String text2) { System.out.print(text1); System.out.print(text2); }
The method
writeText
method in the example above takes two parameters called text1
and text2
. The parameters are both of type String
as written in front of each parameter name.
You can use any primitive data type or built-in Java class as data type for parameters. You can also use your own classes as parameter types.
Parameters vs. Variables
A method parameter similar to a variable. You can read its value, and change its value too. Here is an example:
public void writeText(String text1, String text2) { System.out.print(text1); // read value of text1 parameter. System.out.print(text2); // read value of text2 parameter. text1 = "new value 1"; // change value of text1 text2 = "new value 2"; // change value of text2 }
A note of caution: Though it is possible to change the value of parameters, you should be careful doing that, as it may lead to confusing code. If you think you can handle it, go ahead. If not, create a local variable to hold the value instead, and leave the parameter value intact.
Final Parameters
A method parameter can be declared
final
, just like a variable. The value of a final
parameter cannot be changed. That is, if the parameter is a reference to an object, the reference cannot be changed, but values inside the object still can. Here is an example:public void writeText(final String text1, final String text2) { System.out.print(text1); // read value of text1 parameter. System.out.print(text2); // read value of text2 parameter. }
In this example you cannot reassign the parameters
text1
and text2
to any other String
's than the ones passed as parameters when the method was called.Local variables
You can declare local variables inside a method. A local variable can be used just like any other variable, but it is only accessible inside the scope of the method. Here is an example:
public void writeText() { int localVariable1 = 1; int localVariable2 = 2; System.out.println( localVariable1 + localVariable2 ); }
Local variables can also be declared
final
. If you do so, it's value cannot be changed. If the variable is a reference to an object, the reference to the object cannot be changed, but values inside the referenced object can.Method Return Types
A method can return a value. Here is an example:
public int sum(int value1, int value2) { return value1 + value2; }
This method adds the two parameters passed to it, and returns the result.
First, notice the return,
int
type which is marked in bold before the method name (sum
). This return type signals that this method returns an int
.
Second, notice the
return
statement. The return
statement is what determines what value is returned by the method.
You can return any primitive type or any object from a Java method. You could also return a
String
, like this:public String concat(String string1, String string2) { return string1 + string2; }
This method concatenates the two strings passed as parameters, and returns the result.
Multiple Return Statements
It is possible to have more than one
return
statement in a method. However, they cannot both be executed. Only one return
statement can be executed. Once a return
statement is executed, no more code in that method is executed. The program simply jumps back to the code that called the method.
Here is an example of a method with multiple return statements:
public String concat(String string1, String string2, boolean reverseOrder){ if(reverseOrder) { return string2 + string1; } return string1 + string2; }
Notice the
if
statement inside the method. This if
statement tests whether the boolean parameterreverseOrder
is true or false.
If the
reverseOrder
parameter has the value true
, then the method returns the two strings passed as parameters, concatenated in reverse order (first string2
, then string1
).
If the
reverseOrder
parameter has the value false
, then the method skips the body of the if
statement. It then continues to the second return
statement. This return
statement returns the two parameters concatenated in normal order (string1
, then string2
).Method Access Modifiers
You may have noticed the word
Java classes.
public
which I have put in front of all method declaration examples in this text. This word is the access modifier for the method. The access modifier determines what code is allowed to call this method. Access modifiers are covered in more detail in the text onJava classes.
Exception Declarations
If an error occurs inside a method, the method may throw an exception. Exceptions have to be declared in the method declaration, like this (marked in bold):
public String concat(String string1, String string2) throws MyException { if(string1 == null) { throw new MyException("string1 was null"); } if(string2 == null) { throw new MyException("string2 was null"); } return string1 + string2; }
This method first checks if either of the two parameters
string1
or string2
are null
. If they are, an exception is thrown.
When an exception is thrown, the method also stops executing. But, instead of returning to where the method was called from, the execution is resumed inside the first
catch() { }
clause surrounding the method, targeted at that exception.
I have a whole trail about Java exception handling, so I will not get into more detail about it here.
Calling Methods
I have been talking about calling methods in several places in this text. Now I will show you how to do it. Take a look at these two methods:
public void callSum() { int theSum = add(1, 3); System.out.print(theSum); } public int add(int value1, int value2) { return value1 + value2; }
Notice how the method
callSum()
creates a variable called theSum
, and assigns it the value returned by the add(1, 3)
method call. Afterwards it prints out the value.
Pretty smart, eh?
Methods can be used to break down code into smaller, more comprehensible and reusable segments of code, rather than writing your program as one, big method.
0 comments: