It’s how stuff gets done

advertisement
It’s how stuff gets done
 Methods are blocks of code that can be called from
anywhere in the program
 They take in a set of variables or nothing at all
 They can return one variable or nothing at all
 The methods are placed inside of the class declaration
 Re-Use: Methods provide a convenient way to re-use
code. If there is a specific process that occurs
repeatedly then it can be replaced at each location
with a single method call
 Management: Methods also provide a centralized
location to define a process so it can be easily changed
everywhere by changing what is inside the method.
 Encapsulation: When a method has been programed
by someone else, you can also use it without worrying
about how it works.
 The structure for a method is as follows:
public/private returnType name(input variables){
code
}
 public/private – whether the method is public or private
 returnType – what type of variable or Object the method
returns
 name – the name of the variable
 input variables – the variables or Objects that the method
takes in
 code – the code that is executed
 The following code takes in two integers, adds them
and returns their sum.
 Take note that the value that gets returned follows the
key word return.
public int add(int num1, int num2){
int sum;
sum = num1 + num2;
return sum;
}
 You can rewrite the previous method in one line of
code!
public int add(int num1, int num2){
return num1 + num2;
}
 The following method does nor return anything as
indicated by the key word void. It also does not take
in any variables
public void shout(){
System.out.print(“Hello!!!”);
}
 When primitive variables are passed into a method
they are passed by copy while objects are passed by
reference.
 So if there is a primitive variable x passed into the
method then the value will not be changed outside of
the method.
Download