Methods

From Wikibooks, open books for an open world
Jump to: navigation, search

Literals Java Programming
Methods
API/java.lang.String
Navigate Language Fundamentals topic: v  d  e )


Methods are how we communicate with objects. When we invoke or call a method we are asking the object to carry out a task. We can say methods implement the behaviour of objects. For each method we need to give a name, we need to define its input parameters and we need to define its return type. We also need to set its visibility (private, package, or public). If the method throws an Exception, that needs to be declared as well. It is called a method definition. The syntax of method definition is:

class MyClass {
 ...
    public ReturnType methodName(ParamOneType param1,
                                 ParamTwoType param2)
    throws ExceptionName {
      ReturnType retType;
      ...
      return retType;
    }
 ...
}

We can declare that the method does not return anything using the void Java keyword. For example:

Example Code section 3.50: Method without returned data.
  1. private void methodName(String param1, String param2) {
    
  2.   ...
    
  3.   return;
    
  4. }
    

When the method returns nothing, the return keyword at the end of the method is optional. When the execution flow reaches the return keyword, the method execution is stopped and the execution flow returns to the caller method. The return keyword can be used anywhere in the method as long as there is a way to execute the instructions below:

Warning Code section 3.51: return keyword location.
  1. private void aMethod(int a, int b) {
    
  2.   int c = 0;
    
  3.   if (a > 0) {
    
  4.     c = a;
    
  5.     return;
    
  6.   }
    
  7.   int c = c + b;
    
  8.   return;
    
  9.   int c = c * 2;
    
  10. }
    

In the code section 3.51, the return keyword at line 5 is well placed because the instructions below can be reached when a is negative or equal to 0. However, the return keyword at line 8 is badly placed because the instructions below can't be reached.

Test your knowledge

Question 3.9: Consider the following code:

Example Question 3.9: Compiler error.
  1. private int myMethod(int a, int b, boolean c) {
    
  2.   b = b + 2;
    
  3.   if (a > 0) {
    
  4.     a = a + b;
    
  5.     return a;
    
  6.   } else {
    
  7.     a = 0;
    
  8.   }
    
  9. }
    

The code above will return a compiler error. Why?

Answer
Example Answer 3.9: Compiler error.
  1. private int myMethod(int a, int b, boolean c) {
    
  2.   b = b + 2;
    
  3.   if (a > 0) {
    
  4.     a = a + b;
    
  5.     return a;
    
  6.   } else {
    
  7.     a = 0;
    
  8.   }
    
  9. }
    

The method is supposed to return a int but when a is negative or equal to 0, it returns nothing.

Parameter passing[edit]

We can pass any primitive data types or objects to a method but the two are not processed the same way.

Primitive type parameter[edit]

The primitive types are passed in by value. It means that as soon as the primitive type is passed in, there is no more link between the value inside the method and the source variable:

Example Code section 3.52: A method modifying a variable.
  1. private void modifyValue(int number) {
    
  2.   number = number + 1;
    
  3. }
    
Example Code section 3.53: Parameter by value.
  1. int i = 0;
    
  2. modifyValue(i);
    
  3. System.out.println(i);
    
Computer code Output for Code section 3.53
0  

As you can see in code section 3.53, the modifyValue() method has not modified the value of i.

Object parameter[edit]

The object references are passed by value. It means that:

  • There is no more link between the reference inside the method and the source reference,
  • The source object itself and the object itself inside the method are still the same.

You must understand the difference between the reference of an object and the object itself. A object reference is the link between a variable name and an instance of object:

Object objnew Object()

An object reference is a pointer, an address to the object instance.

The object itself is the value of its attributes inside the object instance:

obj.firstName "James"
obj.lastName "Gosling"
obj.birthDay "May 19"

Take a look at the example above:

Example Code section 3.54: A method modifying an object.
  1. private void modifyObject(Class1 anObject) {
    
  2.   anObject.setName("Susan");
    
  3. }
    
Example Code section 3.55: Parameter by reference.
  1. Class1 obj = new Class1();
    
  2. obj.setName("Christin");
    
  3.  
    
  4. modifyObject(obj);
    
  5.  
    
  6. System.out.println(obj.getName());
    
Computer code Output for Code section 3.55
Susan

The name has changed because the method has changed the object itself and not the reference. Now take a look at the other example:

Example Code section 3.56: A method modifying an object reference.
  1. private void modifyObject(Class1 anObject) {
    
  2.   anObject = new Class1();
    
  3.   anObject.setName("Susan");
    
  4. }
    
Example Code section 3.57: Parameter by reference.
  1. Class1 obj = new Class1();
    
  2. obj.setName("Christin");
    
  3.  
    
  4. modifyObject(obj);
    
  5.  
    
  6. System.out.println(obj.getName());
    
Computer code Output for Code section 3.57
Christin

The name has not changed because the method has changed the reference and not the object itself. The behavior is the same as if the method was in-lined and the parameters were assigned to new variable names:

Example Code section 3.58: In-lined method.
  1. Class1 obj = new Class1();
    
  2. obj.setName("Christin");
    
  3.  
    
  4. // Start of the method
    
  5. Class1 anObject = obj;
    
  6. anObject = new Class1();
    
  7. anObject.setName("Susan");
    
  8. // End of the method
    
  9.  
    
  10. System.out.println(obj.getName());
    
Computer code Output for Code section 3.58
Christin

Functions[edit]

In Java, functions (methods really) are just like in C++ except that they must be declared inside a class and objects are passed by value of reference pointing to that object. You cannot create pointers to a function but Java has events which really are function pointers under the hood for when you need that type of functionality.

