IT 114: Introduction to Java
Class 10
Topics
Tips and Examples
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.
Tips and Examples
Use Flash Cards to Prepare for Graded Quizzes
- To studying for the graded quizzes you need to study the Class Quizzes for the previous week
- The best way to do this is to use flash cards
- You take an index card and write the question on one side
- And the answer on the other
- You should make a set of flash cards for each class
- Label them with the Class Number
- And put a rubber band around them
- I did this when taking courses for my Masters degree
- I would go through them on my way to work on the T
- There are programs that you can use to create virtual flash cards
- But it is better if you write your own cards
- The simple act of writing each card, helps you remember the material
- You can also use flash cards in reverse
- Turn them over, read the answer and guess the question
- This can be helpful when studying for the mid-term or final
Close Curly Braces Immediately When You Open Them
- Java code usually has many curly braces
- Every open curly brace, { must have a
matching closing curly brace, }
- If it doesn't you will get an error
- Most text editors used in programming do this for you
- Every time you type {, a following }
is created
- But some text editors do not do this
- The Unix editor
nano
does not supply the closing }
- Make sure every { you type has a matching }
Review
Names of Java Files
Nested for
Loops
Keywords
- Comments
are sections of code that are ignored by the compiler
- They are used to document what is happening inside the program itself
- When you write a piece of code you know how it works
- But you might remember very little about it 6 months later
- When you need to use it
- Or change it
- Starting this week all homework code must have comments
- If you don't add comments, you will lose points
- I discuss comments further here
- There are three types of comments in Java
- Single line comments
- Multiple line comments
- JavaDoc comments
- The Java compiler ignores anything that comes after //
- // begins a single line comment
- Here is an example
minDivisor = 1; // divisor cannot be zero or division by zero error will occur
- A multiple line comment starts with a slash followed immediately by an asterisk, /*
- Any text between this pair and an asterisk followed by a slash, */ , is ignored by Java
- Here is an comment from the code from a Masters project at UMB
/*
* This class manages the notification of any registered Observer
* object when changes occur in the current state of the Model component
* as a result of user invocation of one of the Action menu commands such as
* Next or Previous.
*/
- The author did not have to begin each line between the first and last with a *
- This is sometimes done to make it obvious that the comment runs several lines
- But you do not have to do this for this class
- The multiple line comment allows you to write a lengthy description of what is going on
- The third type of comment, JavaDoc comments, are not covered in this course
Mixing Data Types
- What happens when you mix values of two different
data types in a calculation?
- For example, how would the compiler handle the following
4 * 3.3
- Java has a simple rule for handling situations like this
- Convert the result to a data type that gives the most information
- In the example above an
int
multiplies a double
- If the result were converted into an
int
the value would be 13
4 * 3.3 -> 13
- But if the result is converted to
double
we get
4 * 3.3 -> 13.2
- The first example is less precise than the second
- Java always uses the data type that will not lose precision
Integer Division
- Integer division works differently than decimal division
5 / 2 -> 2
5.0 / 2.0 -> 2.5
- If you want the result of integer division to be a decimal,
multiply the result by 1.0
public class IntDivision {
public static void main(String[ ] args) {
int n1 = 5;
int n2 = 2;
System.out.println("5/2 -> " + n1/n2);
System.out.println("1.0 * 5/2 -> " + 1.0 * n1/n2);
}
}
$ java IntDivision
5/2 -> 2
1.0 * 5/2 -> 2.5
New Material
Doing Something More Than Once
- Sometimes when you write a program you find yourself doing something over and over again
- In a previous class you saw the following example of a
for
loop
for (int i = 1; i <= 5; i++){
System.out.println("Go Sox!");
}
- What if we wanted to cheer all Boston teams?
- We could do is this way
public class GoTeams {
public static void main(String[ ] args) {
for (int i = 1; i <= 3; i++){
System.out.println("Go Sox!");
}
System.out.println();
for (int i = 1; i <= 3; i++){
System.out.println("Go Pats!");
}
for (int i = 1; i <= 3; i++){
System.out.println("Go Celtics!");
}
for (int i = 1; i <= 3; i++){
System.out.println("Go Bruins!");
}
}
}
- But that is an awful lot of repetition
- We need a better way
Methods
- All the
for
loops above share a common pattern
for (int i = 1; i <= 3; i++){
System.out.println(STRING);
}
- What if we could store this common pattern somewhere
- And use it more than once
- With different values for STRING
- We can do this using something called a
method
- We define the method once
- And then we used it several times with different values
- Like this
public class GoTeams2 {
public static void main(String[ ] args) {
cheer("Sox");
System.out.println();
cheer("Pats");
System.out.println();
cheer("Celtics");
System.out.println();
cheer("Bruins");
System.out.println();
}
public static void cheer (String team) {
for (int i = 1; i <= 3; i++){
System.out.println("Go " + team + "!");
}
}
}
Defining Methods
- You define a method with a special kind of Java statement
called a method declaration
- Like a
for
loop 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)
- This can seem very confusing
- So let's go through each one of these items one by one
- 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
A Simple Method Declaration
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
Choosing Good Identifier Names
- Just because a variable name is legal doesn't mean it's a good variable name
- Consider the following code
d = s * t:
- Can you guess what this is calculating?
- How about this
distance = speed * time;
- Both expressions use legal identifier names
- But the second is more informative than the first
- It is more readable
- The code you write makes sense to you right now
- But will it still make sense a year from now?
- The name of a variable should always describe the value it holds
- The name of a method should describe what it does
- So speed is a good variable name
- But xena_the_warrior_princess is not
- Sometimes you need more than one word to describe the value contained in a variable
- When this happens, you should use the underscore character,
_ to separate words like this
course_id
student_name
first_name
- Another way to combine multiple words in a variable name is to capitalize the first letter of each new word
- Like this
courseId
studentName
firstName
- This technique is called camel case
- I prefer to use underscores since I think they are more readable
- But you are free to use either technique
- You must do something to make the start of each word in name stand out
- I don't want to see
courseid
studentname
firstname
- They are not easy to read
- This is much better
course_id
student_name
first_name
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
Class Quiz
Attendance
Class Exercise