Lesson 1
CSci A201/A597 Introduction to Programming I Independent Study Lesson #1: Simple Java
Before proceeding, follow the instructions on the home page for obtaining your network ID. Before you can submit your assignment or take the quiz, you must send your username to your instructor, so that you can be added to the appropriate rosters.
Reading Assignment Objectives Discussion
* Programming
* Debugging
* Communicating with Language
* Syntax = Grammar
* Semantics = Meaning
* A Simple Java Program
* Formatting Details
* Comments = Documentation
* The Compilation Process
* More Bugs
* Variables
* Variable Types
* Declaration Statement
* Primitive vs. Object Variables
* Assignment Statement
* More about Assignment
* Combining Declaration with Assignment
* Type Conversions
* Operators
* Mixed-Mode Arithmetic
* The Math Class
* Mutation
* String Concatenation
* Avoid Redundancy
* Constants
* User Input
* Summary of Conventions
Self-Study Assignment Submitting Your Assignment Grading Take the Quiz Solutions to Self-Study
Reading Assignment
This lesson covers material from Chapters 1 and 2 of the text Computing Concepts with Java 2 Essentials. Omit the following sections: 1.11, 2.6.2, 2.6.4. These sections will be covered in Lesson 2. Section 2.8 will not be covered at all in this course.
As you read the notes for these lessons, you may be referred to various points in the text's Appendix. In particular, after you've read through the notes, but before you start coding, you should read about "Lexical Issues" on pages 689 - 691 and the grading criteria section of these notes.
Prior to starting this lesson, you should have installed the Java software that you intend to use.
When a portion of the discussion below refers directly to a section from the text, it is so noted in the header. We will not review the material in the same order, necessarily, as presented in the text, and we will not always cover every topic. Nevertheless, you are expected to read all of the supporting material. It's probably a good idea to follow along with the text and the notes below in parallel, rather than doing all the reading from the text followed by the readings from this lesson.
You can begin by reading Sections 1.1 - 1.4 in the text.
Objectives
When you have successfully completed this lesson, you will be able to
* compile and run your first Java program
* explain the concepts of syntax and semantics
* work with primitive variables
* formulate arithmetic expressions and use simple Math functions
* convert between certain types
* change the values of variables through assignment
* read program input and display program output
* demonstrate a basic understanding of String objects
* appreciate the importance of programming style and conventions
* recognize and correct program errors
Programming (Section 1.2)
Java is a programming language which allows us to communicate a sequence of instructions, i.e., a program, to the computer. When the computer carries out our instructions, we say that the computer is executing or running the program. The author of the program is the programmer and the activity of writing programs is called programming.
Debugging
Unfortunately, programming is an error prone activity. Rarely does one write correct programs the first time.
Imagine that you've entered a baking contest where the object is to create a new chocolate cake recipe. You design a wonderful new recipe. This recipe, like all recipes, starts with a detailed list of ingredients, followed by an ordered list of instructions.
You can't stop there. You've actually got to bake the cake to see if the result is any good. Your recipe is like a program and the baking part is akin to executing the program.
You can't stop there. You've got to taste the cake to make sure that it's as delicious as you imagined.
What if it tastes awful? What if it's got a bug in it?! It's back to the drawing board. You've got to revise the recipe, bake another cake based on the new recipe, and taste test it once again.
This process of refining a program until it's correct is called debugging.
Rather than planning tasks for people to perform, in this course you will plan tasks for the computer to perform. Furthermore, whereas it's easy for us to make a mistake when following a recipe (inadvertently skipping a step, or substituting salt for sugar), we can safely assume that the computer will make no such errors. If the end product is not what we expect, then the mistake is with our program, not with the computer itself.
Finding errors in programs and correcting them is much of what programming is all about.
Communicating with Language (Section 1.5)
You write your chocolate cake recipe in English so that other English-speaking people can understand and follow your directions. If your recipe had been written in French, the contest judges would have a hard time understanding what to do.
To program a computer we must first agree on a language that both we, as programmers, and the computer understand. A computer is not sophisticated enough to understand a natural language like English or French, so we must settle on one of many possible computer languages.
A computer is also not intelligent enough to make inferences about what we mean if we don't use the proper grammar. A native English speaker can easily understand the meaning of the sentence "I ain't gonna go nowhere, nohow, not never." However, when we communicate with the computer in the computer's language, we must use the proper grammar at all times. If we speak improperly, the computer will simply inform us of our error and give up.
Syntax = Grammar
To learn any new language, one must not only learn the words and their meanings, but also the rules describing how words can be combined to form valid sentences. The syntax of a language is a set of rules governing the formation of grammatically correct sentences. In a natural language like German, one must understand the rules regarding adjective endings and verb placement. In a computer language, one must understand the structure of each instruction and the proper use of punctuation.
The sentences in a computer language are frequently called program statements, and errors in the formation of statements, i.e., grammatical errors, are called syntax errors. A program that contains one or more syntax errors will not execute.
For example, a simple declarative English sentence has the following form:
<article> <noun> <verb> <article> <noun>.
The angle brackets surrounding each word indicate that this is a placeholder for something of this form. That is, you need to replace each occurrence of <article> with something that is known to be an article.
If we agree that the word the is a particular instance of <article>, cat and milk are instances of <noun>, and drinks is an instance of <verb>, then the sentence
The cat drinks the milk.
is syntactically correct. So is
The milk drinks the cat.
It's certainly true that the computer which is our brain would be quite confused if we heard the above sentence. Our brain does not reject the sentence based on improper syntax but rather on what we know about the meanings of the individual words in the sentence.
Question: Which of the following sentences contain one or more syntax errors based on the grammatical rule above?
1. The cat drinks the milk
2. The drinks milk cat the.
3. The cat drinks milk.
Answer: They all contain syntax errors!
| sentence | first syntax error |
| The cat drinks the milk | Missing period. |
| The drinks milk cat the. | drinks is not a <noun>. |
| The cat drinks milk. | Milk is not an <article>. |
Punctuation is an important part of the syntax of a computer language, and it must be used properly. Common punctuation symbols are {, }, (, ), ", ;.
Semantics = Meaning
A statement can be properly formed yet produce an improper meaning, as with the sentence The milk drinks the cat. The meanings assigned to the words in a language comprise its semantics. Errors in the meaning of statements are called, not surprisingly, semantic errors. A program that contains one or more semantic errors will not produce the desired results. The program will execute, but it may stop unexpectedly at some point or it may run to completion but yield an incorrect result.
Going back to our chocolate cake example, if we accidently use salt instead of sugar, then we eventually get a cake at the end. It looks good, but when we taste it, we realize that something went wrong during the execution of the recipe program. On the other hand, if you neglected to mention that we needed cinnamon in the list of ingredients, then when we get to the step that tells us to add the cinnamon, we would have to stop immediately and proceed no further because we don't have any cinnamon in the house. In this case, we don't get even get a cake at the end.
Semantic errors are only detected during or after the program execution, and so are also called run-time errors.
A Simple Java Program (Section 1.8)
A program contains a sequence of commands or <statement>s. When a program is run, the computer performs each command, one after the other, in the order given.
There are many different types of statements in the language. The first one that we will consider is the <output statement>. When executed, this statement will print something to the screen.
Here is the syntax of the output statement:
System.out.println(<expression>);
The first part of the command, System.out, indicates that the command is being addressed to the object responsible for printing. The System.out object is something that is automatically provided to every program, and its job is to direct the value of the <expression> to the screen.
In general, we could have several output objects in use. One might send its output to a file on your hard disk; another might send its output to your modem. So, when we give a particular command, we must refer to the object of the command by name.
The actual command, or message, being sent to the output object is the println command. The dot is used to separate the object name from the command given to the object. The parentheses around <expression> and the trailing punctuation, i.e., the semi-colon, is required, just as the period must appear at the end of an English sentence.
What do we mean by <expression>? This is a complicated definition, so let it suffice for now to just say that a <string constant> is an example of an <expression>, and a <string constant> is any sequence of characters enclosed in double quotes. For example, all of the following are <string constants>.
"Hello, World!"
"1234"
"chocolate cake"
"4/26/88"
Read about Escape Sequences on page 26 to see how to include double quotes and special characters (like tabs, newlines, accented characters and other glyphs) inside a string.
So, now we can construct a sequence of instructions to insert into our program.
System.out.println("Hello, World!");
System.out.println("I love cake.");
System.out.println("If I eat too much cake, I'll soon weigh 300 pounds!");
OK, but what does it all mean? What are the semantics of these statements? Each println command will cause the string contents (minus the double quotes) to be displayed on the screen when the statement is executed. So, if the above three statements appear in a program, here's what you'd see appear on the screen after the statements were executed:
Hello, World!
I love cake.
If I eat too much cake, I'll soon weigh 300 pounds!
Each string appears on a separate line because the command is println, pronounced print line, which causes a newline character to be sent immediately after the string. There is another command, called print, which has the same syntax as println, but differs in semantics only in that the trailing newline is not sent.
All of the statements that comprise a program are surrounded by curly braces, { and }, and there is a header to the program of the form:
public static void main(String[] args)
Admittedly, this header looks rather strange. The important word is main, meaning that this is the main part of the program. The meaning of the other words in the header will be become clearer much later. For now, just accept them as part of a magic incantation that is necessary for the computer to understand the program. Here's what we've got so far.
public static void main(String[] args) {
System.out.print("Hello, World!");
System.out.println("I love cake.");
System.out.println("If I eat too much cake, I'll soon weigh 300 pounds!");
}
This is called the <main function definition>. In general, a program can contain the definitions of several functions (also called methods). We'll see this in a later lesson.
There's one more step you must do in order to turn this into a complete program. You've got to wrap your function definitions (in this case there's just one, main) in curlies and precede it with a class header. For now, you can just think of the word class as a synonym for program. (In reality, the concept of a program is more general than that of a class, but that is for a later day.) Here's the general syntax of a class:
public class <class name> {
public static void main(String[] args) {
<zero or more statements>
}
}
and here's our specific example:
public class Hello {
public static void main(String[] args) {
System.out.print("Hello, World!");
System.out.println("I love cake.");
System.out.print("If I eat too much cake, ");
System.out.println("I'll soon weigh 300 pounds!");
}
}
The <class name> is something that you make up. Be sure to choose a meaningful, but short, name that describes the program. This name must also be used in the filename containing the text, or source code, of the program. In this case, we used Hello as the <class name>, and so you would type this program into a file named Hello.java.
If you run this program, here's what you'll see:
Hello, World!I love cake.
If I eat too much cake, I'll soon weigh 300 pounds!
The first and second lines run together because the first statement in the program uses the print command, not the println command.
Formatting Details
Java is free-format. This means that it doesn't matter if you split statements among several lines or type them all on the same line. You are not allowed to separate "words" like println with blanks or newlines and you can't split a string constant across a line boundary but, other than that, Java enforces no formatting restrictions on the programmer. We, however, will care a great deal about the look of your program. You are responsible for formatting each program neatly and cleanly.
For readability, we will put only one program statement on a single line, and each command will be indented slightly. Lines can be left entirely blank, and we will do so frequently in our examples to show which parts of the program hang together logically.
Case is significant in this language. The printing object is System.out, not system.out or SYSTEM.OUT.
Comments = Documentation
Although the computer will be carrying out the instructions in your program, humans may also read the code you write. Naturally, this includes your instructor, but it also includes you. Consequently, the language allows us to insert annotations within the code. These annotations are called comments, and they are completely ignored by the computer. Comments serve to explain the intended logic of the program to the human audience.
There are two ways of designating comments in Java. First, any text following the symbols // on a line designates a comment. For example:
// Print welcome message
System.out.print("Hello, World!"); // note: no newline!
Second, any text between /* and */ is considered a comment.
/*
This is my very first Java program and I can't
wait to run it to make sure that it works properly!
*/
The use of indentation, blank lines, and comments will make your program easier to develop and will also please your instructor.
The Compilation Process (Section 1.10)
Before the computer can execute your program and produce the output that you expect, you must first compile, i.e., translate, the Java source code into bytecode, i.e., lower-level instructions. This translation process is called compilation, and it is performed by a compiler.
When a program in a file named Hello.java is compiled, the compiler produces another file named Hello.class, which contains a bytecode version of the program. It is this version of the program that the Java Virtual Machine, or VM for short, is able to execute.
More Bugs (Section 1.9)
There are two type of errors, or bugs, that can creep into your program. A syntactic error occurs when the compiler sees a word in the source code that is not part of the language's vocabulary. If you inadvertently enter pront instead of print, then the computer will not even attempt to execute your program. Instead you are presented with an error message giving the nature and location of the bug. Most times these error messages will be rather cryptic, but we'll supply you with detailed descriptions of the most common errors and hints for how to fix the underlying problem.
Assuming your program does not contain any syntactic errors, then the computer will execute the program. Run-time errors are mistakes in the logic of the program and emerge when the program is run. For example, it is a semantic error if you attempt to divide a number by zero. In this case, the computer would abort the execution prematurely and produce an error message.
Just because the computer completes the program without any error messages does not mean that the program is error free. Perhaps the output is present but incorrect. Only you can judge whether or not the result of running the program is correct. If not, you must go back and re-examine your logic, make corrections, and run the program again. This is analogous to tasting your chocolate cake to see if it turned out well. If it didn't, you must analyze your recipe to determine what caused the failure. Errors in the design of your program are called logic or semantic errors.
Rarely is a program bug free on the first draft. Even expert programmers spend a good deal of their time debugging their programs.
Stop Reading and Do
Before you proceed any futher, you should type in the Hello program, compile it, and run it to make sure that you understand the procedure and what we've done up to this point. Do not attempt to cut and paste the text of this program into your editor. Type it directly. That will help you to absorb and remember the syntax.
You may also want to do the first two exercises from the assignment below.
When you come back, we'll move on to some material from Chapter 2. We're going to skip the material in Section 1.11 for now.
Variables
Your mind is quite extraordinary and can remember many things, like people's names, good books, and telephone numbers. Variables are the means the computer uses to remember things that can change over time.
The mailbox outside your home may be labeled with your name or street address. This label never changes. However, the contents of the mailbox changes from day to day, depending on what your postman places in it. One day you may receive a magazine, the next day a bill, and the next day a letter.
A variable is like a mailbox. It has a label, which is always the same, but you may store different things inside it. Unlike a mailbox, only one item or value may be in a variable at one time.
A variable name should describe the purpose of the variable. Names may start with a letter, an underscore (_), or a dollar sign ($). They may not start with a digit. Variable names are often made up of several words combined. The first word is always all lowercase, but all following words have an initial uppercase letter.
Here are some examples of typical variable names: currentTemperature, firstName, reallyBigNumber, score4.
It is good programming practice to use meaningful names that reflect the usage of the variable, and you are expected to do so in all programs that you write for this course.
In general, you should avoid single letter names like a and b. In certain circumstances, however, single letter names are appropriate. For example, if you need to refer to an (x, y) coordinate in the plane, then it is perfectly legitimate to use a variable named x to hold the x value and a variable named y to hold the y value.
It's also a good idea to avoid abbreviations. Use basketballCoach rather than bbC. The seconds you save typing a shorter name are not worth what you sacrifice in readability.
(In these lessons we will frequently violate this rule about using descriptive names in our examples whenever we need a generic variable.)
Variable Types (Section 2.1)
When a variable is created by the computer, a block of memory is allocated to store the value of the variable. We will usually draw such memory locations as a box, labeled by the name of the variable. Here's a picture of a variable named currentTemperature that has the value 75.
In addition to a name and a value, a variable also has an associated type. The type specifies the sorts of values that the variable may hold. For example, the value in the variable currentTemperature is a number. More specifically, it is a whole number without a fractional part. Java calls such numbers ints.
Declaration Statement
Earlier we described the syntax and semantics of the output statement. Now it's time to learn the syntax of another statement, the declaration statement.
<type> <one or more variable names separated by commas>;
To declare the variable currentTemperature pictured above, you would use the following statement in your program.
int currentTemperature;
This does not, however, put the value 75 into the variable. Right now currentTemperature is uninitialized.
To place a value in a variable, you must use an <assignment statement>, which we'll get to shortly. But, before we leave this topic, there are two other <type>s to mention.
As you saw previously, constants for the type String are characters enclosed in double quotes. Numbers that have decimal points are of type double. The following table lists some examples of constants for these three basic types.
Type Example Constants for the Type int 0, -42, 64000 double 3.1417, 98.6, 0.0, -42.2222 String "", " ", "String", "-42"
Notice that numbers never contain commas. The int constant is 64000, not 64,000.
Notice that "" is different from " ". "" is called the empty string and it is of length 0. " " consists of a single character, a blank, so it is a string of length 1. Also note that "-42" is completely different from -42. The first, "-42", is a string of length 3, whereas the second, -42, is an integer.
An analogy with a refrigerator is helpful in understanding how variables and memory work in the computer. Imagine that your refrigerator is the computer and inside it you have many containers, all properly labeled. Each container represents a variable that has been created. Some of the containers are pitchers and you use them to store liquids like milk, lemonade, and orange juice. You'd never store green beans in a pitcher, just liquids. Furthermore, you have both large and small pitchers. You certainly can't put large amounts of liquid in the small pitchers, and it would be a waste of space in your refrigerator (where space is limited) to store a small amount of liquid in a large pitcher. In the same way as you optimize the use of space in the refrigerator, we want to optimize the use of memory in the computer. As it turns out, the size of an int variable is less than the size of a double variable, so we'll only use double variables when we know for sure that we need the extra precision.
In your refrigerator, you also have containers that hold solid food. Some are really large (like the one for the leftover Thanksgiving turkey) and some are small, but all such containers are used exclusively for solid food, not liquids. Also, like the pitchers, you can't stuff the Thanksgiving turkey in a sandwich container, and it would be a waste of space to keep a sandwich in the turkey container. So, you keep liquids in the pitchers and solids in the solid food containers. In the same way, string constants are stored in String variables, real values are stored in double variables, and integer values are stored in int variables.
Question: Can we store different values in the same variable?
Answer: Yes, but not at the same time. Every time a new value is assigned to a variable, it replaces the old value. Using our refrigerator example, that would be like taking a pitcher of lemonade, pouring out the lemonade and filling the pitcher with orange juice. The lemonade is the old value and orange juice is the new value.
From a hardware perspective, variables are physical segments of memory built out of electronic parts. Variables store information similarly to a cassette tape. You can play a song from a cassette, or you can record a new song on it (in which case, the old song is gone forever). It's the same with variables. When you assign a new value to a variable, the old value is destroyed.
Primitive vs. Object Variables
The types int and double are called primitive types, and variables of these two types are called primitive variables. There are six other primitive types in Java. Of these, we will study three of them in future lessons: long, boolean and char.
The type String is an example of an object type and variables of type String are called object variables, or simply objects. Java provides a huge assortment of object types.
The fully quantified name for the type String is java.lang.String. This means that the definition of the String class can be found in the java.lang package. In our programs, we can use the "nickname" String rather than the full name java.lang.String, since all Java programs automatically import, i.e., know about, the java.lang package. We'll come back to this point later when we start dealing with some of the other Java packages that aren't automatically imported.
The differences between a primitive variable and an object variable is one of the crucial things that you must learn in order to become a good programmer. We will spend a lot of time on it in these lessons.
Assignment Statement (Section 2.2)
To put a particular value into a variable, you use an <assignment statement>, whose syntax is:
<variable name> = <expression>;
We'd better be more specific about what we mean by <expression>. All of the constants for the various types are also examples of <expression>s. Furthermore, an <expression> has a value and this value has a type, which is inherited by the <expression>. For example, -42 is a constant of type int, but it is also an <expression> of type <int>.
For an <assignment statement> to be properly formed, the type of the <variable name> and the type of the <expression> must agree. For example, given the following declaration:
int currentTemperature;
this is a perfectly legal <assignment statement>:
currentTemperature = 75;
but these are not:
currentTemperature = "75"; // cannot assign a String to an int
currentTemperature = 75.6; // cannot assign a double to an int
It's like trying to put a turkey into a sandwich container. The turkey simply doesn't fit.
Here are some other (correct) examples using the String and double types.
String eggs;
double turkey;
eggs = "0000000000000"; // a baker's dozen
turkey = 14.5;
More about Assignment
Assignment is a way to give a value to a variable. The variable name appears on the left hand side and the expression whose value will be assigned to the variable appears on the right hand side.
There is an equal sign between the variable and the expression, but the equal sign does not indicate equality. What we say is that the variable gets the value. In our refrigerator example, if we pour lemonade into a pitcher, we might write the statements:
String pitcher, glass; // declares two variables both of type String
pitcher = "lemonade";
The above assignment statement is read as "The pitcher gets lemonade", not "The pitcher equals lemonade".
The pitcher is the variable and "lemonade" is the value the pitcher gets. Obviously they are not equal. If, later in our program, we write the assignment statement:
pitcher = "milk";
then the "lemonade" value in the pitcher variable is replaced by the "milk" value. That is, the old value, the "lemonade" is discarded and the new value, the "milk", is poured into the pitcher container.
As indicated, <expression>s (i.e., those things that can appear on the right-hand side of an assignment statement) are more complicated than just simple constants. Variables are also <expression>s. For example,
glass = pitcher;
We do not attempt to shove the pitcher itself into the glass. The value of the pitcher, i.e., its contents, is copied into the glass. As before, the previous contents of the glass, whatever they may be, are discarded first.
The important thing to note is that the contents of pitcher are duplicated and transferred into glass. The pitcher is not empty now. It still has the same contents it had originally. The original contents of glass, however, are gone forever. The variables glass and pitcher are still two different variables, but the value that each variable contains is the same. The expression still does not mean equality.
Question: How would you interpret the following code fragment?
String bottleOfMilk, juicePack, pitcher;
bottleOfMilk = "milk";
juicePack = "juice";
pitcher = bottleOfMilk;
bottleOfMilk = juicePack;
Answer: First, the two variables, bottleOfMilk and juicePack, are initialized to specific values.
Then, the contents of bottleOfMilk are copied into pitcher, replacing whatever was in pitcher originally. Thus, pitcher now contains "milk".
At this point, bottleOfMilk is not empty! It's contents are copied, not poured. The bottleOfMilk still contains "milk".
When the last statement is executed, the contents of the variable juicePack are copied into bottleOfMilk. Now, bottleOfMilk contains "juice". Remember, juice and milk don't mix! The "milk" is replaced by the "juice".
Question: What does pitcher contain at the end?
Answer: "milk", but why?
Combining Declaration with Assignment
The variable declaration and subsequent assignment statement, which gives the variable an initial value, frequently come in pairs. To save typing time and shorten the program, these two statements can be combined as follows:
int dollars = 5, cents = 36;
This creates the following two variables:
The initial value only applies to one variable. In the following,
int corn, cob = 3;
the variable corn is uninitialized and the variable cob contains the value 3.
Type Conversions (Section 2.3)
As it turns out, you can always assign an int value to a double variable. The computer will silently append a fractional value of .0 to the integer.
int i = 3; // i contains the value 3
double d = i; // d contains the value 3.0
On the other hand, the compiler will disallow any attempt to store a double value in an int variable. This code fragment
double d = 3.0; // d contains the value 3.0
int i = d; // no can do
will produce a syntax error.
Sometimes, however, it is necessary to convert a quantity of one type into another type. If the two types are both primitive types (like int and double), then you can force the compiler to accept a conversion with something called a cast. (See page 60 of the text.)
double d = 3.0; // d contains the value 3.0
int i = (int) d; // no problem; i contains the value 3
d = 4.7; // now d contains the value 4.7
i = (int) d; // now i contains the value 4
Note that when a double is cast to an int, the fractional part is simply chopped off. No rounding occurs.
It is not possible to convert a String of digits into its numerical equivalent by using a cast. The reason is because Strings are objects, not primitives, and casting cannot be used to convert from a primitive type into an object type, or vice versa.
String s = "123";
int i = (int) s; // Syntax Error: Invalid cast from java.lang.String to int.
Notice that the error message reported by the compiler refers to the fully quantified name java.lang.String. This will be the case for all error messages involving objects.
Operators (Section 2.5)
There are several different operators available in Java. An operator is a symbol, like +, that is used in <expression>s. An operator is applied on its operands to produce a result.
Java provides the usual arithmetic operators, and one which you are probably not familiar with: the remainder operator, denoted as %. You can read about the remainder operator (sometimes called the mod operator) on page 70 of the text.
Here are some examples.
Operator Semantics Example Expression Value of Expression Type of Expression + addition 4 + 5 9 int
1 + 2 + 3 6 int 5.2 + 4.2 9.4 double
- subtraction 4 - 5 -1 int
5.2 - 4.2 1.0 double
- multiplication 4 * 5 20 int
5.2 * 4.2 21.84 double
/ division 4 / 5 0 int
5.0 / 4.0 1.25 double 5 / 4 1 int 14 / 4 3 int
% remainder 4 % 5 4 int
5 % 4 1 int 14 % 4 2 int
Important: It is essential that you commit to memory the exact names of the various Java types. On exams, you may be asked to specify the type of some expression, say 1 + 2. If you write integer or Integer or Int, then your answer will be considered incorrect. The correct type is int, and that is the only acceptable answer.
Note that when both operands are integers, the result of the division operator is an integer. That is, any fractional part in the result is dropped. (See pages 72 - 73 in the text.)
Actually, the results of double arithmetic may not be exact. Some minor round-off error could be present. (See page 62 of the text.)
Note that both operands of the remainder operator, %, must be integers.
The order of evaluation of operators can be specified with parentheses. For example, (2 + (7 / 2)) * (5 - 1) evaluates to 20.
In the absence of parentheses, the following precedence rules and rules of associativity apply.
Operators Associativity
- , /, % left to right
+, - left to right
There are just two levels, for now, in this operator heirarchy. You should understand the above table to mean that multiplication, for example, will be performed before addition.
Expression Fully Parenthesized Expression Value Type 2 * 3 + 4 (2 * 3) + 4 10 int 2 - 3 / 4 2 - (3 / 4) 2 int
The associativity rules kick in when there is a series of operators, all of which are at the same level, chained together. All the operators in our table associate left to right. (There are some operators in Java that associate right to left.) The associativity rule dictates the order in which groupings are made as the expression is evaluated.
Expression Fully Parenthesized Expression Value Type 1 - 2 - 3 - 4 ((1 - 2) - 3) - 4 -8 int 11 % 4 % 2 (11 % 4) % 2 1 int 2 * 3 / 2 (2 * 3) / 2 3 int 3 / 2 * 2 (3 / 2) * 2 2 int
Mixed-Mode Arithmetic
If one or more of the operands to an arithmetic operator is of type double, then the result is always of type double.
Expression Value Type 1.0 + 2 3.0 double 1.3 - 2 -0.7 double 2 * 1.0 2.0 double 5.0 / 4.0 1.25 double
The >>pre<<math>><< Class (Section 2.3)
Java provides a rich collection of mathematical functions, such as square root, and trigonometric functions, like sine and cosine, similar to the sort of functions you would find on any decent calculator. All these functions are accessed through the java.lang.Math class, or simply Math for short. For example, to find the square root of the number 9, you would use the following expression:
Math.sqrt(9)
This expression evaluates to the integer 3. At this point, let's introduce some notation to help with the exposition. When we write this:
Math.sqrt(9) ==> 3
it is a shorthand for saying "the expression Math.sqrt(9) evaluates to 3". The symbol ==> is not Java syntax and you won't find this notation in your textbook. It's used in these notes and also on your exams, as a succinct way of showing you the expected result of evaluating an expression.
Math.sqrt(9) is an example of a function call. We say that we are calling the function Math.sqrt with the value 9.
These function calls can be used as operands in larger expressions, like this:
Math.sqrt(9) + Math.sqrt(16) ==> 3 + 4 ==> 7
2 * Math.sqrt(25) + 3 ==> 2 * 5 + 3 ==> 13
The input to the sqrt function, i.e., the number 9, is placed inside the parentheses. In general, this input can be any expression. Such expressions are typically called arguments. The output from the function is also called its return value.
Math.sqrt(Math.sqrt(64) + 1) ==> 3
If we wanted to write a complete program to print out the square root of 9, then we could do it like this:
public class SquareRoot {
public static void main(String[] args) {
int number = 9;
System.out.print("The square root of ");
System.out.print(number);
System.out.print(" is ");
System.out.print(Math.sqrt(number));
System.out.println(".");
}
}
When this program is run, the output produced is:
The square root of 9 is 3.
To print the square root of another number, say 16, all you need to do is change the initial value of number to 16, recompile and run again. Later on you'll see how to get the user of the program to provide the number as input to the program as it is running.
Appendix A2 in the text provides detailed documentation about the most common Java packages. Although it'll probably look very foreign to you right now, you should take a quick look at the description of the java.lang.Math class beginning on page 713. It will at least give you an idea of the sorts of functions available in the class.
One very handy function is Math.round, which rounds a double value to the nearest whole number.
Math.round(2.99) ==> 3
Math.round(4.5) ==> 5
Math.round(-4.2) ==> -4
Math.round(-4.5) ==> -4
Math.round(-4.6) ==> -5
Notice that halves are always rounded up. The return value from Math.round is an integer, but it is of type long, not int. The long type is another primitive, and it is just like int except that the size of the variable is twice as big, and thus it can hold a larger range of values. We won't really be interested in the type long in this course, except in this context. If you want to place the result of Math.round in a variable, you must either use a long type variable:
long result = Math.round(2.99);
or you can use an int variable, but then you must cast the result.
int result = (int) Math.round(2.99);
Two other convenient functions in the Math class are ceil and floor. Each takes a double value and returns a double value. Here are some examples of how they work on positive numbers:
Math.ceil(2.99) ==> 3.0
Math.ceil(4.5) ==> 5.0
Math.ceil(0.1) ==> 1.0
Math.floor(2.99) ==> 2.0
Math.floor(4.5) ==> 4.0
Math.floor(0.1) ==> 0.0
Mutation
The value stored in a variable may change over time as the program executes. These changes or mutations can be done via assignment. Consider the following program fragment:
int x = 5; // line 1
System.out.println(x); // line 2
x = x + 1; // line 3
System.out.println(x); // line 4
x = x * 2; // line 5
System.out.println(x); // line 6
What is printed? There are three println statements (lines 2, 4, and 6), so we expect to see three lines of output.
Let's execute the statements one at a time. Here's the situation after line one is executed:
Line 2 just produces some output:
Line 3 performs an assignment. This is a two-step process. The expression on the right-hand side must first be evaluated: x + 1 ==> 5 + 1 ==> 6. Once the value of 6 is obtained, it is placed in the variable x, thereby obliterating the previous value.
Line 4 produces some output:
Line 5 is another assignment. This time the expression on the right side is evaluated as x * 2 ==> 6 * 2 ==> 12.
Finally, line 6 produces the last line of output:
String Concatenation (Section 2.6.3)
Concatenation is just a fancy way of saying connect items together. In Java, the + operator is used to join string values together.
For example,
"pig" + "tail" ==> "pigtail"
"pig" + "tail" + "s" ==> "pigtails"
The fact that Java attaches two different meanings to the same symbol (+) is an example of a more general concept called polymorphism. According to Webster, polymorphism means the quality or state of being able to assume different forms. Java is able to decide the interpretation to assign to the + operator based on the context in which it is used. The + operator has the same precedence, i.e., the same position in the hierarchy, whether it is interpreted as addition or concatenation.
If both operands to the + operator are numeric (i.e., ints and/or doubles), then + means "arithmetic addition".
If one of the operands to the + operator is of type String and the other is of type int, for example, then the integer is automatically converted into the corresponding string of digits and the operation performed is string concatenation, not arithmetic addition.
3 + "pigs" ==> "3pigs"
3 + "4" ==> "34"
1 + 2 + "3" ==> "33" // since (1 + 2) + "3" ==> 3 + "3" ==> "33"
"1" + 2 + 3 ==> "123" // since ("1" + 2) + 3 ==> "12" + 3 ==> "123"
String concatenation is frequently used in output statements.
String firstName = "Bill";
int prize = 100;
String welcome = "Hi there " + firstName,
result = "You just won " + prize + " dollars," + firstName + "!!!";
System.out.println(welcome + "\n" + result); // \n means newline
Avoid Redundancy
One reason for using variables is to avoid duplication of any sort. We'd like our programs to be as easy to modify as possible. As a very simple example, consider the Hello program.
public class Hello {
public static void main(String[] args) {
System.out.print("Hello, World!");
System.out.println("I love cake.");
System.out.print("If I eat too much cake, ");
System.out.println("I'll soon weigh 300 pounds!");
}
}
Right now the object of our affections, i.e., cake, is repeated in two places. We could refine this program as follows.
public class Hello {
public static void main(String[] args) {
String favorite = "cake";
int maxWeight = 300;
System.out.print("Hello, World!");
System.out.println("I love " + favorite + ".");
System.out.println("If I eat too much " + favorite +
", I'll soon weigh " + maxWeight +
" pounds!");
}
}
Constants (Section 2.4)
A constant (also called symbolic constant), is like a variable, except that it must be initialized at declaration time and its value can never change thereafter. In Java, constants are enforced by attaching the final attribute to the declaration. This means that its initial value is its final value, and the compiler will reject any attempts to mutate the variable.
See the note on the middle of page 67 about the naming convention for final variables. You must follow this convention in all programs that you write for this course. Here's how we'd rewrite the previous program using symbolic constants:
public class Hello {
public static void main(String[] args) {
final String FAVORITE = "cake";
final int MAX_WEIGHT = 300;
System.out.print("Hello, World!");
System.out.println("I love " + FAVORITE + ".");
System.out.println("If I eat too much " + FAVORITE +
", I'll soon weigh " + MAX_WEIGHT +
" pounds!");
}
}
Many Java classes contain some predefined constants. For example,
Math.PI ==> 3.141592653589793
Integer.MAX_VALUE ==> 2147483647
Integer.MIN_VALUE ==> -2147483648
Math.PI evaluates to the most accurate double representation of the number pi.
Integer is another Java class, similar to Math in that it contains some useful functions. (See Appendix A2, page 712.) Despite the name similarity, the class Integer is completely different from the primitive type int. One function, which we'll see shortly, is called parseInt and it will allow us to convert a string of digits into its numerical equivalent.
Every int variable is 32 bits in length. The range of possible integers that can be stored in an int variable is large but limited. As the numbers get bigger (or smaller) the variable will overflow (or underflow) at some point. The values of the constants Integer.MAX_VALUE and Integer.MIN_VALUE allow us to determine exactly where the overflow/underflow cutpoints are.
What do you think happens when the following statements are executed? Try it and find out.
int x = Integer.MAX_VALUE;
x = x + 1;
System.out.println(x);
Analogous constants exist in the Double class (Double.MAX_VALUE and Double.MIN_VALUE) and in the Long class (Long.MAX_VALUE and Long.MIN_VALUE)
User Input (Section 2.7)
Our programs would be much more useful if they could query the user for data as the program is running. Then the program could produce results specific to the input given by the user.
Java automatically provides to your program an object of type InputStream, named System.in, for capturing user input from the keyboard. Unfortunately, grabbing the user's keystrokes and interpreting them properly is an awkward and cumbersome process. In order to streamline the procedure and hide the gory details, the author of our text has provided us with a pre-defined class called ConsoleReader that will do the technical work for us.
Be warned that the ConsoleReader class is not part of standard Java. In order to use it in your program, you'll have to copy the ConsoleReader.java file to the same directory that contains your program's .java file.
In any program that reads data from the user, include the following statement inside your main function:
ConsoleReader keyboard = new ConsoleReader(System.in);
This turns the standard System.in object into a new object, named keyboard, which is friendlier and easier to use. You'll apply one of three different methods to the keyboard object, depending on what type of data you expect the user to provide. In all cases, the input typed by the user is read until the user presses the enter key. If the user enters inappropriate characters, then a run-time error is produced. This is not terribly nice, but it will do for now.
1. keyboard.readLine() returns, as a String, the entire line of text typed by the user. The trailing newline is not included as part of the String itself. 2. keyboard.readInt() returns the int typed by the user. 3. keyboard.readDouble() returns the double typed by the user.
Normally your program will precede each read with an output statement that prompts the user for the expected input. For example, here's a program fragment that acquires some personal information about the user and then echoes it back.
System.out.print("Enter your name: ");
String name = keyboard.readLine();
System.out.print("Enter your age (in years): ");
int age = keyboard.readInt();
System.out.println("Hello " + name + ", you are " + age + " years old.");
It would be a good idea to copy the above code into the main routine of your Hello program. What happens if you type some leading or tailing blanks when you are prompted for your age? The blank characters are considered part of the input and the keyboard object produces an error because you entered some non-digit characters.
Summary of Conventions
Please adhere to the following conventions in all programs that you write for this course. Remember that your work will be graded on both correctness and style.
1. The name of a class must begin with a capital letter. For example, Hello.
2. When more than one word is desired as part of a class name, capitalize each word. For example, HelloWorld. Java requires that the class name must not contain blanks; i.e., it must be a single contiguous unit.
3. Always indent the main function header inside the class wrapper.
4. Always indent the statements comprising the body of the main function inside its wrapper.
5. At the top of each file that you submit, include the following information in program comments:
/*
Your Name
Your Student ID Number
Your e-mail address
Lesson Number
*/
6. Thoroughly document your code with meaningful comments. Avoid decorative comments, e.g.,
int x; // declare an integer named x
x = 5; // set x to 5
Self-Study
1. Type the Hello program into your editor. (Do not just cut and paste the code. Typing the program will help you absorb the Java syntax.)
Compile and run the program. Now, change the value of the FAVORITE constant to a string representing your favorite dessert and change the MAX_WEIGHT constant to some other number. Compile and run the program again.
2. There are numerous opportunities for errors to creep into your program. Cut and paste the following program directly into your editor, and then save it in a file called Cube.java.
public class Cube {
public static void main() {
double height = 3.0; /* in inches *
double cubeVolume = height * height * height;
double surfaceArea = 8 * height;
/* Produce some output: */
System.out.println("Volume = " cubeVolume);
System.out.println("Surface area = " + surfaceArea;
}
}
1. What error messages are produced when you first compile this program?
2. Correct all syntax errors.
3. Correct all logical errors, i.e., semantic errors.
3. For each expression in the following table, indicate its value and the type of the value.
Expression Value Type
3 + 2 / 5
5 - 0.0
"age = " + 20
25 % 10
2 + 3 * 4 - 5
"cat" + 2 + 3
2 + 3 + "cat"
4. Consider the following program fragment:
ConsoleReader keyboard = new ConsoleReader(System.in);
int num;
num = 5;
Which of the following, if any, are valid statements that could possibly appear next.
1. 9 = num;
2. num = num + 2;
3. num = keyboard.readLine();
4. System.out.println("num = " + num);
5. The user runs a program containing the following fragment and then types 37 at the prompt. Exactly what is printed by the last output statement?
ConsoleReader keyboard = new ConsoleReader(System.in);
int weight;
System.out.print("Enter the weight in ounces: ");
weight = keyboard.readInt();
int pounds, ounces;
pounds = weight / 16;
ounces = weight % 16;
System.out.println(pounds + " pounds, " + ounces + " ounces.");
6. The price of some item is stored in a double variable named cost. The sales tax on this item is 5 percent. Write a statement that will increase the value in cost by the sales tax.
7. What is printed when the following program is run?
public class Mystery {
public static void main(String[] args) {
int a;
a = 2; a = 3; a = 4;
System.out.println(a + a + a);
}
}
8. Write a program named Square that displays the squares and cubes of the numbers 2 through 10 in a tabular format. Here are the first few lines of output:
Num Square Cube
--- ------ ----
2 4 8
3 9 27
4 16 64
5 25 125
: : :
As you can see, the output is arranged in a table. Use the tab character \t to separate the items on a line. For example, the following statement will print the column headers.
System.out.println("Num\tSquare\tCube");
Do not print the square and cube values as constants. For each number, compute its square and cube by using the * operator.
9. Write a program named Compute that prompts the user for two integers and then prints:
1. the sum,
2. the difference,
3. and the product.
Here is a sample run. The user input is given in green italics. Note that your program must work for any integers provided by the user, not just 5 and 9.
Enter an integer: 5
Enter an integer: 9
The sum of 5 and 9 is 14.
The difference of 5 and 9 is -4.
The product of 5 and 9 is 45.
Assignment
This is your actual assignment for this lesson. You will write and debug several programs. Each program will be stored in a separate file with a .java extension.
Please take care to use the exact program names specified in the problems below.
Before you get started, you should spend a few minutes creating directories (i.e., folders) on your computer where you intend to do your work. Create a separate folder for each lesson, named Lesson1, Lesson2, etc. Keep all your programs for a single lesson in a separate directory. As the course moves along, we will refer back to work done in previous lessons, and you'll be able to locate your work more easily if it is well organized.
Download the following file to your working directory:
ConsoleReader.java
1. (Exercise P1.1 on page 45.) Write a program named Name that displays your name inside a box on the screen, like this:
+---------+
| Suzanne |
+---------+
2. (Exercise P1.2 on page 45.) Write a program named Tree that prints a Christmas tree, like this:
/ / / / --------
" "
" "
" "
Remember to use escape sequences to print the \ and " characters.
3. Write a program named Range that prints out the range of possible values for an int and also for a double. Your output should be properly labeled. (Make use of the constants in the Integer and Double classes.)
4. Write a program named Reckon that prompts the user for two integers and then prints:
1. the average,
2. the distance (i.e., the absolute value of the difference),
3. the maximum (i.e., the larger of the two numbers),
4. and the minimum (i.e., the smaller of the two numbers).
Make use of the following Math functions: Math.abs, Math.max, Math.min. Here are some examples of how they work:
Math.abs(3) ==> 3
Math.abs(-3) ==> 3
Math.abs(5 - 2 * 6) ==> 7
Math.max(7, 3) ==> 7
Math.max(3, 7) ==> 7
Math.max(-3, -7) ==> -3
Math.min(7, 3) ==> 3
Math.min(3, 7) ==> 3
Math.max(Math.abs(-10), Math.min(5, 12)) ==> 10
Here is a sample run. The user input is given in green italics. Note that your program must work for any integers provided by the user, not just 5 and 9.
Enter an integer: 5
Enter an integer: 9
The average of 5 and 9 is 7.
The distance of 5 and 9 is 4.
The maximum of 5 and 9 is 9.
The minimum of 5 and 9 is 5.
5. Write a program named Hal that prints the message, "Hello, my name is Hal.". Then, on a new line, the program prints "What is your name?". Next, the program should read the user's name and print "Hello, <user's name>. I am glad to meet you.". Then, on a new line, the program should print the message "What would you like me to do?". Then it is the user's turn to type in an input. Finally, the program should ignore the user input and print the message, "I am sorry <user's name>. I cannot do that.".
Here is a sample run. The user input is given in green italics.
Hello, my name is Hal.
What is your name? Dave
Hello, Dave. I am glad to meet you.
What would you like me to do? Open the pod bay door!
I am sorry, Dave. I cannot do that.
6. The government computes income tax as 17% of a taxpayer's income after deducting $6000. Write a program named Tax that prompts the user for the amount of money earned during a particular tax year (as a double value) and then calculates the amount of tax owed. Assume that everybody makes at least $6000 per year.
Here is a sample run. The user input is given in green italics.
Enter the amount of money earned: 27368.63
Your tax bill is 3632.6671000000006
7. Assume that a can of paint costs ten dollars and covers fifteen square meters. Write a program named Paint that prompts the user for the dimensions (length, width and height, in meters, all integers) of a room. Calculate the cost of painting the room, i.e., all four walls and the ceiling. (Assume that there are no doors or windows.) Note that you cannot purchase a fraction of a can of paint, so your result should be an integer. Hint: Use the Math.ceil function.
Submitting Your Assignment
If you have not yet e-mailed your IU Network ID (just your username, not you password) to your instructor, then do so now! You will not be able to submit your work until your instructor has added you to the class roster.
For this lesson, you should submit seven files:
* Name.java
* Tree.java
* Range.java
* Reckon.java
* Hal.java
* Tax.java
* Paint.java
Do not submit .class files. Only the files named above should be submitted. You do not have to submit all the files at the same time or on the same day. Furthermore, you may resubmit a file as often as you like up to the point when you indicate that you are done with the lesson and it's ready to be graded. Only your most recent submissions of each file will be graded.
To submit a lesson, there are three things that you must do:
1. Submit all program files to the submission system. 2. Tell the submission system that you are DONE with the lesson. 3. Send e-mail to istudy@indiana.edu, cc'ed to your instructor, indicating that you have submitted the lesson. The subject line of your e-mail must contain CSCI A201 and the lesson number (e.g., CSCI A201 Lesson 1). The body of the e-mail must contain your full name, your student identification number and the date you submitted your lesson. NOTE: this information must be e-mailed for you to receive credit for the lesson.
We'll step you through the process this time.
To submit lesson 1, point your browser to the following address:
Lesson Submission Page
You'll see two boxes. In the first box, the "Submit an Assignment" option should be selected. Click on the "Submit" button in this box. Select "Lesson 1" and click "Submit". You'll see a screen with seven text fields, each followed by a "Browse" button. Click on "Browse" for one of the text fields and navigate through your file system to one of the .java files for this lesson. Once you've selected a file, press "Submit".
If you chose to submit Name.java, for example, then you'll see a screen like this:
-----------------------------
Name.java has been uploaded.
Compiling Name.java
-----------------------------
Congratulations! All files compiled successfully.
If your program(s) had had any compilation errors, then they would have been reported to you above. (This is just a precaution to make sure that you've submitted a synactically correct program.) You should correct any errors and resubmit.
After you have submitted all of the files for the lesson, you should select "Acknowledge you are DONE with an assignment" from the submission page.
At any time, you can view your complete submission history, and download any files that you've previously submitted, by selecting "View files submitted to date" from the submission page.
Now, there's one final thing to do. Send e-mail to istudy@indiana.edu, cc'ed to your instructor, indicating that you have submitted the lesson.
Your e-mail to istudy@indiana.edu should look something like this:
To: istudy@indiana.edu
From: janedoe@indiana.edu
cc: menzel@indiana.edu
Subj: CSCI A201 Lesson 1
Jane Marie Doe
Student ID # 999-99-9999
I submitted lesson 1 on 10/10/01.
How Will These Assignments Be Graded?
For each lesson, you will receive a single letter grade. Correctly fulfilling the basic requirements of the assignment earns you a grade of B. That is, you must complete and submit all programs and they must all work as intended.
To receive a grade of A, your programs must also be well documented (contain insightful comments), have a consistent and readable layout (e.g., indentation, blank lines), and use variables with meaningful names. They must also incorporate a solution that is straightfoward and efficient.
In general, avoid single letter variable names like x and y. Names like grossIncome and paintCost are far better. Stick with our naming conventions, e.g., all variable names should begin with a lowercase letter.
Make use of blank lines to separate logically equivalent blocks of code. But do not put a blank line between every single statement! That just makes the whole program harder to read.
Appendix A1 in the text contains a detailed style guide. Please read about "Lexical Issues" on pages 689 - 691. The author specifically advises against the style of braces that I prefer (see end of A1.7.3.) and that is used in all examples in these notes. You may use whatever style of braces you find most readable, but be consistent and adhere to your chosen style. Under no circumstances should you ever put more than one closing curly brace on a single line.
}}}}} // Never, ever, ever do this!
The author also advises that you use tab stops of length 3 to indent levels in your program. I prefer an indentation level of 4, so that's what you'll see in these notes. Again, you should use whatever you find pleasing, just as long as you do so consistently.
Take the Quiz
You can test how well you have understood this lesson by taking Quiz 1 at QuizSite. To use this system, you will need to enter your Indiana University Network Username and Password.
Solutions to Self-Study
1.
public class Hello {
public static void main(String[] args) {
final String FAVORITE = "pudding";
final int MAX_WEIGHT = 200;
System.out.print("Hello, World!");
System.out.println("I love " + FAVORITE + ".");
System.out.println("If I eat too much " + FAVORITE +
", I'll soon weigh " + MAX_WEIGHT +
" pounds!");
}
}
2.
1. Here are the error messages that my compiler produced:
Cube.java:8: ')' expected.
System.out.println("Volume = " cubeVolume);
^
Cube.java:12: Unbalanced parentheses.
^
Cube.java:12: '}' expected.
^
3 errors
2. Here's how I corrected these three errors. The line numbers are not part of the source code. They are included to assist you in matching up each error message with the line in the program that generated the message. Notice that even though the compiler complained about problems on line 12, the errors were actually generated by a missing right parentheses on line 9.
1 public class Cube {
2 public static void main() {
3 double height = 3.0; /* in inches *
4 double cubeVolume = height * height * height;
5 double surfaceArea = 8 * height;
6
7 /* Produce some output: */
8 System.out.println("Volume = " + cubeVolume);
9 System.out.println("Surface area = " + surfaceArea);
10 }
11 }
12
However, fixing these three errors did not correct all the syntax errors in the code. Here are the new messages:
Cube.java:8: Undefined variable: cubeVolume
System.out.println("Volume = " + cubeVolume);
^
Cube.java:9: Undefined variable: surfaceArea
System.out.println("Surface area = " + surfaceArea);
^
2 errors
The error is subtle. It has to do with the fact that the comment on line 3 was not closed properly. The compiler interpreted everything beginning with the /* on line 3 up until the */ at the end of line 7 as a comment. This included our variable declarations. Adding the slash on line 3 fixes both errors.
1 public class Cube {
2 public static void main() {
3 double height = 3.0; /* in inches */
4 double cubeVolume = height * height * height;
5 double surfaceArea = 8 * height;
6
7 /* Produce some output: */
8 System.out.println("Volume = " + cubeVolume);
9 System.out.println("Surface area = " + surfaceArea);
10 }
11 }
12
Now, the program compiles, but when you attempt to run the program, you get the following run-time error.
Exception in thread "main" java.lang.NoSuchMethodError: main
The reason is because the signature of the main function (line 2) is incorrect. It must appear exactly as given in the Hello program.
1 public class Cube {
2 public static void main(String[] args) {
3 double height = 3.0; /* in inches */
4 double cubeVolume = height * height * height;
5 double surfaceArea = 8 * height;
6
7 /* Produce some output: */
8 System.out.println("Volume = " + cubeVolume);
9 System.out.println("Surface area = " + surfaceArea);
10 }
11 }
12
3. There are two semantic errors in the computation of surfaceArea. First, a cube has 6 sides, not 8. Second, the area of each side is height * height, not just height. Here's the completely corrected program.
public class Cube {
public static void main(String[] args) {
double height = 3.0; /* in inches */
double cubeVolume = height * height * height;
double surfaceArea = 6 * height * height;
/* Produce some output: */
System.out.println("Volume = " + cubeVolume);
System.out.println("Surface area = " + surfaceArea);
}
}
Here's the output produced by this program:
Volume = 27.0
Surface area = 54.0
3.
Expression Value Type
3 + 2 / 5 3 int
5 - 0.0 5.0 double
"age = " + 20 "age = 20" String
25 % 10 5 int
2 + 3 * 4 - 5 9 int
"cat" + 2 + 3 "cat23" String
2 + 3 + "cat" "5cat" String
4. Statements b and d are valid. Statement a is invalid because the left hand side of the assignment is not a variable. Statement c is invalid because the result of the readLine method is a String and you cannot assign a String object to an int variable.
5. 2 pounds, 5 ounces.
6. cost = cost + cost * 0.05;
or
cost = cost * 1.05;
7. 12
8. This program makes use of variables and assignment to generalize the computation. Notice that the four statements in each block offset by blank lines are the same. Once the basic form was established, all that needed to be done was to copy and paste these four statements the correct number of times. If the problem statement was changed so that the table should include a row for all numbers up to 100, then this program could be easily extended. Can yours?
public class Square {
public static void main(String[] args) {
int num = 2, square, cube;
System.out.println("Num\tSquare\tCube\n" +
"---\t------\t----");
square = num * num;
cube = num * square;
System.out.println(num + "\t" + square + "\t" + cube);
num = num + 1;
square = num * num;
cube = num * square;
System.out.println(num + "\t" + square + "\t" + cube);
num = num + 1;
square = num * num;
cube = num * square;
System.out.println(num + "\t" + square + "\t" + cube);
num = num + 1;
square = num * num;
cube = num * square;
System.out.println(num + "\t" + square + "\t" + cube);
num = num + 1;
square = num * num;
cube = num * square;
System.out.println(num + "\t" + square + "\t" + cube);
num = num + 1;
square = num * num;
cube = num * square;
System.out.println(num + "\t" + square + "\t" + cube);
num = num + 1;
square = num * num;
cube = num * square;
System.out.println(num + "\t" + square + "\t" + cube);
num = num + 1;
square = num * num;
cube = num * square;
System.out.println(num + "\t" + square + "\t" + cube);
num = num + 1;
square = num * num;
cube = num * square;
System.out.println(num + "\t" + square + "\t" + cube);
}
}
9. Notice that the parentheses are required when printing out the sum of x and y. This is to ensure that the arithmetic addition operator will be performed on the two ints, rather than the String concatenation version of +.
"2 + 3 = " + 2 + 3 ==> "2 + 3 = 23"
"2 + 3 = " + (2 + 3) ==> "2 + 3 = 5"
Also note that we again make use of a variable to generalize the code. This time the variable is a String which holds the name of the operation being performed.
public class Compute {
public static void main(String[] args) {
// create console reader
ConsoleReader keyboard = new ConsoleReader(System.in);
// get user input
int x, y;
System.out.print("Enter an integer: ");
x = keyboard.readInt();
System.out.print("Enter an integer: ");
y = keyboard.readInt();
System.out.println(); // prints a blank line
// produce output
String operation = "sum";
System.out.println("The " + operation + " of " + x + " and " + y +
" is " + (x + y));
operation = "difference";
System.out.println("The " + operation + " of " + x + " and " + y +
" is " + (x - y));
operation = "product";
System.out.println("The " + operation + " of " + x + " and " + y +
" is " + (x * y));
}
}
last modified June 18, 2001 by Suzanne Menzel; menzel@cs.indiana.edu