Lecture 1B- Methods
COMP2111 COMP2111: :
Object Oriented Programming Object Oriented Programming Ansif Arooj
Preparation
Scene so far has been background material and experience
Computing systems and problem solving
Variables
Types
Input and output
Expressions
Assignments
Using objects
Standard classes and methods
Decisions (if, switch)
Loops (while, for, do-while)
Next: Experience what Java is really about
Design and implement objects representing information
Object-oriented programming
Basis
Create and manipulate objects with attributes and behaviors that the programmer can specify
Mechanism
Classes
Benefits
An information type is design and implemented once
Reused as needed
Known Classes
Classes we’ve seen
String
Rectangle
Scanner
System
Classes we’ll be seeing soon
BigDecimal
But the first step is on creating methods…
Methods we’ve seen
We’ve seen method (function) before
System.out.println (“Hello world”);
The way to name methods is the same as variables
allTheWordsTogether
With the first letter of each word capitalized
Except the very first letter is lower case
Our first class with methods
public class Methods1 {
public static void main (String args[]) {
Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt();
if ( value == 1 ) validValue();
else if ( value == 2 ) validValue();
Our first class with methods, continued
public static void invalidValue() {
System.out.println ("You have entered an invalid value."); System.out.println ("The program will now exit.");
System.exit (0); }
public static void validValue() {
System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!");
System.out.println ("The program will now exit."); System.exit (0);
}
Program Demo
What’s happening there
public static void validValue() {
System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!");
System.out.println ("The program will now exit."); System.exit (0);
}
public static void main (String args[]) {
Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt();
if ( value == 1 ) validValue(); // ...
} Scanner 10
stdin
Notes on these methods
None of those two methods return a value
Notice the “void” before the method name
And none take in any parameters
Return Values
The return keyword
The return keyword immediately stops execution of a method
And jumps back to whatever called that method
And possibly returns a value (we’ll see this next)
Consider the following method
public static void foo (int x) { if ( x == 1 )
return;
System.out.println (“x is not 1”); }
Return values
At some point in those methods, Java must be told to take a value and “pass” it back
Consider angleSin = Math.sin (90 * PI/180.0);
At some point in the Math.sin() method, the sin has been computed
And that value must be “passed back” to be stored in angle
This is called “returning” a value from a method
Note that some methods don’t return a value
System.out.println(), for example
Return values (aka return types)
public class Methods2 {
public static int returnsAValue () { return 1;
}
public static double alsoReturnsAValue() { return 1.0;
}
public static void main (String args[]) { int value1 = returnsAValue();
System.out.println (value1);
double value2 = alsoReturnsAValue(); System.out.println (value2);
// The following line requires a cast
int value3 = (int) alsoReturnsAValue(); System.out.println (value3);
} }
Program Demo
Methods2.java
Return types
All a return statement does is take the value
Which could be a number
Or a value in a variable
Or an expression (such as x+1)
Parameters
Sometimes you need to pass in parameters to tell a method how to perform
Consider Math.sin() – it needs to know the angle
The parameters are listed between the parenthesis after the method name
public static void main (String args[])
The methods we will study next compute (and return) x2, x3,
and x4
The methods
public static int square (int x) { int theSquare = x * x;
return theSquare; }
public static int cube (int x) { return x * x * x;
}
public static int fourthPower (int x) { return square(x) * square(x);
A method with multiple parameters
public static int squareOrCube (int which, int value) { if ( which == 1 )
return value * value; else if ( which == 2 ) {
int cube = value * value * value; return cube;
} else
return 0; }
The main() method
import java.util.*;
public class Methods3 {
// the previous methods go here
public static void main (String args[]) {
Scanner stdin = new Scanner (System.in); System.out.println ("Enter an int value"); int value = stdin.nextInt();
int theSquare = square(value);
System.out.println ("Square is " + theSquare); System.out.println ("Cube is " + cube (value));
System.out.println ("Square is " + squareOrCube (1, value)); System.out.println ("Cube is " + squareOrCube (2,value));
System.out.println ("Fourth power is " + fourthPower (value)); }
}
Program Demo
Methods3.java
Returning objects
We can also return objects from methods
What gets returned is the reference
to the object
public class Methods4 {
public static String getCourse () { String name = "CS 101";
return name; }
Program Demo
Methods4.java
Modifying parameters
Consider the following code
public class Methods5 {
public static void changeValue (int x) { x = 7;
}
public static void main (String args[]) { int y = 5;
changeValue(y);
System.out.println (y); }
}
Program Demo
Methods5.java
Pass by value
Java is a pass-by-value language
This means that a COPY of the parameter’s value is passed into the method
If a method changes that value, only the COPY is changed
Once the method returns, the copy is forgotten
And thus the change is not visible outside the method
There are other manners of returning values that are used in other languages
Pass by reference
Variable scoping
A variable is visible within the block it is declared
Called the “scope” of the variable
public class Scoping { static int z
public static void foo (int x) { // ...
}
public static void bar () { // ...
}
public static void main (String[] args) { int y;
// ... }
}
29 This local variable is visible until
the end of the main() method This variable is visible
anywhere in the Scoping class
More on parameter passing
Modifying parameters
Consider the following code
public class Methods5 {
public static void changeValue (int x) { x = 7;
}
public static void main (String args[]) { int y = 5;
changeValue(y);
System.out.println (y); }
}
What gets printed?
5 is printed 31
5 y
Program Demo
Methods5.java
Adding a Method That Takes
Parameters
class Box {
double width; double height; double depth;
double volume() {
return width * height * depth;}
void setDim(double w, double h, double d) {
width = w; height = h;
depth = d; }}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box(); Box mybox2 = new Box(); double vol;
mybox1.setDim(10, 20, 15); mybox2.setDim(3, 6, 9);
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
} }
Program Demo
Box2.java
Method notes summary
You can put the methods in a class in any order
Java doesn’t care which one is listed first
Thus, you can call a method listed later in the method
This is different than C/C++
All methods must specify a return type
If it’s void, then no value is returned
Parameters can’t be changed within a method