Methods
- 100% developed as of Dec 31, 2012 Statements
- 100% developed as of Mar 10, 2013 Conditional blocks
- 100% developed as of Mar 10, 2013 Loop blocks
- 100% developed as of May 24, 2013 Boolean expressions
- 100% developed as of Feb 16, 2010 Variables
- 100% developed as of Mar 10, 2013 Primitive Types
- 100% developed as of Mar 10, 2013 Arithmetic expressions
- 100% developed as of May 24, 2013 Literals
- 100% developed as of Mar 10, 2013 Methods
- 100% developed as of May 24, 2013 String
- 100% developed as of Mar 10, 2013 Objects
- 100% developed as of Jul 5, 2012 Packages
- 100% developed as of Mar 10, 2013 Arrays
- 75% developed as of Jan 11, 2013 Mathematical functions
- 75% developed as of Jan 11, 2013 Large numbers
- 75% developed as of Jan 11, 2013 Random numbers
- 100% developed as of Apr 8, 2013 Unicode
- 100% developed as of Apr 8, 2013 Comments
- 100% developed as of Sep 27, 2007 Keywords
- 100% developed as of Aug 6, 2013 Coding conventions
- 0% developed as of Mar 26, 2018 Lambda expressions
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 a checked exception, that needs to be declared as well. It is called a method definition. The syntax of method definition is:
MyClass{ ... publicReturnTypemethodName(ParamOneTypeparameter1,ParamTwoTypeparameter2){ ... returnreturnValue; } ... }
We can declare that the method does not return anything using the void
Java keyword. For example:
privatevoidmethodName(Stringparameter1,Stringparameter2){ ... 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:
return
keyword location.
privatevoidaMethod(inta,intb){ intc=0; if(a>0){ c=a; return; } intc=c+b; return; intc=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.
Question 3.9: Consider the following code:
privateintmyMethod(inta,intb,booleanc){ b=b+2; if(a>0){ a=a+b; returna; }else{ a=0; } }
The code above will return a compiler error. Why?
privateintmyMethod(inta,intb,booleanc){ b=b+2; if(a>0){ a=a+b; returna; }else{ a=0; } }
The method is supposed to return a int
but when a
is negative or equal to 0, it returns nothing.
Parameter passing
[edit | edit source ]We can pass any primitive data types or reference data type to a method.
Primitive type parameter
[edit | edit source ]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:
privatevoidmodifyValue(intnumber){ number+=1; }
inti=0; modifyValue(i); System.out.println(i);
0
As you can see in code section 3.70, the modifyValue()
method has not modified the value of i
.
Reference type parameter
[edit | edit source ]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. An 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:
Take a look at the example above:
privatevoidmodifyObject(FirstClassanObject){ anObject.setName("Susan"); }
FirstClassobject=newFirstClass(); object.setName("Christin"); modifyObject(object); System.out.println(object.getName());
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:
privatevoidmodifyObject(FirstClassanObject){ anObject=newFirstClass(); anObject.setName("Susan"); }
FirstClassobject=newFirstClass(); object.setName("Christin"); modifyObject(object); System.out.println(object.getName());
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:
FirstClassobject=newFirstClass(); object.setName("Christin"); // Start of the method FirstClassanObject=object; anObject=newFirstClass(); anObject.setName("Susan"); // End of the method System.out.println(object.getName());
Christin
Variable argument list
[edit | edit source ]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 type of a variable parameter must be followed with ...
, and Java will box all the arguments into an array:
publicvoiddrawPolygon(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.
A method can have both normal parameters and a variable parameter but the variable parameter must always be the last parameter. For instance, if the programmer is required to use a minimum number of parameters, those parameters can be specified before the variable argument:
// A polygon needs at least three points. publicvoiddrawPolygon(Pointp1,Pointp2,Pointp3,Point...otherPoints){ //... }
Return parameter
[edit | edit source ]A method may return a value (which can be a primitive type or an object reference). If the method does not return a value we use the void
Java keyword.
However, a method can return only one value so what if you want to return more than one value from a method? You can pass in an object reference to the method, and let the method modify the object properties so the modified values can be considered as an output value from the method. You can also create an Object array inside the method, assign the return values and return the array to the caller. However, this gives a problem if you want to mix primitive data types and object references as the output values from the method.
There is a better approach, define a 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:
publicclass MyObject{ ... /** Nested object is for return values from getPersonInfoById method */ privatestaticclass ReturnObject{ privateintage; privateStringname; publicvoidsetAge(intage){ this.age=age; } publicintgetAge(){ returnage; } publicvoidsetName(Stringname){ name=name; } publicStringgetName(){ returnname; } }// End of nested class definition /** Method using the nested class to return values */ publicReturnObjectgetPersonInfoById(intid){ intage; Stringname; ... // Get the name and age based on the ID from the database ... ReturnObjectresult=newReturnObject(); result.setAge(age); result.setName(name); returnresult; } }
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:
MyObjectobject=newMyObject(); MyObject.ReturnObjectperson=object.getPersonInfoById(102); System.out.println("Person Name="+person.getName()); System.out.println("Person Age ="+person.getAge());
Question 3.10: Consider the following code:
privateintmyMethod(inta,intb,Stringc){ if(a>0){ c=""; returnc; } intb=b+2; returnb; }
The code above will return a compiler error. Why?
privateintmyMethod(inta,intb,Stringc){ if(a>0){ c=""; returnc; } intb=b+2; returnb; }
The method is supposed to return a int
but at line 4, it returns c
, which is a String.
Special method, the constructor
[edit | edit source ]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.
publicclass MyClass{ /** * MyClass Empty Constructor */ publicMyClass(){ } }
Static methods
[edit | edit source ]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:
Integeri=Integer.valueOf("10");
The static keyword makes attributes instance-agnostic. This means that you cannot reference a static attribute of a single object (because such a specific object attribute doesn't exist). Instead, only one instance of a static attribute exists, whether there is one object in the JVM or one hundred. Here is an example of using a static attribute in a static method:
privatestaticintcount=0; publicstaticintgetNewInteger(){ returncount++; }
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. This is how Java achieves one universal output stream that we can use to print output. Here is a more complex use case:
publicclass MyProgram{ publicstaticintcount=0; publicstaticvoidmain(String[]args){ MyProgram.count++; MyProgramprogram1=newMyProgram(); program1.count++; MyProgramprogram2=newMyProgram(); program2.count++; newMyProgram().count++; System.out.println(MyProgram.count); } }
4
Question 3.11: Visit the Oracle JavaDoc of the class java.lang.Integer
.
How many static fields does this class have?
4.
int MAX_VALUE
,int MIN_VALUE
,int SIZE
andClass<Integer> TYPE
.
- To learn how to overload and override a method, see Overloading Methods and Constructors.