IT 114: Introduction to Java
Class 11
Topics
Review
New Material
Homework 4
Homework 4 is due this Sunday at 11:59 PM.
You will find the assignment here.
If you have a problem or a question, make a post on the Class Discussion Area.
Review
Defining Methods
- You define a method with a special kind of Java statement
called a method declaration
- A method declaration has two parts
- The method body is a code block containing the Java statements that are executed each
time the method is run
- The method header specifies
- What Java programs can use the method
- What kind of value it creates
- The method name
- What values it needs when it is run
- The method header has the following format
MODIFIER [static
] RETURN_DATA_TYPE METHOD_NAME(PARAMETER_LIST)
- The MODIFIER determines which other Java programs can use the method
- In this class we will only use
public
as the modifier
static
is enclosed in square brackets, [ ], in the format above
- That means the
keyword
static
is optional
- We will talk about static methods later in this course
- For now will use
static
in the header for the methods we define
- The method name comes next
- Followed the the PARAMETER_LIST inside parentheses
- The parameter list has the following format
DATA_TYPE PARAMETER_NAME[, DATA_TYPE PARAMETER_NAME ...]
- The [, DATA_TYPE PARAMETER_NAME ...] mean you can have multiple parameters
- Parameters are special variables inside the method code
- We'll talk more about them a little later
Running a Method
Arguments and Parameters
Methods Can Have Many Parameters
- In GoTeam2.java the method cheer has one parameter
public static void cheer (String team)
- When we call this method we supply one argument
cheer("Sox");
- This method always prints a cheer 3 times
- But what if sometime we wanted a different number of cheers?
- I can do this by giving the cheer method another parameter
- This parameter will specify the number of cheers
- Here is the method declaration
public static void cheer (String team, int times) {
for (int i = 1; i <= times; i++){
System.out.println("Go " + team + "!");
}
}
- When we call the method we must provide a 2nd argument
cheer("Sox", );
- When we create a method we can give it as many parameters as we want
- When the method is called, there must be as many arguments in the method call
as there are parameters
- We can even declare a method with no parameters
public static void cheer () {
for (int i = 1; i <= 3; i++){
System.out.println("Go Sox!");
}
}
- When we call this method the ( ) must be empty
cheer();
- And every time we call the method it will produce the same output
Go Sox!
Go Sox!
Go Sox!
Identifiers
- When we write code we have to name things
- In Java we give names to
- Variables
- Methods
- Classes
- People who study computer languages, call these names
identifiers
- In these Class Notes, an identifier will always look like this
- All computer languages have rules specifying what characters can be used in identifiers
- In Java, identifiers must start with a letter
- That letter can be followed by any number of other letters and digits
- Java thinks of two special characters as letters when creating an identifier
- $ - dollar sign
- _ - underscore
- Java identifiers cannot contain spaces
- Remember that Java is
case sensitive
- To keep things simple, it is best to use lowercase letters
Java Class Names
- Certain things in life have to be done a certain way because it is the law
- Like which side of the road you drive on
- In the United States you must drive on the right hand side of the road
- If you don't you could be arrested
- Other things are usually done a certain way because it makes things easier
- Like having even numbered address on one side of the street
- And odd numbers on the other side
- You won't be arrested for not doing this
- But it makes life easier for everyone if you do
- People who write in particular programming languages form a community
- And they have certain ways of doing things
- Following these customs makes things easier
- Such things are called
conventions
- In Java there is a convention for class names
- Names should start with an UPPERCASE letter
- Camel case should be used with names of more than one word
New Material
Methods That Create Values
- The methods cheer and
triangles print some output
- But they did not create values that can be used outside the method
- They are perfectly good methods
- But most methods do more
- They create values that can be used in other parts of the program
- These values are given to the
java
interpreter
- So they can be passed back to the method call
Returning Values
- When a method creates a value and sends it back to the the
method call, we say it is
returning a value
- This is done with a
return
statement
which has the following format
return EXPRESSION
- Remember, an expression
is anything that can be turned into a value
- When the
java
interpreter comes to a return statement
it does the following
- Causes the running of the method to stop
- Sends the value of EXPRESSION
back to the method call
- So a method stops running when it gets to a
return
statement
- Any statements following a
return
statement in the same
code block
will never be reached
- If your code has such statements
javac
will give you
an error when you compile your code
- The method header contains important information the compiler needs
to do its job
- It has to specify what kind of value each method returns
- It learns this from the
return type
that appears in the method header right before the method name
- Even if the method does not return a value, it still needs a
return type
- The return type for a method that returns nothing is
void
- The return type has to be a valid data type
- For example
int
double
boolean
String
Example of a Method Returning a Value
- Let's look at a simple example of a method returning a value
public class Squares {
public static void main (String[] args){
int number = 3;
System.out.println(number + " squared is " + square(number));
number = 5;
System.out.println(number + " squared is " + square(number));
}
public static int square(int number){
return number * number;
}
}
- The method square takes a single
parameter of type
int
- And it return a value of type
int
- When we run this code we get
3 squared is 9
5 squared is 25
- Here is another example
public class SumsToLimit {
public static void main (String[] args){
int number = 10;
System.out.println("The sum from 1 to " + number + " is " + sum_to_limit(number));
number = 100;
System.out.println("The sum from 1 to " + number + " is " + sum_to_limit(number));
}
public static int sum_to_limit(int limit){
int sum = 0;
for (int i = 1; i <= limit; i++){
sum = sum + i;
}
return sum;
}
}
- Here the method sum_to_limit
adds the numbers from 1 to limit
- And returns the total
Why Does javac
Need the Return Type?
Method Calls Can Be Expressions
A More Useful Java Method
- The code above are examples of what programmers call "toy programs"
- They are small programs written for educational purposed
- You would never write programs like this in real life
- Below is an example of a method that does something useful
- It calculates the Body Mass Index, or BMI
- The BMI is used by doctors when advising patients about their weight
- Here is the code
public class BMICalculator {
public static void main(String[ ] args) {
System.out.println("A person of height 70 and weight 195 has a BMI of " + bmi(70, 195));
}
public static double bmi(int height, int weight){
return 1.0 * weight / (height * height) * 703;
}
}
- When this code is run, we get
A person of height 70 and weight 195 has a BMI of 27.976530612244897
Problems When Dividing Integers
- There are two things odd about the program above
- bmi takes two integer parameters
- But it's return type is
double
- The reason is that dividing two integer gives an integer result
- And precision is lost
- A doctor would not like that
- But the oddest thing is multiplying weight by 1.0
- If we do not do that we get 0 as the BMI
- weight and height are both
integer
- When two integers are divided the result is an integer
- In this case the value of the numerator, weight
is smaller than the denominator, height *
height
- This means the result will be 0
- Multiplying 703 by 0 is still 0
- But if we multiply weight by 1.0
it is converted into a decimal
- So the result of the division will also be a decimal
- This shows the kind of trouble you can get into when using
integers for anything other than counting
- A simpler and better solution is to change data type of the
parameters of the method bmi
- If we make them of type
double
the problem disappears
public class BetterBMICalculator {
public static void main(String[ ] args) {
System.out.println("A person of height 70 and weight 195 has a BMI of " + bmi(70, 195));
}
public static double bmi(double height, double weight){
return weight / (height * height) * 703;
}
}
$ java BetterBMICalculator
A person of height 70 and weight 195 has a BMI of 27.976530612244897
The main Method
- The real work in Java programs is done by methods
- You could write all the code as statements inside the main method
- But that would not be a good idea
- For one thing the code would be hard to read
- A well written program breaks a big problem down into a number of methods
- The main method then calls the methods
to do the work required
- If the method names are well chosen, simply reading the method calls
in the main method gives a good idea of what the program does
- The main method in Java is special
- All other methods have to be called to run
- Not the main method
- It is automatically called when you run the Java file
- You cannot run a Java file if it does not have a main method
- The method drives the work of the program
Class Quiz
Attendance
Class Exercise