Return parameter[edit]

So as we can see, a method may or may not return a value. If the method does not return a value we use the void Java keyword.

Same as the parameter passing, the method can return a primitive type or an object reference. So a method can return only one value. What if you want to return more than one value from a method. You can always pass in an object reference to the method, and let the method modify the object properties. The modified values can be considered as an output value from the method. However you can also create an Object array inside the method, assign the return values and return the array to the caller. You could have a problem however, if you want to mix primitive data types and object references as the output values from the method.

There is a better approach. Defines special return object with the needed return values. Create that object inside the method, assign the values and return the reference to this object. This special object is "bound" to this method and used only for returning values, so do not use a public class. The best way is to use a nested class, see example below:

Computer code Code listing 3.10: Multiple returned variables.
  1. public class MyObject {
    
  2.   ...
    
  3.  
    
  4.   /** Nested object is for return values from getPersonInfoById method */
    
  5.   public static class ReturnObj {
    
  6.       private int    age;
    
  7.       private String name;
    
  8.  
    
  9.       public void setAge(int val) {
    
  10.           this.age = val;
    
  11.       }
    
  12.  
    
  13.       public int getAge() {
    
  14.           return age;
    
  15.       }
    
  16.  
    
  17.       public void setName(String val) {
    
  18.           name = val;
    
  19.       }
    
  20.  
    
  21.       public String getName() {
    
  22.           return name;
    
  23.       }
    
  24.   } // End of nested class definition
    
  25.  
    
  26.   /** Method using the nested class to return values */
    
  27.   public ReturnObj getPersonInfoById(int id) {
    
  28.      int    age;
    
  29.      String name;
    
  30.    ...
    
  31.      // Get the name and age based on the ID from the database
    
  32.    ...
    
  33.      ReturnObj ret = new ReturnObj();
    
  34.      ret.setAge(age);
    
  35.      ret.setName(name);
    
  36.  
    
  37.    return ret;
    
  38.   }
    
  39. }
    

In the above example the getPersonInfoById method returns an object reference that contains both values of the name and the age. See below how you may use that object:

Example Code section 3.59: Retrieving the values.
  1. MyObject obj = new MyObject();
    
  2. MyObject.ReturnObj person = obj.getPersonInfoById(102);
    
  3.  
    
  4. System.out.println("Person Name=" + person.getName());
    
  5. System.out.println("Person Age =" + person.getAge());
    
Test your knowledge

Question 3.10: Consider the following code:

Example Question 3.10: Compiler error.
  1. private int myMethod(int a, int b, String c) {
    
  2.   if (a > 0) {
    
  3.     c = "";
    
  4.     return c;
    
  5.   }
    
  6.   int b = b + 2;
    
  7.   return b;
    
  8. }
    

The code above will return a compiler error. Why?

Answer
Example Answer 3.10: Compiler error.
  1. private int myMethod(int a, int b, String c) {
    
  2.   if (a > 0) {
    
  3.     c = "";
    
  4.     return c;
    
  5.   }
    
  6.   int b = b + 2;
    
  7.   return b;
    
  8. }
    

The method is supposed to return a int but at line 4, it returns c, which is a String.

Special method, the constructor[edit]

The constructor is a special method called automatically when an object is created with the new keyword. Constructor does not have a return value and its name is the same as the class name. Each class must have a constructor. If we do not define one, the compiler will create a default so called empty constructor automatically.

Computer code Code listing 3.11: Automatically created constructor.
  1. public class MyClass {
    
  2.   /**
    
  3.    * MyClass Empty Constructor
    
  4.    */
    
  5.   public MyClass() {
    
  6.   }
    
  7. }
    

Static methods[edit]

A static method is a method that can be called without an object instance. It can be called on the class directly. For example, the valueOf(String) method of the Integer class is a static method:

Example Code section 3.60: Static method.
  1. Integer i = Integer.valueOf("10");
    

As a consequence, it cannot use the non-static methods of the class but it can use the static ones. The same way, it cannot use the non-static attributes of the class but it can use the static ones:

Example Code section 3.61: Static attribute.
  1. private static int count = 0;
    
  2.  
    
  3. public static int getNewInteger() {
    
  4.   return count++;
    
  5. }
    

You can notice that when you use System.out.println(), out is a static attribute of the System class. A static attribute is related to a class, not to any object instance, so there is only one value for all the object instances. This attribute is unique in the whole Java Virtual Machine. All the object instances use the same attribute:

Computer code Code listing 3.12: A static attribute.
  1. public class MyProgram {
    
  2.  
    
  3.     public static int count = 0;
    
  4.  
    
  5.     public static void main (String[] args) {
    
  6.         MyProgram.count++;
    
  7.  
    
  8.         MyProgram program1 = new MyProgram();
    
  9.         program1.count++;
    
  10.  
    
  11.         MyProgram program2 = new MyProgram();
    
  12.         program2.count++;
    
  13.  
    
  14.         new MyProgram().count++;
    
  15.         System.out.println(MyProgram.count);
    
  16.     }
    
  17. }
    
Computer code Output for Code listing 3.12
4
Test your knowledge

Question 3.11: Visit the Oracle JavaDoc of the class java.lang.Integer.

How many static fields this class has?

Answer

4.

  • int MAX_VALUE,
  • int MIN_VALUE,
  • int SIZE and
  • Class<Integer> TYPE.
To learn how to overload and override a method, see Overloading Methods and Constructors.

External links[edit]


Literals Java Programming
Methods
API/java.lang.String