The four things about methods that you need to grasp well  for the exam are:

  • Arguments are always passed by value
  • Varargs
  • The return value
  • Method overloading

Method Arguments

Method arguments are always passed by value, which means that any changes to the values of the arguments exist only within the scope of the method. However, if the argument is a reference to an object, the values of the referenced object’s fields can be changed (if they have proper access level).

Take a look at the following code. What’s its output?

Varargs

Varargs is the Java feature that allows invoking a method with an arbitrary number of arguments (0 to n). The syntax is:

parameterType... parameterName

The three things to remember about vargars parameters are:

  • There can be only one parameter of this type per method and it’s always the last parameter
  • Method can be invoked either with a sequence of arguments or with an array
  • Inside the method the argument is always treated like an array

Below there are some varargs examples:

The Return Value

A method returns to the code that invoked it when it (whichever occurs first):

  • Completes all the statements in the method
  • Reaches a return statement
  • Throws an exception

Some things you must know about the return value type:

  • When return type is void, the method doesn’t return a value but it can contain return; statements for branching
  • When return type is a class, the object returned must be of the same class or a subclass of that class
  • When return type is an interface, the object returned must implement it

Method Overloading

Method overloading is the Java feature that allows a class to have different methods with the same name whenever they have different parameter lists (type or order). The return type is not considered when differentiating methods:

 


Leave a Reply