Welcome!
Steve Bruell
101D MLH
22C:16/106 Home Page
A computer is nothing more than a general-purpose tool used
to accomplish tasks.
A computer must be instructed how to accomplish a specific
task.
A program is a list of instructions, written in a
programming language, that a computer can execute to accomplish a specific
task.
Any task is accomplished by performing a series of steps in
a definite order. This series of steps is an algorithm.
Algorithms are generally written in pseudo-code.
A programmer accomplishes a task with a computer by
developing an algorithm to perform the task, then translating the
pseudo-code algorithm to a program written in a programming language.
There are many different programming languages. Some are considered "low-level" languages and others are considered "high-level" languages. Java is a "high-level" programming language.
List of instructions for performing a process step-by-step.
Example: Automatic Gasoline Pump
Two outcomes:
Explicit result:
receipt
Side effect:
tank is filled and credit card is debited
public class Hello { public static void main(String[] args) { // Print our message System.out.println("Hello, world!"); } }
What does each of these statements mean?
Notice that the statements that are contained inside the curly braces are indented. This is not required by the compiler, but is done by convention to make the program easier to read for humans. When looking at this sample program it is easy to see that each opening curly brace has its corresponding closing curly brace. If we took out all of the carriage return / line feed characters in this program the compiler would not object. But the program would not be very readable by humans. As and example, can you tell if each opening curly brace has a corresponding closing curly brace in the following program?
public class Hello{public static void main(String[] args){System.out.println("Hello, world!");}}
Effective for large systems with many interacting objects.
Algorithm design is needed to describe the operations performed by the
objects.
Example: Crazy-eight's Card Game
Objects | Properties | Behavior |
Card | Number Suit |
Display itself Match another card |
Card Deck | Collection of cards | Shuffle itself Deal a card Tell whether empty |
Hand | Collection of cards Number of cards |
Add a card Remove a card |
Discard Pile | Collection of cards | Add a card |
Player | Position Hand |
Play a turn |
We begin the course with Procedural Programming to introduce the basic concepts
of programming with Java. We will also introduce most of the commands available
to a Java programmer.
Problem: Convert 86º fahrenheit into celsius
Algorithm:
86º - 32º = 54º
54º · 5 / 9 = 270º / 9 =
30º celsius
Write this calculation in Java output commands:
System.out.print("86 degrees fahrenheit is equivalent to "); System.out.println((86 - 32) * 5 / 9 + " degrees celsius.");
Note: "print" means print to screen
without a return.
"println"
means print followed by a return.
"+" means
String concatenation.
public class Degrees { public static void main(String[] args) { System.out.println("87 degrees fahrenheit is equivalent to "); System.out.println((87 - 32) * 5 / 9 + " degrees celsius."); } }
Problems:
Example of variable declaration:
int fahrDegrees; double celDegrees;
Assignment of Values to Variables
fahrDegrees = 86; celDegress = (fahrDegrees - 32.0) * 5.0 /9.0;
public class Degrees1 { public static void main(String[] args) { int fahrDegrees; double celDegrees; fahrDegrees = 90; celDegrees = (fahrDegrees - 32.0) * 5.0 / 9.0; System.out.print(fahrDegrees + " degrees fahrenheit is equivalent to "); System.out.println(celDegrees + " degrees celsius."); } }
Numbers are stored with binary (base 2) representations inside the computer.
Two Basic Kinds
Declaration: int num, count;
num
? |
count
? |
Declaration with initialization: int sum = 0, product = 1;
sum
0 |
product
1 |
Rule: Variables start with a letter and may continue with letters, digits, or underscores.
Example:
double tax_factor1, tax_factor2;
Example (better):
double taxFactor1, taxFactor2;
Java convention: Begin variables with lowercase letters.
Binary operations: +, -, *,
/, %
m % n is the remainder on dividing m
by n
Precedence
Higher: *, /,
%
Lower: +, -
Left-to-right associativity (grouping)
5 - 3 + 6 means (5 - 3) + 6, which
evaluates to 8, not -4 (which would be obtained from 5 - (3 + 6)).
Parentheses are allowed to override precedence.
5 - (3 + 6) evaluates to -4.
Examples:
36 / 4 - 4 + 11 evaluates to 16
8 + 13 / 5 * 2 evaluates to 12
46 % 8 evaluates to 6
76 % 10 % 3 evaluates to 0
int m = 15, n = 3;
(m + 1) / (n - 1) evaluates to 8
(m + 1.0) / (n - 1.0) evaluates to
8.0
m + 1 / n - 1 evaluates to 14
m + 1.0 / n - 1 evaluates to
14.33333333333333
variable = expression;
Kinds of Expressions
Type |
Examples of Literals of Indicated Type |
int | 25, -466, 0 |
double | 18.23, 6.742E8, 3844e-5 |
boolean | true, false |
char | 'a', 'Z', '#' |
String | "this is a string" |
/* this is a comment */
// another comment
Given:
Purchase price in cents
Payment in cents
Assume change is made only in quarters, dimes, nickels, and pennies.
Provide the number of coins necessary for change using the least number of
coins.
Example:
price = 126
payment = 210
change = 84
number of quarters = 84 / 25 = 3
remaining = 84 % 25 = 9
number of dimes = 9 / 10 = 0
remaining = 9 % 10 = 9
number of nickels = 9 / 5 = 1
number of pennies = 9 % 5 = 4
This example serves as the basis for writing the Java program to perform the
calculation.
Java code:
public class Change { public static void main(String[] args) { int price = 126; // "Input phase" int payment = 210; int change = payment - price; // Calculation phase int quarters = change / 25; int remaining = change % 25; int dimes = remaining / 10; remaining = remaining % 10; int nickels = remaining / 5; int pennies = remaining % 5; // Output phase System.out.println("Number of quarters = " + quarters); System.out.println("Number of dimes = " + dimes); System.out.println("Number of nickels = " + nickels); System.out.println("Number of pennies = " + pennies); } }
Output: Number of quarters = 3 Number of dimes = 0 Number of nickels = 1 Number of pennies = 4
This program will be more useful when we can provide the price and payment as input, so that the program can be run on different sets of data.
type list-of-variables;
Example of
types: int, double, char, boolean, String
public class Expressions { public static void main(String[] args) { int k, m, n; double x, y, z; String s, t, u; char c, d; m = 5; n = 13; k = n + 8 / 5; System.out.println("k = " + k); // k = 14 x = 3.6; y = -10.5; z = x / 2 * y; System.out.println("z = " + z); // z = -18.9 c = 'A'; System.out.println("c = " + c); // c = A d = '&'; System.out.println("d = " + d); // d = & s = "hello"; t = "world"; u = s + t; System.out.println("u = " + u); // u = helloworld u = s + "\n" + t; System.out.println("u = " + u); // u = hello // world } }
Input is relatively difficult to do in Java. A beginner needs to postpone
doing input directly in Java.
We will use a special class, called TextInput, written by Ken Slonneger.
How to Use TextInput
These input methods look for numbers separated by whitespace, typed by the
user.
Whitespace is either a space, tab, or return.
The compiled code for the class can be found in the file text.jar. You'll need this file only if you download JCreator on your home PC.
If Command: we can tell the computer to execute a section of code only when a given condition is true by using the if command.
if (boolean-expression)
command; //
command executed if boolean-expression evaluates to true
or
if (boolean-expression)
command; //
this command executed if boolean-expression evaluates to true
else
command; //
this command executed if boolean-expression evaluates to false
Examples:
if (degrees >
80)
System.out.println("It is hot today.");
(By
convention we indent the command(s) that are subordinate to the if.)
if (degrees >
80)
System.out.println("It is hot today.");
else
System.out.println("It is a nice day today.");
Block Command: we can tell the computer that a group of statements are to be executed as a result of a condition being true (or false). To do so we enclose those statements in curly braces.
{
Sequence of declarations and commands
}
Note that no semicolon follows this command.
What if we want more than one command with an if? Use a block command.
if (boolean-expression)
{
Sequence of commands
}
Example:
if (degrees > 80)
{
System.out.println("It is hot today.");
System.out.println("Let's go swimming.");
}
else
{
System.out.println("It is a nice day today.");
System.out.println("Let's have a picnic.");
}
Relational operators produce boolean values == equal to ("=" is assignment operator) != not equal to < less than > greater than <= less than or equal >= greater than or equal
Check if an integer is even
public class Even { public static void main(String[] args) { // prompt user for input System.out.print("Type an integer: "); // retrieve input from console TextInput input = new TextInput(); int k = input.readInt(); // determine if value read is even or odd if ((k % 2) == 0) System.out.println(k + " is even"); else System.out.println(k + " is odd"); } }
How do we tell if a number is divisible by 5?
int m = 101;
if ((m % 5) == 0)
{
System.out.println("m is divisible by 5.");
}
else
{
System.out.println("m is not divisible by 5.");
}
Can use boolean variable in if command:
int m = 18; boolean b; b = (m % 2) == 0; if (b) System.out.println("m is even");
Can use literal in if command:
if (true) // always executes following command some command;
|| (logical or), && (logical and), ! (logical not)
Expression | Evaluates to |
! true | false |
! false | true |
true && true | true |
true && false | false |
false && true | false |
false && false | false |
true || true | true |
true || false | true |
false || true | true |
false || false | false |
Test whether k is even. If it is, determine whether it is negative, zero, or positive.
public class EvenAnd { public static void main(String[] args) { // prompt for input System.out.print("Input an integer: "); // retrieve input TextInput in = new TextInput(); int k = in.readInt(); // determine whether k is even AND negative, zero, or positive if ((k % 2) == 0) { System.out.print(k + " is even "); if (k < 0) System.out.println("and negative."); else if (k == 0) System.out.println("and zero."); else System.out.println("and positive."); } else System.out.println(k + " is odd."); } }
Nested if's can frequently be replaced by logical operators:
if (((k % 2) == 0) && (k < 0)) System.out.println(k + " is even and negative."); else if (((k % 2) == 0) && (k == 0)) System.out.println(k + " is even and zero."); else if ((k % 2) == 0) System.out.println(k + " is even and positive.");
This code is not necessarily better.
if (x = y) is normally an error: using assignment operator (=) instead of comparison operator (==).
if ((1 <= m) && (m <= 10)) System.out.print("Hello "); System.out.println("world");
Highest | - ! |
unary minus logical not |
*, /, % | multiplicative operators | |
+, - | additive operators (binary) | |
<. <=, >, >= | ||
==, != | ||
&& | logical and | |
|| | logical or | |
Lowest | = | assignment |
Example:
public class Rounding { public static void main(String[] args) { double x = 85.0, y = 307; System.out.println("x / y = " + x / y); } }
prints:
x / y = 0.2768729641693811
If that's the number of decimal digits you want fine. But say you want only 3 digits after the decimal point.
Need to use a method:
Math.rint(d)
that takes a double d and returns that double rounded to the nearest whole number (10.5 rounds to 10.0 (yes, that is right)). (Note: real numbers midway between two integers will round to the closest even integer, so 11.5 will round to 12.0.)
Math.rint(0.3423728) produces the value 0.0.
Solution: Move the decimal point three positions to the right
(multiply by 1000.0), round the number, and then put the decimal point back in
its proper position (by dividing by 1000.0). Specifically, do:
double ans = Math.rint(1000.0 * d) / 1000.0;
In the example above do the following:
public class Rounding3 { public static void main(String[] args) { double x = 85.0, y = 307; System.out.println("x / y = " + Math.rint(1000.0 * (x / y)) / 1000.0); } }
which prints:
x / y = 0.277
A String is an object in Java. We will study objects at length later in the course. For now we will use them without an in depth understanding of the details.
A sequence of characters between double quotes is a String in Java. An example of a String literal is "Why did the chicken cross the road?".
We use escape characters to tell the compiler that there is a special character in a string. If we want a String to contain a double quotation mark how can we do it?
\n is how we insert a carriage return/line feed into a String.
\" is how we insert a double quotation mark in a String.
\\ is how we insert a backslash into a String.Example use:
"This String contains several \"special\" characters.\nOne of those characters is a double backslash \"\\\\\"."
would print as:
This String contains several "special" characters.
One of those characters is a double backslash "\\".
String concatenation
String s = "Hello"; String t = "world"; String u = s + t; // u has the value "Helloworld"
s.substring(start,pastEnd)
If s is a string variable (or literal), the method call returns the substring of s consisting of characters in positions start, start+1, ... , pastEnd-1.
s.substring(0,1) // evaluates to "H" u.substring(3,6) // evaluates to "low"
s.length()
If s is a string variable (or literal), the method call returns the number of characters in the string.
System.out.println("The String u has length of " + u.length()); // prints out "The String u has length of 10"
s.indexOf(substring)
If s is a string variable (or literal), the method call returns position of the first character in s where the entire substring occurs for the first time in s, returning -1 if the search fails.
System.out.println("The index of r in u is " + u.indexOf("r")); // prints out "The index of r in u is 7"
s.lastIndexOf(substring)
Works the same way as indexOf(substring), except that it searches from the end of the String
String a = new String("String equality"); String b = "String equality";
Note: when a variable is assigned a String value, it is given a REFERENCE to
the string object.
if (a == b) // NOT TRUE (fails because a and b are different references) { System.out.println("a equals b"); }
Comparison between strings must be done with the operation "equals."
if (a.equals(b)) // IS TRUE { System.out.println("a has the same characters in the same order as b"); } else { System.out.println("a and b do not have the same characters in the same order"); }
s.charAt()
To get the character at a certain position of a String we use charAt(). This method returns a char that is the character at the desired position of the String.
char ch = u.charAt(0); // Assigns the char value 'H' to variable ch;
Note that if we try to get a character at a position that does not exist we get an error.
s.toUpperCase()
We can convert all of the alphabetical characters of a string to uppercase with this method.
String s1 = u.toUpperCase(); // s1 now holds "HELLOWORLD"
s.toLowerCase()
We can convert all of the alphabetical characters of a string to lowercase with this method.
String s2 = u.toLowerCase(); // s2 now holds "helloworld"
s.trim()
Sometimes we need to strip off any leading or trailing spaces from a string. The trim() method does this for us.
String s3 = " There are two leading spaces and two trailing spaces here "; System.out.println("s3 holds " + s3); System.out.println("After we trim the spaces s3 holds " + s3.trim());
Assume we have created the following text object using TextInput text = new TextInput();
String str = text.readLine();
Reads the string consisting of all characters typed up to but not including the return.
String word = text.readWord();
Reads next clump of letters and apostrophes.
String token = text.readToken();
Reads next clump of characters delimited by whitespace.
Examples:
public class StringExample { public static void main(String[] args) { // create text object TextInput tin = new TextInput(); // prompt for input System.out.print("What is your name? "); // retrieve line of input String name = tin.readLine(); // obtain first character char ch = name.charAt(0); // append a blank String initial = ch + " "; // convert to uppercase initial = initial.toUpperCase(); // obtain first character String temp1 = initial.substring(0,1); // obtain rest of characters String temp2 = name.substring(1,name.length()); // remove spaces at front and back temp2 = temp2.trim(); // output System.out.println("Hello " + temp1 + temp2); } }
Problem: Print Date
Read three numbers, mm, dd, yyyy, and print the date in the common form: July 4, 2002.
Analysis:
Use TextInput to read the numbers.
Day and year are ready to be output immediately.
Use a cascading if command to test the month and find the proper string.
public class Day { public static void main(String[] args) { TextInput ti = new TextInput(); System.out.print("Enter month (mm): "); int month = ti.readInt(); System.out.print("Enter day (dd): "); int day = ti.readInt(); System.out.print("Enter year (yyyy): "); int year = ti.readInt(); String ans = ""; if (month == 1) ans = "January"; else if (month == 2) ans = "February"; else if (month == 3) ans = "March"; else if (month == 4) ans = "April"; else if (month == 5) ans = "May"; else if (month == 6) ans = "June"; else if (month == 7) ans = "July"; else if (month == 8) ans = "August"; else if (month == 9) ans = "September"; else if (month == 10) ans = "October"; else if (month == 11) ans = "November"; else if (month == 12) ans = "December"; ans = ans + " " + day + ", " + year; System.out.println(ans); } }
Note that we do not perform any input validation for this program. What happens if we input 25, 50, 2002?
A method is a group of commands that we want to be executed as a group. Sometimes we want that group of commands to calculate a value and return that value. Sometimes we don't want the method to return anything, just perform some tasks.
We can create our own methods to carry out our desired tasks. When we have written our programs so far, we have been putting commands into the body of the "main" method of the program.
To write a new method we must define it. We define a method by creating its header and its body. We include our new method definition between the opening and closing curly braces that define the class. If our class has more than just the main method, the order in which the methods appear inside the class is irrelevant.
The parts of a method header are:
visibility modifier - public (there are others we will learn
about later).
memory binding modifier - static (We will learn more about
this when we study objects. For now all of our methods will be static.)
a return type for our method - void for no return type, any
other defined type is legal.
a name for the method - we define the names of our
methods. Use descriptive names. JeffsMethod is not very descriptive, better
would be validateInput. Convention says that the first character of the name
is lowercase. The first letter of any other words in our name are
capitalized.
the parameter definition - what type of data will the method be asked to work on? The main method works on an array of Strings. That array is called "args". ( We will learn about arrays later.)
After the header has been declared we start the body. The body of a method is a block of code. We use the block command to delineate the start and stop of our method body.
Inside the body we can include almost any valid Java commands. We can declare variables, execute other methods, etc.
If in the header we said that the method will return a value of some type, then inside the body of the method we must include a "return" statement. The return statement returns the computed value to the statement that executed our method. When the return statement is executed, the compiler exits our method and resumes executing commands where it left off before executing our method.
When the computer executes a program, it starts at the first statement in the main method and executes the commands in order after that. When it encounters a call to a method, control passes to the header of that method. If there are any parameters declared in the header, then the compiler reserves memory for those variables and puts the data into those variables that was passed in from the calling statement. Then the body of the method is executed starting from the first statement in the body. When the last statement of the method is executed or a return statement is executed, control passes back to the statement that called the method. See the text for a picture of this behavior.
Consider the following program:
public class Methods { public static void main(String args[]) { String str1 = "I was declared inside main of the Methods class."; System.out.println("Inside the main method str1 has the value \"" + str1 + "\""); System.out.println("I am about to execute the method called printMessage."); printMessage(); System.out.println("I am back inside the main method."); System.out.println("Inside the main method str1 has the value \"" + str1 + "\""); } public static void printMessage() { System.out.println("I have entered method printMessage"); String str1 = "I was declared inside method printMessage"; System.out.println("Inside method printMessage str1 has the value \"" + str1 + "\""); System.out.println("I am about to leave the printMessage method"); } }
It produces the following output:
Inside the main method str1 has the value "I was declared inside main of the Methods class." I am about to execute the method called printMessage. I have entered method printMessage Inside method printMessage str1 has the value "I was declared inside method printMessage I am about to leave the printMessage method I am back inside the main method. Inside the main method str1 has the value "I was declared inside main of the Methods class."
Creating methods gives us tools we can use to solve bigger problems. Consider the phone answering machine. It is making use of a "method" called "record sound." The electrical engineers that invented the answering machine recognized that someone else developed a "method" to record sound waves. All the engineers had to do was to feed that "method" the sound waves from the phone. They used a component, or tool, that already existed so they did not have to reinvent the recording process. We can do the same. We can put together tools to accomplish complex tasks. We can use these tools over and over again in other programs without having to create the algorithm and translate it into Java every single time we want to solve the same problem. This is known as "code reuse."
If we want to execute the same set of code several times, we could write those lines of code for each time we want to execute them, or put them in a method and call the method each time we need that code executed. This makes for code that is easier to read and follow. It also makes it easier to change the code later. If we need to change the process that is to be repeated several times, we would have to make the exact same change every place we wrote the code, or just change it once in the method.
Putting code into a method allows for abstraction of a task. Consider the program to make change. First, we update it to read the price and payment from the keyboard.
public class Change1 { public static void main(String[] args) { // Declare our TextInput Object TextInput tin = new TextInput(); // Prompt the user to enter the price System.out.print("What is the price? "); // Read the price from the keyboard int price = tin.readInt(); // Prompt the user for the payment System.out.print("What is the payment? "); // Read the payment from the keyboard int payment = tin.readInt(); // Now do our calculations like before. int change = payment - price; int quarters = change / 25; int remainder = change % 25; int dimes = remainder / 10; remainder = remainder % 10; int nickels = remainder / 5; remainder = remainder % 5; int pennies = remainder; // output result System.out.println("Quarters: " + quarters); System.out.println("Dimes: " + dimes); System.out.println("Nickels: " + nickels); System.out.println("Pennies: " + pennies); System.out.println("Total change: " + change); } }
Let's now write the same program with methods.
public class Change2 { public static void main(String[] args) { // Get the price and payment. int price = getPrice(); int payment = getPayment(); // Now make sure they paid enough for the sale, and that the sale // amount is a positive number. if (!validInput(price,payment)) { // If we made it here then the user gave us bad input. // Print a message and exit the program. System.out.println("Invalid input. Please try again."); return; } // If we made it here then we have valid input. // Calculate the amount of change to give. int change = payment - price; // Now get the number of quarters to return . int quarters = getNumCoins(25,change); // Compute remaining change to give. int remainder = change % 25; // Now get the number of dimes. int dimes = getNumCoins(10,remainder); // Compute remaining change to give. remainder = remainder % 10; // Get the number of nickels. int nickels = getNumCoins(5,remainder); // Compute remaining change to give. remainder = remainder % 5; // The remaining change to give must be given in pennies. int pennies = remainder; // Print the results. printResults(quarters, dimes, nickels, pennies, change); } public static int getPrice() { // Declare a TextInput Object. TextInput tin = new TextInput(); // Prompt the user to enter the price. System.out.print("What is the price? "); // Read and return the price from the keyboard. return tin.readInt(); } public static int getPayment() { // Declare a TextInput Object. TextInput tin = new TextInput(); // Prompt the user to enter the payment. System.out.print("What is the payment? "); // Read and return the payment from the keyboard. return tin.readInt(); } public static boolean validInput(int price, int payment) { if (price < 1) { // We don't give items away so price must be at least 1 return false; } // If we made it here then the price must be valid. // Now make sure that the payment is at least as high // as the price. if (payment < price) { return false; } // If we made it here then the input must be valid return true; } public static int getNumCoins(int value, int changeLeft) { return changeLeft / value; } public static void printResults(int quarters, int dimes, int nickels, int pennies, int change) { System.out.println("Quarters: " + quarters); System.out.println(" Dimes: " + dimes); System.out.println(" Nickels: " + nickels); System.out.println(" Pennies: " + pennies); System.out.println("Total change: " + change); } }
Use a method to accomplish one specific task, like validate
input or print results.
Variables declared inside a block command can be seen and
used only inside that block. That is, the "scope" of a variable is the
block command where it was declared, and any blocks of code started inside
the block where the variable was declared.
Variables declared inside a block command go away after the
program executes that block command.
Local variables in one method can have the same name as
local variables in another method because of variable scope rules.
A good method is short enough to fit on one page or screen.
In order to write a method we must know exactly what
behavior is expected from the method. Does it return any values? If so, what
is the type of that value? Does it require inputs to be able to carry out a
calculation? If so, what are they and what is their type?
For now, all of the methods we write in a program must be
included inside the block command that delineates the class.
The order in which the methods of a program appear is
irrelevant.
If we put repeated code into a method, then when we need to change that code we have to change it in only one place.
Change the focus of programming from the program units to the data that need to be manipulated.
Each data item has its own type.
5 is of type int
2.63 is of type double
‘H’ is of type char
false is of type boolean
"hello" is of type
String
OOP allows us to define new types of data:
The data values are the objects of OOP.
The new types are (defined by) the classes in OOP.
Some new classes that might be useful:
Date Domino Employee
Coin Student Point
Die Button
An object is an instance (a specimen) of a class.
Data fields (variables) that define its state or
properties.
Operations (methods) that define its behavior.
Example (outline only)
class Die
Possible fields
Number of sides
Color
Possible behavior
Roll itself, producing a number
Return its number of sides
Return its color
Change its color
These fields and behaviors are defined in a class definition.
class Die
{
// data declarations and method declarations
}
Such a class definition creates a new kind or type of data, namely Die objects.
Use the new operator and specify initial information
Die d1, d2; // declares variables of type Die
d1 = new Die(6, Color.blue);
d2 = new
Die(20, Color.red);
Color.blue and Color.red are two of the thirteen color
constants provided in Java.
Suppose roll is a method defined inside the Die class with the syntax:
int
roll()
Using the roll method:
int m = d1.roll(); // returns a value 1…6
int n = d2.roll(); //
returns a value 1…20
Syntax of a call to a method belonging to an object:
objectReference.methodName(parameters)
Method may be a function or a procedure.
Example of a procedure:
d1.setColor(Color.orange); // changes color to orange
instance
methods and
class methods
Difference has to do with ownership
Instance methods belong to objects of the class.
Class methods belong to the class.
Classes are used to create (define)
objects.
Examples of classes: Die, String, Employee
Behavior of the objects created from these classes is defined by instance methods.
d1.getColor(); // returns the current color of the d1 Die
d2.setColor(Color.white); // tells the d2 Die to change its color
Constructors are a kind of instance method automatically called when an object is created.
String s1 = new String(); // empty string
String s2 = new String("herky");
String s3 = "herky"; // exception: no new
String s4 = s2;
The String class has a constructor with no parameters and one with a single parameter.
s1.length() returns 0
s2.length() returns 5
s2.indexOf("ky") returns 3
s2.indexOf("hk") returns -1
s2.substring(1,4) returns "erk"
s2.concat(s3) returns "herkyherky"
s2.equals(s3) returns true
s2 == s3 returns false
s2 == s4 returns true
s2.charAt(1) returns 'e'
String str = " 152 ";
str.trim() returns "152"
Belong to the class, not to the individual objects.
Used to define "utility" methods that perform various operations.
Any data that they use must be supplied as parameters because class methods have no object whose data can be used implicitly.
May be executed even if no objects have been created.
Defined with the keyword static.
Called by naming the class.
String.valueOf(5723); // returns "5723"
Class need not be named if call is from within the class.
Math.sqrt(2) returns 1.4142135
Math.random() returns a random double, 0≤d<1
Math.rint(7.82) returns 8.0
Math.abs(-13) returns 13
Integer.parseInt("5723") returns 5723 as an int
Values
Primitive data items:
int, double, char, boolean
Objects:
String, Point, Date, Die
Variables
Symbols that name memory locations; these locations may contain values.
Examples:
int k; // a variable
k = 5; // put a value in k’s location
k = k + 2; // change value in k's location
System.out.println(5); // 5
System.out.println("k"); // k
System.out.println(k); // 7
Compare if (x == k) … with if (x == 'k') …
TextInput ti = new TextInput();
String ans = ti.readWord();
String yes = "no";
Compare
if (ans.equals(yes)) …
with if (ans.equals("yes")) …
Java has two kinds of methods with
overlap between the kinds.
Functions
produce a value
used as an expression (consume the result)
require a command to send the value back
return value;
Procedures
no explicit result
defined as returning void
make changes in the state of the computer
used as a command
ways
to exit a procedure
> execute the command return;
> complete execution of the body (drop off end)
belong to the class itself
use static modifier
independent of the objects created
can be called from anywhere
belong to the individual objects
can be called only with an existing object
Die d = new Die(12,Color.red);
d. roll();
or
roll(); // inside another Die instance method
need to be defined inside the class that defines the objects they will be associated with
Clarification
Since we are not defining our own objects yet, we must concentrate on class methods (Procedural Programming)
If we want
to define an operation on String objects, it must be a class method since we
cannot get into the class definition for the String class (it was written by
Sun several years ago).
Write a method that takes three integers as parameters and returns the largest of the three.
public class largest3 { static int largest(int n1, int n2, int n3) { if (n1 > n2) { if (n1 > n3) return n1; else return n3; } else if (n2 > n3) return n2; else return n3; } public static void main(String[] args) { int largestOfThree = largest(2,22,12); System.out.println("The largest of 2, 22, and 12 is " + largestOfThree); } }
The method isEmpty will take a String as a parameter and tell whether that string is empty, meaning that it returns true or false.
public class IsEmptyTest { static boolean isEmpty(String s) { boolean result = (s.length() == 0); return result; } public static void main(String[] args) { System.out.println("Is \" \" an empty string? " + isEmpty(" ")); System.out.println("Is \"\" an empty string? " + isEmpty("")); } }
Alternative definition
public class IsEmptyTest2 { static boolean isEmpty(String s) { return s.equals(""); } public static void main(String[] args) { System.out.println("Is \" \" an empty string? " + isEmpty(" ")); System.out.println("Is \"\" an empty string? " + isEmpty("")); } }
Calling the isEmpty method, using strings read from the console.
public class IsEmptyTest3 { static boolean isEmpty(String s) { return s.equals(""); } public static void main(String[] args) { TextInput text = new TextInput(); System.out.print("Enter a string: "); String str = text.readLine(); if (isEmpty(str)) System.out.println("The string is empty."); else System.out.println("The string has characters."); } }
Note: We cannot make isEmpty an instance method because we cannot add code inside the String class.
Class methods act as utility operations working outside of the realm of objects, although they may take objects as parameters.
Write a method that takes a positive integer as a parameter and prints the last three digits, one to a line, unit’s digit first. Do nothing if the number is not positive.
public class printDigitsTest { static void printDigits(int num) { if (num > 0) { int units = num % 10; int tens = (num / 10) % 10; int hundreds = (num / 100) % 10; System.out.println(units); System.out.println(tens); System.out.println(hundreds); } } public static void main(String[] args) { System.out.print("Enter a number: "); int m = (new TextInput()).readInt(); printDigits(m); } }
Note that we create one TextInput object and use it immediately.
Since it is not assigned to a variable, it can only be used once.
Parentheses are required because the dot has higher precedence that the new operator.
Write a method that takes an integer as a parameter and returns a String representing the month specified by the number, 1≤ month ≤12.
To convert the month integer into a String, create a String, called months, containing all the month names with each name taking 10 characters.
Then select the appropriate 10-character substring for the month desired.
For example, the 1st month will lie in character positions 0 to 9, the 2nd month will lie in character positions 10 to 19, and the 5th month will lie in character positions 40 to 49.
Use the instance method trim() to remove the extra spaces.
public class monthStringTest { static String monthString(int month) { String months = "January February March April " + "May June July August " + "September October November December "; int m = month - 1; // 0 <= m <= 11 String s = months.substring(10 * m, 10 * m +10).trim(); return s; } public static void main(String[] args) { TextInput text = new TextInput(); System.out.print("Enter the number of a month between 1 and 12: "); System.out.println(monthString(text.readInt())); } }
Observe that this method is a function.
The purpose of an expression is to produce a value.
In addition, some expressions may have side effects.
Side effect: Change in the value of a variable.
Output to the display screen.
var = expr;
Normally acts as a command.
But it may also serve as an expression; its value is the value assigned to the variable on the left.
m = 5 + (n = 3); // n get 3 and m gets 8
if ((m = m + 6) > 0) … // m gets 14
This usage is poor programming style.
m += 5; means m = m+5;
k *= 2; means k = k*2;
x /= 10; means x = x/10;
p &&= q; means p = p && q;
n
>>>= 2;
means n = n >>> 2; //
shift n, 2 bits to right
These expressions may be used as commands:
m++; // has the effect of m = m + 1;
k--; // has the effect of k = k - 1;
k = k + 1; m = m – 1;
++k; --m;
k++; m--;
k += 1; m –= 1;
Preincrement
When ++k occurs in a larger expression, the value of k is augmented before it is accessed (used).
k = 5;
m = ++k; // k gets 6, m gets 6
Postincrement
For k++, the value is accessed before k is augmented, and that previous value is used in the expression.
k = 5;
m = k++; // k gets 6, m gets 5
These expressions can lead to obscure code:
m = 5; m = 5;
n = m++ * m; n = m * m++;
// n gets value 30 // n gets value 25
public class Trace { public static void main(String [] args) { System.out.println("Starting main"); int k = 20; one(k); System.out.println("Back from one"); k = 5; one(k); System.out.println("Back from one again"); System.out.println("Done with k = " + k); } static void one(int m) { System.out.println("Entering one with m = " + m); int ans = 1; m = m * m; if (m < 100) ans = two(m, 1.2); System.out.println("ans = " + ans); System.out.println("Leaving one with m = " + m); } static int two(double x, double y) { System.out.println("Entering two"); double z = x * x + y * y; System.out.println("Leaving two with z = " + z); return (int)z; } }
/*************************** Here's the output
Starting main
Entering one with m = 20
ans = 1
Leaving one with m = 400
Back from one
Entering one with m = 5
Entering two
Leaving two with z = 626.44
ans = 626
Leaving one with m = 25
Back from one again
Done with k = 5
***************************/
Consider the code:
if (m > 0)
if (n > 0)
System.out.println("m and n are positive");
else
System.out.println("m is <= 0");
Note ambiguity: To which if does else belong?
An else clause always belongs to the if of the preceding command (the closest pending if).
Indenting and logic are incorrect.
Try m = 10 and n = -3.
Be careful to indent correctly.
Use braces (a block command) to group commands.
if (m > 0)
{
if (n > 0)
System.out.println("m and n are positive");
}
else
System.out.println("m is <= 0");
In simulation problems we frequently want to create an integer in some given range randomly.
Problem
Select a random number between 1 and 100.
Solution
double d = Math.random();
0 <= d < 1
Number of possibilities (=100 in
the following example) becomes a multiplier:
0 <= 100 * d < 100
Truncate to an integer using a
cast:
(int) (100 * d) is one of the values 0, 1, 2, ..., 0=98, 99
Add the first value in the range:
1 + (int) (100 * d) is one of the values 1, 2, 3, ..., 99, 100
Example:
public class GenerateRandom { public static void main(String[] args) { double d = Math.random(); // 0 <= d < 1 int num = (int) (100 * d); // 0 <= num < 100 num = num + 1; // 1 <= num <= 100 System.out.println("Random number between 1 and 100 is " + num); } }
Each step is a task. Let's make a method for each task.
Will this algorithm solve our problem? It will if we define the methods.
/*
The printRules() method does not receive any input.It just prints
some lines
to the screen.
*/
public static void printRules()
{
// The body will contain just some print statements.
}
/*
The generateNumber() method will not need any inputs.
It will generate a random int between 1 and 100
inclusive and return that int.
*/
public static int generateNumber()
{
return (int)(Math.random() * 100) + 1;
}
/*
The playTurn() method receives a number that says which
turn we are playing. We will need this method to return
true or false telling the caller whether the player won
the game or not.
This method prompts the player for their guess. It reads the
input and validates it. If the input is not valid a message is
displayed and the method returns false. If the input is valid
then this method determines if the player's guess is correct,
too high, or too low. A message is displayed accordingly. If
the guess was the correct number the method returns true,
otherwise false.
*/
public static boolean playTurn(int turn)
{
// Prompt player for their guess and capture it.
int guess = getGuess(turn);
// validate the guess
boolean isValid = validateInput(guess);
// Handle the case where the input is invalid.
if (!isValid)
{
System.out.println("Please guess a number between 1 and 100
inclusive");
return false;
}
// If we made it here then the input was valid so compare it to
// the correct number
if (guess == number)
{
System.out.println("Congratulations! You win!");
return true;
}
else
{
// Print proper message and return false
if (number < guess)
{
System.out.println("The correct number is
lower");
}
else
{
System.out.println("The correct number is
higher");
}
return false;
}
}
This method calls some helper methods to help him get his job done. Let's define those helper methods.
/* Class GuessMyNumber This class plays a game with a user. The program generates a random number between 1 and 100. The player then has 10 turns to guess the number. The program prompts the player for their guess. The player's guess is validated. If the guess is not valid a message is displayed and the turn is over. If the guess is valid then a message is displayed stating whether the correct number is higher, lower, or exactly correct. If the player guesses the number within 10 turns they win and the game ends. Inputs: There are no command line inputs to this program. The user is prompted to enter integers. Outputs: Messages are displayed to the screen. History: 06/17/02 Jeff LeBeau. ******************************************************/ public class GuessMyNumber { static int number; public static void main(String[] args) { // Generate the number number = generateNumber(); if (playTurn(1)) return; if (playTurn(2)) return; if (playTurn(3)) return; if (playTurn(4)) return; if (playTurn(5)) return; if (playTurn(6)) return; if (playTurn(7)) return; if (playTurn(8)) return; if (playTurn(9)) return; if (!playTurn(10)) { System.out.println("Sorry! You lose."); } } /******************************************************* The printRules method does not receive any input. It just prints some lines to the screen *******************************************************/ public static void printRules() { System.out.println("Welcome to Guess My Number"); System.out.println("I have picked a number between 1 and 100 inclusive."); System.out.println("You must try to guess my number in 10 turns or less.\n\n"); } /******************************************************* The generateNumber() method will not need any inputs. It will generate a random int between 1 and 100 inclusive and return that int. *******************************************************/ public static int generateNumber() { return (int)(Math.random() * 100) + 1; } /******************************************************* The playTurn() method receives a number that says which turn we are playing. We will need this method to return true or false telling the caller whether the player won the game. This method prompts the player for their guess. It reads the input and validates it. If the input is not valid a message is displayed and the method returns false. If the input is valid then this method determines if the player's guess is correct, too high, or too low. A message is displayed accordingly. If the guess was the correct number the method returns true, otherwise false. *******************************************************/ public static boolean playTurn(int turn) { // Prompt player for their guess and capture it. int guess = getGuess(turn); // validate the guess boolean isValid = validateInput(guess); // Handle the case where the input is invalid. if (!isValid) { System.out.println("Please guess a number between 1 and 100 inclusive"); return false; } // If we made it here then the input was valid so compare it to // the correct number if (guess == number) { System.out.println("Congratulations! You win!"); return true; } else { // Print proper message and return false if (number < guess) { System.out.println("The correct number is lower"); } else { System.out.println("The correct number is higher"); } return false; } } /******************************************************* The getGuess() method receives 1 parameter as input. That is the current turn number. It prompts the player for a number between 1 and 100 and returns the response from the user as an int. *******************************************************/ public static int getGuess(int turn) { // We will need a TextInput object to read in the number TextInput tin = new TextInput(); System.out.print("Turn " + turn + ": Enter an integer between 1 and 100 inclusive. "); return tin.readInt(); } /******************************************************* The validateInput method receives the guess that the player entered and returns true if the number lies between 1 and 100 inclusive, false otherwise. *******************************************************/ public static boolean validateInput(int myGuess) { if ((myGuess < 1) || (myGuess > 100)) { return false; } else { return true; } } }
When writing a check we need to express the number with English words.
Write a program that reads an integer between 0 and 999 and prints the corresponding English words.
Sample execution:
Enter an integer between 0 and 999: 567
five hundred sixty-seven
Analysis:
Digits in
567: 5 is hundred’s digit
6 is ten’s digit
7 is unit’s digit.
The
hundreds and most of the units are handled the same way, using the strings
"one", "two", …, "nine".
Most of
the tens digits are represented by the strings "twenty", "thirty", …, "ninety".
Note, however, that this ten word is followed by a hyphen only if the units
digit is nonzero.
Exception: Numbers from 10 to 19 have special words, "ten", "eleven", …, "nineteen".
We use methods to convert the digits to the appropriate words.
The main method:
public class Numbers { static String units(int m) { if (m == 0) return "zero"; if (m == 1) return "one"; if (m == 2) return "two"; if (m == 3) return "three"; if (m == 4) return "four"; if (m == 5) return "five"; if (m == 6) return "six"; if (m == 7) return "seven"; if (m == 8) return "eight"; if (m == 9) return "nine"; return "Invalid units"; } static String tens(int m) { if (m == 2) return "twenty"; if (m == 3) return "thirty"; if (m == 4) return "forty"; if (m == 5) return "fifty"; if (m == 6) return "sixty"; if (m == 7) return "seventy"; if (m == 8) return "eighty"; if (m == 9) return "ninety"; return "Invalid tens"; } static String teens(int m) { if (m == 0) return "ten"; if (m == 1) return "eleven"; if (m == 2) return "twelve"; if (m == 3) return "thirteen"; if (m == 4) return "fourteen"; if (m == 5) return "fifteen"; if (m == 6) return "sixteen"; if (m == 7) return "seventeen"; if (m == 8) return "eighteen"; if (m == 9) return "nineteen"; return "Invalid teens"; } public static void main(String[] args) { TextInput textIn = new TextInput(); System.out.print("Enter an integer between 0 and 999: "); int num = textIn.readInt(); if ((num < 0) || (num > 999)) { System.out.println("Number not between 0 and 999"); return; } int unitsDigit = num % 10; int q = num / 10; int tensDigit = q % 10; q = q / 10; int hundredsDigit = q % 10; String resultString = ""; if (hundredsDigit > 0) resultString = resultString + units(hundredsDigit) + " hundred "; if ((2 <= tensDigit) && (tensDigit <= 9)) { resultString = resultString + tens(tensDigit); if (unitsDigit > 0) resultString = resultString + "-" + units(unitsDigit); } else if (tensDigit == 1) { resultString = resultString + teens(unitsDigit); } else if ((tensDigit == 0) && ((unitsDigit > 0) || (hundredsDigit == 0))) { resultString = resultString + units(unitsDigit); } System.out.println(resultString); } }
Enter an integer between 0 and 999: 908
nine hundred eight
Enter an integer between 0 and 999: 1
one
Enter an integer between 0 and 999: 519
five hundred nineteen
Enter an integer between 0 and 999: 0
zero