User:Janjurada

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, protected 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 parameter1,            ParamTwoType parameter2) throws ExceptionName { ReturnType returnType; ...    return returnType; } ... }

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

Example	Code section 3.67: Method without returned data. private void methodName(String parameter1, String parameter2) { ... return; } 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.68: return keyword location. private void aMethod(int a, int b) { int c = 0; if (a > 0) { c = a;   return; } int c = c + b;  return; int c = c * 2; } In the code section 3.68, 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 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.69: A method modifying a variable. private void modifyValue(int number) { number += 1; } Example	Code section 3.70: Parameter by value. int i = 0; modifyValue(i); System.out.println(i); Standard input or output	Output for Code section 3.70 0 As you can see in code section 3.70, 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 object ⇔ new 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:

object.firstName	⇒	"James" object.lastName	⇒	"Gosling" object.birthDay	⇒	"May 19" Take a look at the example above:

Example	Code section 3.71: A method modifying an object. private void modifyObject(FirstClass anObject) { anObject.setName("Susan"); } Example	Code section 3.72: Parameter by reference. FirstClass object = new FirstClass; object.setName("Christin"); modifyObject(object); System.out.println(object.getName); Standard input or output	Output for Code section 3.72 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.73: A method modifying an object reference. private void modifyObject(FirstClass anObject) { anObject = new FirstClass; anObject.setName("Susan"); } Example	Code section 3.74: Parameter by reference. FirstClass object = new FirstClass; object.setName("Christin"); modifyObject(object); System.out.println(object.getName); Standard input or output	Output for Code section 3.74 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.75: In-lined method. FirstClass object = new FirstClass; object.setName("Christin"); // Start of the method FirstClass anObject = object; anObject = new FirstClass; anObject.setName("Susan"); // End of the method System.out.println(object.getName); Standard input or output	Output for Code section 3.75 Christin Variable argument list[edit] Java SE 5.0 added syntactic support for methods with variable argument list, which simplifies the typesafe usage of methods requiring a variable number of arguments. Less formally, these parameters are called varargs[1]. The last parameter can be followed with ..., and Java will box all the arguments into an array. Vararg parameter must always be the last method parameter:

Example	Code section 3.76: A method using vararg parameters. public void drawPolygon(java.awt.Point... points) { //… } When calling the method, a programmer can simply separate the points by commas, without having to explicitly create an array of Point objects. Within the method, the points can be referenced as points[0], points[1], etc. If no points are passed, the array has a length of zero. To require the programmer to use a minimum number of parameters, those parameters can be specified before the variable argument:

Example	Code section 3.77: Variable arguments. // A polygon needs at least three points. public void drawPolygon(Point p1, Point p2, Point p3, Point... otherPoints) {…} 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.12: Multiple returned variables. public class MyObject { ... /** Nested object is for return values from getPersonInfoById method */ public static class ReturnObject { private int age; private String name; public void setAge(int age) { this.age = age; }     public int getAge { return age; }     public void setName(String name) { name = name; }     public String getName { return name; } } // End of nested class definition /** Method using the nested class to return values */ public ReturnObject getPersonInfoById(int id) { int   age; String name; ...   // Get the name and age based on the ID from the database ...   ReturnObject result = new ReturnObject; result.setAge(age); result.setName(name); return result; } } 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.78: Retrieving the values. MyObject object = new MyObject; MyObject.ReturnObject person = object.getPersonInfoById(102); System.out.println("Person Name=" + person.getName); System.out.println("Person Age =" + person.getAge); Test your knowledge 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.13: Automatically created constructor. public class MyClass { /** * MyClass Empty Constructor */ public MyClass { } } 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.79: Static method. 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.80: Static attribute. private static int count = 0; public static int getNewInteger { return count++; } 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.14: A static attribute. public class MyProgram { public static int count = 0; public static void main (String[] args) { MyProgram.count++; MyProgram program1 = new MyProgram; program1.count++; MyProgram program2 = new MyProgram; program2.count++; new MyProgram.count++; System.out.println(MyProgram.count); } } Italic text