You are on page 1of 54

Introduction to Programming in Java

Table of Contents

Table of Contents
Preface Chapter 1 Basic Computer Science Concepts & Java Computer ----------------------------------------------------------------------------Software -----------------------------------------------------------------------------Types of Programs ------------------------------------------------------------------Executable program or Machine Language program ---------------------------Programming Languages ----------------------------------------------------------Compiler ------------------------------------------------------------------------------Java Virtual Machine ---------------------------------------------------------------Review Questions -------------------------------------------------------------------Chapter 2 Introduction to Java Programming Class Definition ----------------------------------------------------------------------Method Definition -------------------------------------------------------------------Head and Body -----------------------------------------------------------------------Statements ----------------------------------------------------------------------------Comments ----------------------------------------------------------------------------Language Elements -----------------------------------------------------------------Program Execution ------------------------------------------------------------------Review Questions -------------------------------------------------------------------Chapter 3 Variables, Data Types and the Declaration Statement Variable -------------------------------------------------------------------------------Data Type -----------------------------------------------------------------------------Declaration Statement ---------------------------------------------------------------Declaration and Memory -----------------------------------------------------------Non Primitive Data Type or Objects ----------------------------------------------Example Program --------------------------------------------------------------------Review Questions --------------------------------------------------------------------Lab 3 -----------------------------------------------------------------------------------Chapter 4 Expressions and Arithmetic Operators Expression ----------------------------------------------------------------------------Arithmetic Operators ----------------------------------------------------------------Subexpressions -----------------------------------------------------------------------Constants ------------------------------------------------------------------------------Review Questions --------------------------------------------------------------------Lab 4 ----------------------------------------------------------------------------------19 19 21 23 24 25 11 11 11 13 14 15 16 17 6 6 6 6 7 7 9 10 1 1 1 1 2 3 4 5

Introduction to Programming in Java Chapter 5 - Classes and Methods

Table of Contents

Primitive Data & Objects -----------------------------------------------------------Java Class -----------------------------------------------------------------------------Class Libraries and Java API ------------------------------------------------------Anatomy of a Class -----------------------------------------------------------------Main Method ------------------------------------------------------------------------Creating an Object of Fraction Class --------------------------------------------Static Variables and Static Methods ---------------------------------------------Review Questions -------------------------------------------------------------------Lab 5 ----------------------------------------------------------------------------------Chapter 6 Use of Java API and Console Input Java API ------------------------------------------------------------------------------Java API in HTML Format --------------------------------------------------------Input and Output of the Program --------------------------------------------------Example I/O Program ---------------------------------------------------------------Review Questions -------------------------------------------------------------------Lab 6 ----------------------------------------------------------------------------------Chapter 7 Making Decisions and Repetitions Two-way Decisions -----------------------------------------------------------------One-way Decisions -----------------------------------------------------------------Example Program -------------------------------------------------------------------Repetitions ---------------------------------------------------------------------------Review Questions -------------------------------------------------------------------Lab 7 ----------------------------------------------------------------------------------Appendix Sample Exam ---------- -------------------------------------------------------------

27 27 27 28 31 32 32 34 35

37 38 39 40 41 42

44 45 45 46 49 50

51

Preface This tutorial is intended to introduce the features of the basic programming concept of computer science using Java. This tutorial also provides an overview of the Java language and the facilities that are provided by the standard Java class libraries, including the Java Application Programmer Interface (API) class libraries. The tutorial is not intended to completely cover the Java language and facilities, but rather to provide enough understanding of the basic concepts to allow a student to more easily look up additional and more specific information as needed. Computer science is not just about programming techniques. It rests on deep ideas and the nature of computation. I want students to understand these deep ideas, as well as grasp the practicality of computation and experience the pleasure of computing. The tutorial is divided into seven chapters. Each chapter contains three parts of the lesson. 1. Lesson 1. Review questions 2. Programming exercises (Labs) The tutorial is also an excellent supplement for the ICS students. A 75 mints log sample test which covers all the materials from chapter 1 to chapter 7 is included at the end of the tutorial. You are welcome to e-mail me at ihsan1@gmail.com with your thoughts and comments while you are reading this tutorial or afterwards. I promise to get back to you speedily.

Ihsan Rehman London, Ontario Canada

Chapter 1

Basic Computer Science Concept & Java

Chapter 1 Basic Computer Science Concepts & Java


Computer: A computer is a complex machine that executes software (programs, data). It consists of many different components. But at the heart -- or the brain, if you want -- of the computer is a single component that does the actual computing. This is the Central Processing Unit, or CPU. In a modern desktop computer, the CPU is a single "chip" on the order of one square inch in size. The job of the CPU is to execute programs. Programs: Programs are lists of instructions for the CPU or Processor to perform a task. Software: Software consists of both programs and data. Data can be any information that a program needs: character data, numerical data, image data, or many other types. Types of Programs: There are two categories of programs. Application programs (usually called just "applications") are programs that people use to get their work done. Computers exist because people want to run these programs. Systems programs keep all the hardware and software running together smoothly.
Application Programs: Word processors Game programs Spreadsheets Graphics programs Web browsers Systems Programs

Operating system. Networking system. Web site server. Database system. Programming language software. JAVA

The most important systems program is the operating system. The operating system is always present when the computer is running. It coordinates the operation of all the hardware and software components of the computer system. The operating system is responsible for starting application programs running and finding the resources that they need. Executable program or Machine Language program: Each different type of CPU has its own unique language that it understands, called machine language. Every program must be converted into a machine language before it executes. A program in the form of machine language is also called executable program.

-1-

Chapter 1

Basic Computer Science Concept & Java

Example of machine language program and its execution: Let us say that an electric toothbrush has a CPU (Processor). The processor can rotate the bristles left and right, and can check the on/off switch. Here is imaginary table for machine instructions (Machine Language) and machine operation.
Machine Instruction Machine Operation

0000 0000 0000 0001 0000 0010 0000 0100 0000 1000

Stop Rotate bristles left Rotate bristles right Go back to start of program Skip next instruction if switch is off

Programming Languages: Programmers write programs using some languages that called programming languages. There are two types of programming languages. 1. Low Level Languages 2. High Level Languages Low Level Languages: A low-level programming language is a language that provides little or no abstraction from low-level CPU operations. High Level Languages: A high-level programming language is a programming language that is easier to program in, to some extent platform-independent like Java, and abstract from low-level CPU operations.

-2-

Chapter 1 Compiler:

Basic Computer Science Concept & Java

As we read in previous pages, a computer perhaps CPU or processor can understand only machine language. And programmers prefer to write their programs in high level languages because it is easy to write and human readable. A compiler is a program that translates a high level language to a low-level machine

language. Java (A Programming Language): Java is a high-level, object-oriented programming language developed by Sun Microsystems. It is similar to C++, but has been simplified to eliminate language features that cause common programming errors. Java is a general purpose programming language with a number of features that make the language well suited for use on the Web and it has a very rich library, called Java API. We will explore these features in later lessons. Of course to write and run a Java program you need Java Development Kit (JDK). The Java Development Kit (JDK) is a collection of software for developing Java programs available at no charge from Sun Microsystems. Installing JDK: JDK download is available at java.sun.com. Detailed instructions on how to download it and install it are available at that site. If you have not yet installed Java, get the most recent version. The JDK for Windows comes in a file named jdk1.5.0_01-win.exe (or a similar name.) Edit Compile Run, Java Programs: Here is an example Java program. Some of its details will be explained later. This program will be created as a text file using any editor such as the "NotePad" editor. The

-3-

Chapter 1

Basic Computer Science Concept & Java

file that contains this program should be named Hello.java. This file is called a source program. class Hello { public static void main ( String[] args ) { System.out.println("Hello World!"); } }

Java compiler converts this source program (Hello.java) into Java bytecodes (Hello.class). Then an other program called Java Virtual Machine JVM converts these bytecodes into machine language. Java Virtual Machine: You might be thinking why we use JVM. Why we do not convert source code like Hello.java directly into machine language. There are many reasons for that.
1. Platform Independent:

Java bytecodes file can be run on any platform. The only we need JVM and java bytecodes.

2. Security:

Many Java programs are to be downloaded over a network. This leads to obvious security concerns: you don't want to download and run a program that will damage your computer or your files. The JVM acts as a buffer between you and the program you download. You are really running the JVM, which runs the downloaded program indirectly. The JVM can protect you from potentially dangerous actions on the part of that program.
3. Java Applets:

An applet is a Java bytecode program that runs on a Web browser. Often applets are used for complicated user interaction, or for graphics and animation that can't otherwise be done in a Web page. Applets will be discussed in later in these notes.

-4-

Chapter 1 Review Questions:

Basic Computer Science Concept & Java

1. Lets a computer has just added 13 to 27. Where did this activity take place?

2.

Imagine that you are using a word processor program to write a letter. a. Where (in the computer system) is the program you are running? b. Where are the characters you have typed?

3. Imagine that you have just turned on your computer and have not yet started any application. Are any programs running?

4. Do all processor chips (CPU) have the same architecture?

5. What is the difference between bit and byte.

6. Define the functionality of these hardware components of a computer. Processor Main memory Secondary memory devices Input/output devices

Lab: Copy the source program Hello.java in your favorite editor. I recommend Jcreator. This editor available free at jcreater.com. Save this program some where in your hard derive. a. Produce a Hello.class file in the same directory using Java compiler. b. Run the program and see what is the output. c. See the source code and observe where this output comes from the source code.

-5-

Chapter 2

Introduction to Java Programming

Chapter 2 Introduction to Java Programming


Here is the source program (source file) similar from the previous day but little advance. The purpose of this program is to do some calculation and putting the result on the monitor. Example 2.1: 1 2 3 4 5 6 7 8 9 10 11 Public class Area { public static void main(String[] args) { int width; width = 8; int height = 3; int area = width * height; System.out.println(area); } }

We start our exploration by looking at the program. This program exposes features common to all Java programs.
Class Definition:

The statement on line 1 indicates the beginning of a class named Area. This statement is called the class header and is followed by two braces (an opening brace on line 2 and closing brace on line 11) that enclose the class body. Method Definition: The statement on line 3 indicates the beginning of the main method. This statement is a method header and followed by two braces that encloses the body of the method. Statements: The body of the main method contains five statements. A variable name width is declared as an integer (int) on line 5 and is assigned the value 8 on line 6. Similarly on line a variable hight is declared and assigned the value 3. We can aslo write this line as int height; height = 3; However, it is convenient and commonly used shortcut to combine declaration with assignment. The statement on line 8 uses same shortcut to declare a third integer variable,

-6-

Chapter 2

Introduction to Java Programming

area and assign it the product of the previous two variables. The last statement on line 9 put the area on the screen. Comments: Comments are non-executable notes that we add in program to remember what this program or statement do. A comment starts with the two characters "//" (slash). The Java compiler ignores those characters and everything that follows them on that one line. If we need comments more than two lines then we use /* and */. The Java compiler ignores every thing in between these two characters. Here is Example 2.1 with comments. Example 2.2: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 /* This class calculate the area of a rectangle. Author: Ihsan Rehman Version: 2.01 */ Public class Area { // main method public static void main(String[] args) { int width; // width of rectangle width = 8; int height = 3; // height of rectangle int area = width * height; System.out.println(area); } } // end of class

Language Elements: Correctness of a sentence written in human language like English is a multistage process. In the first stage, we examine each word in the sentence and attempt to classify it according to the rules of the language, for example, as a verb, noun, proper name, preposition and so on. Similarly, the first stage in determining the correctness of a Java program is to break each of its statements into tokens and to classify each token as one of the lexical element of Java. In this section, we will look at lexical elements of Java: keywords, identifiers, operators, and separators.

-7-

Chapter 2
1. Keywords:

Introduction to Java Programming

Keywords are words that have predefined meaning in Java. Some commonly used keywords are public, class, boolean, return, if, break etc.
2. Identifiers:

Identifiers are names that programmers choose to use in their programs; they have no predefined meanings in Java. For example, Area (a class name), main (a method), and width ( a variable name ) are identifiers.
3. Literals:

Literals are constant values. For example, the number 3 that appears on line in Example 2.1 is an integer literals. Also true, false, null are literals.
4. Operators:

An operator is like a mathematical function because it takes one or more arguments and produce a result. The multiplication asterisk (*) on line 8 in Example 2.1 is an operator that takes two arguments, width and height, and produce a result. Some example of Java operators are = , !, &, % etc
5. Separators:

Separators are characters that separate various part of the Java code. They are similar to punctuation symbols in human language, Java separators are , ; ( ) [] { }

Note: The reserved words are the key words plus the literals: true, false, null

-8-

Chapter 2

Introduction to Java Programming

Program Execution: Three steps are needed to execute (run) a program: Edit We use an editor to write the program and save it in a file. Previous program example 2.2 must be saved in a file name Area.java We call this file as a source file. We use a compiler to translate our program form Java, a high-level language, to bytecode. The compiler reads the source file, translate it, and stores the translation in a file called the class file. The file is so named because it has the same name as the source but with the class extension; for example the source Area.java complies into Area.class. If there is any syntax error in the source file, compiler will issue a list of compile-time errors. In that case, we must go back to the editor, correct the reported errors, save the file and compile again. This process is called editcompile cycle. Run We use a virtual machine JVM to execute the bytecode in the class file.

Compile

-9-

Chapter 2 Review Questions: 1. Here is the first line of a Java program: class AddUpNumbers

Introduction to Java Programming

a. What should the source file be named? b. What will the compiler automatically name the bytecode file? 2. a. What is the command that runs the Java compiler? b. What is the command that runs the Java interpreter? 3. If a source program compiles correctly in step 3, does that mean that it will run correctly? 4. Are comments included in the bytecode translation of a Java program? 5. Is it possible to write an entire paragraph of comments? 6. Why would you ever want to use comments to help a person understand your program? 7. How do you know whether a word is a Java reserve word? 8. Is there a semicolon at the end of a class header? 9. Following has exactly 3 syntax errors. Can you identify them? /* This class calculate the area of a circle. Author: Ihsan Rehman Version: 2.01 */ Public class Area // main method public static void main(String[] args) { int Area; int radius = 6 cm; // radius of a circle Area = (22/7) radius * radius; System.out.println(area), } } // end of class 10. a. What is run-time error? b. Is the above program has a run time error? Lab 2:

- 10 -

Chapter 2 1.

Introduction to Java Programming

Write a program, which take the following data

int hoursWorked = 40; double payRate = 10.0 taxRate = 0.20; and produce exactly the following output. Hours Worked: 40 Pay Amount : 400 Tax Amount: 80

2. Consider the fragment int x = 3; int y = 14; double pi = x + y / 100.0; int z = (5 % 4) + 6 / 8; System.out.println(pie); System.out.println(z); a. Is there a compile-time error in it?. If not, predict its output. b. Validate your answers by creating a program and running it.
3.

The following program computes and writes out the value of exp( 32 ). This is the base of natural logarithms "e" raised to the power 32

class DoubleCrash { public static void main ( String[] args ) { double value = 32; System.out.print("e to the power value: "); System.out.print(Math.exp( value ) ); } } Compile and run the program. Does it compile and run correctly? Now change the 32 to larger and larger numbers until something goes wrong.

- 11 -

Chapter 3

Variables, Data Types and the Declarations Statements

Chapter 3 Variables, Data Types and the Declaration Statement


Variable: A variable is just a memory location (or several locations treated as a unit) that has been given a name so that it can be easily referred to and used in a program. The programmer only has to worry about the name; it is the compiler's responsibility to keep track of the memory location. The programmer does need to keep in mind that the name refers to a kind of "box" in memory that can hold data, even if the programmer doesn't have to know where in memory that box is located. Data Type: Every variable in the program has a type that indicates what sort of data it can hold. One type of variable might hold integers -- whole numbers such as 3, -7, and 0 -- while another holds floating point numbers -- numbers with decimal points such as 3.14, -2.7, or 17.0. (Yes, the computer does make a distinction between the integer 17 and the floating-point number 17.0; they actually look quite different inside the computer.) There could also be types for individual characters ('A', ';', etc.), strings ("Hello", "A string can include many characters", etc.), and less common types such as dates, colors, sounds, or any other type of data that a program might need to store. Declaration Statement: The declaration statement has the following form: type variableName; In this statement programmer is indicating that a variable with the specified name will be used later in the program and that its future value will be of the specified type. The statement does not assign a value to the variable; it merely prepares it to hold a value of a particular type. For example, the following statement declares that the programmer intends to use a variable named width and store integer in it. int width; A declaration must appear before the variable is used in the program; otherwise, the compiler will report an error. We can also initialize a variable by assigning a value to it. This value must be of the correct data type. int width = 8;
- 12 -

Chapter 3

Variables, Data Types and the Declarations Statements

Declaration and Memory: When we declare variable, we are asking the compiler to set aside an area of memory to hold its future values. Memory can be viewed as a one-dimensional arrangement of cells, each of which is called a memory byte. Data type integer takes 4 bytes of the memory. So when the compiler encounters a declaration such that int width; it realize that 4 bytes of memory are needed.

Identifier

Type

Block Address

width

int

Many Data Types: Java has very many data types built into it, and you (as a programmer) can create as many more as you want. However, all data in Java falls into one of two categories: primitive data type and non primitive data type (objects). Primitive Data Types: Primitive data types are types of data that are fundamental and built into Java. Programmers use these data types to produces other types of data (non-primitive data type). The names of the eight primitive data types are:
byte short int long float double char boolean

Upper and lower case characters are important. So "byte" is the name of a primitive data type, but "BYTE" is not. Computer languages where case is important are called case sensitive. Java is case sensitive language. Some languages are not case sensitive, especially old languages that were designed when data entry equipment did not have lower case characters.

- 13 -

Chapter 3

Variables, Data Types and the Declarations Statements

Non Primitive Data Type or Objects: There are only the eight primitive data types. Any data type you invent will be a type of non-primitive data type or objects. Much more will be said about objects in the future (since Java is a object oriented programming language.) The following will be all you need to know, for now: A primitive data value uses a small, fixed number of bytes. There are only eight primitive data types. A programmer can not create new primitive data types. An object is a big block of data. An object may use many bytes of memory. An object usually consists of many internal pieces. The data type of an object is called its class. Many classes are already defined in the Java Development Kit. A programmer can create new classes to meet the particular needs of a program.

Example Program 3.1: public class Example { public static void main(String[] args) { String name = "Ali"; double payRate = 10.0; double taxRate = 0.10; int hoursWorked = 40; System.out.println("Total earning for "+name+": "+payRate*taxRate*hoursWorked); } } This example program containing several variable declarations. Variable name is of data type String. String is a class coming from Java built in library. Variable payRate is of type double. The character * means multiply. In the program, (hoursWorked * payRate) means to multiply the number stored in hoursWorked by the number stored in payRate. The character + is used for concatenation (connecting two strings). Output of This Program:

Total earning for Ali: 40

- 14 -

Chapter 3 Example Program 3.2: /*

Variables, Data Types and the Declarations Statements

class Example shows the total earning for Ali. Author: Ihsan Rehman Copy rights @ 2006 Version 1.01

*/ public class Example { // main method, holding all data. public static void main(String[] args) { String name = "Ali"; // name double payRate , taxRate, totalEarning; int hourWorked; // initialize the variables. payRate = 10.0; taxRate = 0.10; hoursWorked = 40; totalEarning = payRate*taxRate*hoursWorked; // calculating total System.out.println("Total earning for "+name+": "+totalEarning); } } // end of class

Logically the example program 3.2 is same as Example program 3.1. Only difference is in style. Good programming style is very important, particularly when your program is hundreds lines long. In the above program, programmer declares the variables and then initializes the variables by assigning them some values. Remember variables can be initialize only with compatible values. It means integer variable can hold only integer values, not characters or any other data type. Java program tells the computer to take these values stored in these variables, do calculation as program says and then store the result in the variable named "totalEarning" and print the result on the monitor.

- 15 -

Chapter 3 Review Questions

Variables, Data Types and the Declarations Statements

1. Is Int a primitive data type?

2. Is 197.0 an integer literal?

3. Do you think that using float instead of double saves a significant amount of computer memory?

4. Do you suspect that characters are important enough to be one of the eight primitive data types?

5. What is wrong with the following char literal? char = w;

6. Is the following variable name legal: Grandtotal ? Suggest a better name for it.

7. What does the following assignment statement statement do: sum = 42 - 12 ;

8. What is a memory block?

9. What is syntactical rules for naming identifiers?

10. Can a boolean value be converted to any other type?

- 16 -

Chapter 3 Lab 3

Variables, Data Types and the Declarations Statements

1. The following program uses primitive data type short: class ShortEg { public static void main ( String[] args ) { short value = 32; System.out.println("A short: " + value); } }

The word "value" in this program is a variable---a name for a section of memory that holds data using a particular data type. In this case "value" will be the name for 16 bits of main memory that uses short to represent an integer. This program puts the value 32 into "value." Then it writes out: A short: 32 In other words, the next line of the program examines the variable and writes out what it finds. Your Job: Create a file called ShortEg.java. Compile and run it. Check what it writes onto the screen. Now edit the program so that the 32 is changed to some other small number, say 356. Compile and run the program. Everything should be fine. Next change the number to 35000 and try to compile and run the program. This number is too large to work with the data scheme short (in other words, it cannot be represented in 16 bits using data type short.) What happens? Now edit the program (don't change the 35000) so that the data type is int. Compile and run the program. Is there a difference? 2. The consider the following program uses primitive data type double: class DoubleCrash { public static void main ( String[] args ) { double value = 32; System.out.println("e to the power value: " + Math.exp( value ) ); } }

- 17 -

Chapter 3

Variables, Data Types and the Declarations Statements

Compile and run the program. Does its output differ from the output of the first program in the previous exercise? Now change the 32 to larger and larger numbers until something goes wrong.

3. The following program uses primitive data type char: class CharEg { public static void main ( String[] args ) { char ch = 'A' ; System.out.println("A char: " + ch ); } }

The variable "ch" is 16 bits of main memory that uses a scheme for representing characters. The character 'A' has be placed in it. The program will write: A char: A Do the following: a) Change the 'A' into 'Z' and compile and run. b) Change the 'A' into 'AA' and try to compile the program. c) Change the 'A' into ' ' and compile and run the program. Notice carefully: there is a single space between the two ' marks. d) Change the 'A' into '' and try to compile. Notice carefully: there is no character between the two ' marks. e) Change the 'A' into "A" and try to compile the program. (The double quotes " signify a String, which is something different from a char).

- 18 -

Chapter 4

Expressions and Arithmetic Operators

Chapter 4 Expressions and Arithmetic Operators


Expression: An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value. The parts of an expression must be arranged correctly. The syntax of Java describes the correct arrangements. The rules for correct Java expressions are about the same as for algebra. We need to talk about operators and operands. You already know what an operator is (a symbol + - * / that calls for an arithmetic operation.) An operand is a value that is acted upon by an operator. For example, in 13 - 5 the 13 and the 5 are the operands and the - is the operator. Arithmetic Operators: Arithmetic expressions are especially important in programming. Java has many operators for arithmetic: An integer operation is always done with 32 bits or more. If one or both operand is 64 bits (data type long) then the operation is done with 64 bits. Otherwise the operation is done with 32 bits, even if both operands are smaller.
Operator

+ * / % + -

Meaning unary minus unary plus multiplication division remainder addition subtraction

For example, with 16 bit short variables, the arithmetic is done using 32 bits: short x = 12; // 16 bit short int result; // 32 bit int result = x / 3; // arithmetic will be done using 32 bits The expression x / 3 divides a 32 bit 12 by a 32 bit 3 and put the 32 bit answer in result. The literal 3 automatically represents a 32 bit value. Another example: short x = 12; short y = 3; short result; result = x / y; The expression x / y divides a 32 bit 12 by a 32 bit 3, even though the variables x and y are only 16 bit wide. The answer then will be shortened to 16 bits and placed in result.

- 19 -

Chapter 4

Expressions and Arithmetic Operators

At the professional programming level, details like these are sometimes important. But mostly for general purpose programs use int or long for integers and double for floating point. This will keep you out of trouble. Division Operator: The division operator "/" means integer division if there is an integer on both sides of it. The result of integer division is always an integer; if the exact result calls for a decimal fraction, that part of the result is dropped (not rounded.) If one or two sides has a floating point number, then it means floating point division. There is a difference between what Java will do and what a calculator will do. A calculator will do floating point arithmetic for the expression: 7/2 Java will regard this as integer arithmetic and give you: 7/2 = 3 This is easy enough to see when it is by itself, but here is a more confusing case of the same thing: 1.5 + 7/2 The division will be done first, because "/" has higher precedence than "+". The result, 3, is an integer. Now floating point 1.5 is added to integer 3 to get floating point 4.5. Integer arithmetic may be used in parts of an expression and not in others, even though the final value of the expression is floating point. Most programming languages do this. Believe it or not, it is fortunate that Java works this way. It would be awful if what was done in the middle of a calculation depended on the final result. Practice: The normal rules of arithmetic are used to determine the sign of the result of integer division: +num/+div = = +result -num/+div = = -result +num/-div = = -result -num/-div = = +result It is easiest to first calculate the result as if num and div were positive, then apply the above rules. For example: 17/5 = = 3 -17/5 = = -3 17/-5 = = -3 -17/ -5 = = 3

- 20 -

Chapter 4 Subexpressions:

Expressions and Arithmetic Operators

The expression 3/4 calls for integer division because both the operands are integers. The expression 3.0/4.0 calls for floating point division because both the operands are floating point. Most of the operators we are interested in take two operands. In each of the following examples the operator has two operands: 34 + 12 19/3 90 - sum val * x

However, unary operators take just one operand: +93 -72 +sum -Math.PI

A binary operator will always have exactly two operands. However, sometimes one or both operands of a binary operator is a subexpression. A subexpression is a part of an expression that is by itself a correct expression. Sometimes a subexpression is a constant, like "8". Any expression can be a subexpression of a larger expression. In the following, both operands of the red operator are subexpressions. 2*3 + 8 (x - y) / 2.3 (sum - 2) * (sum + 3)

Mixed Floating Point and Integer Expressions: If both operands are integer, then the operation is an integer operation. If one or two operands is floating point, then the operation is floating point. For example, the following are integer operations (assume that a and b are int variables): 12 * b a-2 56%a

Each operation in the following expressions is a floating point operation (assume that a and b are int variables, and that x and y are floating point variables): x*b (a - 2.0) 56*y

In more complicated expressions, an operand of a particular operator might be a subexpression. But the rule still applies: if one or both operand is a floating point type then the operation is floating point. In the following, each / operation is floating point: (12.0 * 31) / 12 (a - 2.0) / b 56*x/3

In that last example, the 56*x is a floating point subexpression that is one of the operands for the division operator. (Because * and / have equal precedence, so evaluation is done from left to right.)

- 21 -

Chapter 4 Remainder Operator:

Expressions and Arithmetic Operators

You may recall in fourth grade doing division like this:

13 / 5 = = 2 with a remainder of 3. This is because 13 = = 2*5 + 3. The symbol for finding the remainder is % (percent sign.) Copy the following program to a file and play with it. Change the 17 and 3 to other numbers and observe the result.

class RemainderExample { public static void main ( String[] args ) { int quotient, remainder; quotient = 17 / 3; remainder = 17 % 3; System.out.println("The quotient : " + quotient ); System.out.println("The remainder: " + remainder ); System.out.println("The original : " + (quotient*3 + remainder) ); } }

Taking an Integer Apart: The integer division operator / and the remainder operator % take an integer apart. theInteger / divisor > quotient theInteger % divisor > remainder The original integer can be put back together again: quotient * divisor + remainder > theInteger In many calculations, it is convenient to do everything with integers, so both / and % are needed.

- 22 -

Chapter 4 Constants:

Expressions and Arithmetic Operators

Often in a program you want to give a name to a constant value. For example you might have a tax rate of 0.045 for durable goods and a tax rate of 0.038 for non-durable goods. These are constants, because their value is not going to change when the program is executed. It is convenient to give these constants a name. Consider the following program:

class CalculateTax { public static void main ( String[] arg ) { final double DURABLE = 0.045; final double NONDURABLE = 0.038; . . . . . . } }

The reserved word final tells the compiler that the value will not change. The names of constants follow the same rules as the names for variables. (Programmers sometimes use all capital letters for constants; but that is a matter of personal style, not part of the language.). The constants can be used in expressions like: taxamount = gross * DURABLE ; But the following is a syntax error: DURABLE = 0.441; // try (and fail) to change the tax rate.

In your programs, use a named constant like DURABLE rather than using a literal like 0.441. There are two advantages in doing this: Constants make your program easier to read and check for correctness. If a constant needs to be changed (for instance if the tax rates change) all you need to do is change the declaration of the constant. You don't have to search through your program for every occurrence of a specific number.

- 23 -

Chapter 4 Review Questions: 1. Is the following a correct expression? 13 * 6

Expressions and Arithmetic Operators

2. Are arithmetic expressions the only kind of expression?

3. Do you expect that a modern electronic calculator will give you the same answer as Java for the expression (31.5 - 12)/4.1 ?

4. What is the result of evaluating the following expression: 1/2 + 1/2

5. What is the value of the expression 99/100 ?

6. What is the value of the expression 3/4 ?

7. In an expression like 34.12 / 68.0 how do you know if the / means "integer division" or means "floating point division" ?

8. What type (integer or floating point) of operator is the / in the following: (12 + 0.0) / 7

9. What is the result of evaluating this expression ( a/b + 4) / 2 Assume that a contains 6 and b contains 12.0

10. What is the remainder after dividing 13 by 5 (with integer division)?

11. Why were the innermost set of parentheses used in the statement: System.out.println("The original : " + (quotient*3 + remainder) );

12. If you exchange 372 pennies for dollar bills, how many bills do you get? How many pennies are left over?

- 24 -

Chapter 4

Expressions and Arithmetic Operators

Lab 4
General Instructions: Write each of these programs as specified. None of these programs expect the user to enter data. The values one of these programs uses is "hard wired" into the program with declaration statements or assignment statements. Usually this is a poor way to write a program. Input will be covered in the next two days. After you read them you could come back and write a better version of these programs. Note: Each of these exercises asks you to run the program several times with different values. This is important to do! Playing with your programs is vital to understanding them and getting "feel" of programming under you skin. Exercise 1 --- Average Rain Fall Write a program that averages the rain fall for three months, April, May, and June. Declare and initialize a variable to the rain fall for each month. Compute the average, and write out the results, something like:
Rainfall for April: 12 Rainfall for May : 14 Rainfall for June: 8 Average rainfall: 11.333333

To get the numerical values to line up use the tabulation character '\t' as part of the character string in the output statements. Check that your program prints the correct results. There is a beginner's error lurking in this program too! Did you fall victim to it? Exercise 2 --- Trigonometry To compute the sine of a double precision value use this method: Math.sin( value ) The value is in radians (not degrees.) The cosine is computed using Math.cos( value ) Again, value is in radians. Write a program that: 1. Computes the sine of 0.5236 radians and saves it in a variable. 2. Computes the cosine of 0.5236 radians and saves it in another variable. 3. Computes the square of each those two values (use the variables), adds the two squares, and saves the result (in a third variable.) Writes out the three variables. The output statement should be something like: System.out.println("sine: " + sinx + " cosine: " + cosx + " sum: " + sum ); Try a few other values besides 0.5236.
- 25 -

Chapter 4 Exercise 3 --- Degrees to Radians

Expressions and Arithmetic Operators

It is sometimes hard to think in terms of radians; we would rather use degrees. Remember (from those dark days of trigonometry class) that there are PI radians per 180 degrees. So to convert an angle given in degrees to radians do this: rad = degrees * Math.PI/180 Math.PI gives you an accurate value of PI. Edit the previous program so that it does the same things, but the angle is 30 degrees (which you will convert into radians.)

- 26 -

Chapter 5

Classes and Methods

Chapter 5 - Classes and Methods


As discussed earlier, we have two kinds of data type. Primitive data type and non primitive data, Non primitive data type also called objects.

An object is a large chunk of memory that can potentially contain a great deal of data along with methods (little programs) to process data. It often represents a corresponding real world object.

Java Class: A Java class or simply class is a factory for objects, it produces objects. There are hundreds of object classes that come standard with Java, and a programmer can easily create additional classes. Class Libraries and Java API: A class library is a set of classes that support the development of programs. The Java Application Programming Interfaces (API) is a set of class libraries. The classes of the Java API are grouped into package. A package is a Java language element used to group related classes under common name. Packages can be nested inside one another. All of the packages in the Java are collected into a single package that is simply called Java API.

- 27 -

Chapter 5

Classes and Methods

Anatomy of a Class: A class consists of both variables and methods. A class is merely a description of an object. The picture illustrates a conceptual class for a car.

Instance Variables: The variables that a class contains are called instance variables, fields or data of the class. Methods: Methods are used to modify the instance variables of a class. Or more generally a method is a group of programming language statements associated with a particular class. Main Method: Every application class has a main method. We have defined the main method of a program many times. Syntax for Defining a Method:

return type method-name { programming statements }

(parameter list)

The header of a method includes the type of the return value, the method name, and list of parameters that the method accepts. The list of statements that makes up the body of the method are defined in a block.

- 28 -

Chapter 5

Classes and Methods

The following code is the definition of a method called thirdPower:

int thirdPower( int number) { int cube; // local variable Cube = number * number * number; Return cube; } Local Variables: A method may declare local variables in the body of the method for use only in that method. These variables are called local variables, because they are local to that method only. The variable cube in the thirdPower method is local to this method. The return Statement: Method can return a value, whose type must correspond to the return type in the method header. The return type can be a primitive type or an object type. When a method does not return any value, the reserved word void is used as the return type, as is always done with the main method. A return type must always be specified in the method header. Parameters: A parameter is a value that is passed into a method when it is invoked. The parameter list in the header of a method specifies the type of the values that are passed. The following method adds the two passed integer parameters and return their sum.

int add( int num1, int num2) { int result; // local variable result = num1 + num2; Return result; } Constructor: Constructor is a special method that is used to construct objects of that class. Every class has a constructor. If the programmer doesn't provide one, then the system will provide a default constructor. This default constructor does nothing beyond the basics: allocate memory and initialize instance variables. Remember a constructor has no return type and has name as of its class. Class Syntax:

- 29 -

Chapter 5

Classes and Methods

The basic syntax for defining a class in Java is: Class class-name { - Instance variables declaration - constructors - methods } Example Java class for fractions: 1 2 public class Fraction int numerator; 3 { int denominator; 4 5 public Fraction( int nume, int denom) 6 { 7 numerator = nume; 8 denominator = denom; 9 } 10 -------- Methods ---------11 // 12 13 public int getNumerator( ) 14 { return numerator; 15 } 16 17 18 public int getDenumerator( ) 19 { return denominator; 20 } 21 22 23 public string toString( ) 24 { return (numerator + / +denominator); 25 } 26 27 public static void main( String[] args) { Fraction myFraction; 28 myFraction = new Fraction(3,4); 29 int numVal = myFraction.getNumerator( ); 30 System.out.println(Numenator Value: + numVal); 31 System.out.println(Fraction: + myFraction); 32 } We start our class anatomy exploration by looking the above program

- 30 -

Chapter 5

Classes and Methods

The statement on line 2 indicates the beginning of a class named Fraction. This statement is class header and is followed by two braces (an opening brace on line 3 and a closing brace on line 28. On line 3 and 4 two instance variables of type int are defined. On line 6 constructor of the class is defined, it takes two int type parameters and initialize the instance variables. On line 15 a method getNumerator( ) with return type int is defined. This method return the value of the instanve variable numerator. Similarly on line 25 a method toString( ) with return type string is defined. toString( ) Method: toString( ) method return a textual description of the object on which it is invoked. main( String[] args) main method On line 26 main method of the class start. Before we explore inside block of the main method, we need to understand the concept of the objects. Creating an Object: As mentioned earlier classes can be thought of as factories of objects. To make a new object, first we search a class in Java library if there is no class for our purpose then we make a new class. Even we can make our class regardless class exist in Java library or not. There are two steps to create an object from an existing class.

1. Declare a variable(Also called a reference variable) with type of that class Fraction myFraction; 2. Instantiate the class using its constructor myFraction = new Fraction(3,4);

Dot Notation:

- 31 -

Chapter 5

Classes and Methods

The various things an object containsits variables and its methodsare called the members of that object. The members of an object are accessed using dot notation, which looks like this: objectReference . memberName If you want to run a method of the object, use the method name. If it needs parameters (values supplied to the method), they go inside ( ) like this: objectReference . methodName( parameter ) Always use ( ) with a method name, even if it needs no parameters. Creating an Object of Fraction Class: Look at the line 27 of the fraction class. A reference variable myFraction is declared. On line 28, an object of class fraction is created by using constructor. On line 29 value of numerator is obtained by invoking getNumerator( ) method. On line 30 a library class System and its instance variable out, out is a variable of type printStream and method println( ) is a method of printStream class is used to put the output on the monitor. Static Variables and Static Methods: So for we discussed, objects are created from classes and we have seen that a class can contain variables and methods. And an object is also a collection of variables and methods. The variables and methods that the object contains are called instance variables and instance methods. Some time in programming we need variables or methods that is common to all objects of that class, then we use keyword static to declare such variables or methods. Static variables or methods are also called class variables or class methods. Static methods are not referenced through a particular instance of a class (Object) but through the class itself. As we have seen non static methods always invoked on the objects of the class using dot notation. The compiler will issue an error is a static method attempts to use with an object of the class. The main method of a Java class must be declared static so that main method can be executed without instantiating an object.

- 32 -

Chapter 5

Classes and Methods

Invoking Static Method:

Aclass.aMehod( ); aMethod is a static method of class name Aclass

Example: public class students { static int count = 0; public students( ) { count = count +1; } // constructor

public static int numberOf Students( ) { return count; } public static void main(String[] args) { Student Ali = new Student(); Student Jesi = new Student(); Student Fatima = new Student(); int totalStudents; totalStudents = Stdent. int numberOf Students( ); System.out.println(totalStudents); } } // class students

The variable count is shared among all objects of the Student class.

- 33 -

Chapter 5

Classes and Methods

Review Question: 1. What are the two divisions of data in Java?

2. Can objects contain primitive data?

3. What are the two steps in creating an object?

4. Are the object and the reference variable different things?

5. What is the difference between an object and a class?

6. What are constructors used for? How they are defined.

7. What is static in Java?

8. What is the difference between declaring a variable and defining a variable?

9. How can you determine whether a variable in a given class is static?

10. Where do you look to determine whether a method is void?

- 34 -

Chapter 5

Classes and Methods

Lab 5
Exercise 1 --- Implementation of Fraction Class a. Implement the following methods of Fraction class. public class Fraction { int numerator = 1; int denominator = 1; // implement two constructors public Fraction add ( Fraction a, Fraction b) { // implement the body of the method } public Fraction subtract ( Fraction a, Fraction b) { // implement the body of the method } public Fraction multiply ( Fraction a, Fraction b) { // implement the body of the method } public String toString ( ) { // implement the body of the method } public static int countFractions( ) { return count; // count is a static variable }

public static void main(String[] args) { // implement the body of the method } } // fraction class

- 35 -

Chapter 5

Classes and Methods

b. Implement the main method of your Fraction class such that your program exactly produce the following output:

Fraction 1 = 3 / 4 Fraction 2 = 5 / 2 Fraction 3 = 7 / 2 Fraction 1 + Fraction 2 = 13 / 4 Fraction 2 Fraction 3 = -1 / 1 Fraction 3 * Fraction 1 = 21 / 8 Total Fractions = 3

- 36 -

Chapter 6

Use of Java API and Console Input

Chapter 6 Use of Java API and Console Input


Java API: Java API stands for a "Java Application Programming Interface". It is like a super dictionary of the Java language, that one uses to look something up in. It has an index or collection of all Java classes with all of their methods, fields (instance variables) and constructors, and how to use them. When one programs, there are many classes that are commonly used, and therefore pre created, so that the programmer doesn't need to create them from scratch. Let's look, for example, Math class. If the programmer had to create one from scratch, he would have to write hundreds of lines of code and this Math class is used frequently. Every programmer has to write his own Math class. Thanks to Java who has written the code for one, and programmers use this class. Programmers do not care how classes are implemented, all they need to know are what the methods are, the constructors, and it's fields. Hence the name Java Application Programming Interface, the API is a collection of interfaces telling us what each class can do, not telling us how it is done. The API contains many packages for many different purposes, among them, the applet package for creating applets, the awt and swing packages for graphics and GUI, the io package for input and output, the sql package for Java databasing, and many more. For every package that you use a class from you must import it, with the exception of the java.lang package that deals with basic programming classes, that is automatically imported into your program. Each API is organized in the following way. When you start the API you are given three frames, the first listing all of the Java packages in that API, and when you click on any particular package, the second frame lists all of the interfaces, classes, and exceptions in that package. The main frame starts with an overview of all of the packages, and shows the index, class hierarchy for each package, and help section when you click for it on the top menu. Also, it gives you the details for each class document. The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields. The class document is set up with the top showing that class inheritance diagram and subclasses, the middle showing the field, method, and constructor summaries, and the bottom giving details for the fields, methods, and constructors. For more information, check out the APIs help section. The web site for Java API is www.java.sun.com/j2se/1.4.2/docs/api/ You can also down load an offline version from www.java.com In short, when you start programming, you're constantly going to have to look up something in the API. There's going to be some class or method that you don't know how to use, you're not sure what parameters it takes, etc, and you can find out all of the information in the API

- 37 -

Chapter 6 Java API in HTML Format:

Use of Java API and Console Input

Example Program using API:

public class TestAPI { public static void main( String[] args) { int p = Math.pow(2,3); int c = Math.cos(2.12); int s = Math.sqrt(25); System.out.println(Exponent :+p); System.out.println(Cosin Value :+c); System.out.println(Square Root :+s); } }

Compile and run the above program and observe its output.

- 38 -

Chapter 6 Input and Output of the Program:

Use of Java API and Console Input

Input is any information that is needed by your program to complete its execution. There are many forms that program input may take. Some programs use graphical components like a popup dialog box to accept and return the character string that is typed by the user. You are certainly familiar with programs that are controlled simply by clicking the mouse in a specific area of the screen. Still other programs, like word processing programs, get some of their input from a file that is stored on the computer's floppy or hard disk drive. Some programs, like web browsers, get their data from a network connection, while others get data from devices like scanners, digital cameras and microphones. Output is any information that the program must convey to the user. The information you see on your computer screen is being output by one or more programs that are currently running on your computer. When you decide to print a document, a program is told to send some output to the printer. Any sound that your computer makes is because some program sent output to the speakers on your computer. Java Input and Output: In Java, a source of input data is called an input stream and the output data is called an output stream. Think of these streams like this:

A program may have several input streams flowing into it and several output streams flowing out of it. For most of the programs in these notes, there are three I/O streams: System.in the input stream. System.out the output stream for normal results. System.err the output stream for error messages.

Normally System.in is connected to the standard input (keyboard) and the data are characters. System.out and System.err both are connected to the standard output (monitor). The print and println methods send information to monitor. These notes do not use System.err. Console Input: Console input is any input data that is entered through the console window (Dos prompt window) for the program.

- 39 -

Chapter 6 Example I/O Program:

Use of Java API and Console Input

Reading from standard input is somewhat more involved than writing to standard output. Lets examine that read a string of characters from the user and prints it back out. Imort java.io*; // class Echo reads a string from the user and prints it public class Echo { public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)) ); String message; System.out.println(Enter a line of text:); Message = stdin.readLine( ); System.out.println( You entered: \+message +); } // main method

} // class Echo

After being compiled, the program can be executed. A sample run of the program is presented below. Enter a line of text: Java is interesting You entered: Java is interesting In this program we made an object stdin of BufferedReader class. BufferedReader class is defined in the java.io package, which is imported on the first line of the program. If we look at the API of BufferedReader class, we need to pass an object of InputStreamReader class to the constructor of BufferedReader class to construct its object. We did this all with the following declaration: BufferedReader stdin = new BufferedReader( new IputStreamReader(System.in)) );

The readLine method throws an exception ( see the API), thats the reason header of the main method goes some thing different (throws IOException)

- 40 -

Chapter 6 Review Questions:

Use of Java API and Console Input

1. What is difference between a class and an API. 2. What are the main parts of a class API. 3. Do you need to see the method detail to be able to determine the return of a method. 4. What does the keyboard send to your program when you type 1234 5. Consider the following program. import java.util.Scanner; class Echo { public static void main (String[] args) { String inData; Scanner scan = new Scanner( System.in ); System.out.println("Enter the data:"); inData = scan.nextLine(); System.out.println("You entered:" + inData ); } }

Does the output of this program is exactly as given in the example program. If your answer is yes then where is the difference? 6. Is data from the keyboard always only characters? 7. Can a string of digits from the keyboard be converted into an int type? 8. 9. Can arithmetic be done with strings of characters? How should the program react if an input is invalid?

10. Could the +80 be interpreted as an integer?

- 41 -

Chapter 6

Use of Java API and Console Input

Lab 6
Exercise 1 --- Use of String class API Write a program that takes a string from user similar in the example program and prints on standard output the same string with capital letters and number of characters in the string. Exercise 2 --- Average of five numbers Write a program that takes five integers from the user through console window and prints their average on the standard output. Exercise 3 --- Play with substring( ) Consider the following program public class StringDemo3 { public static void main ( String[] args ) { String str = new String( "Golf is a good walk spoiled." ); // create the original object String sub = str.substring(8); //create a new object from the original System.out.println( sub ); } } String objects have another version of the substring( ) method that looks like this: substring(int beginIndex, int endIndex)

This method creates a new String object, based on the original object, but containing only the characters that start at beginIndex and end at endIndex. A completely new object is created; the characters it contains are copies of those in the original object. For example String str = new String( "Golf is a good walk spoiled." ); String sub = str.substring(8, 18); Create a new object (referenced by sub) containing the characters "a good walk" . Modify your program so that it uses this two-parameter substring( ). Experiment with the two parameters to confirm how they work. Now try the questions on the next page.

1. Make both parameters the same value.


- 42 -

Chapter 6

Use of Java API and Console Input

2. Make the first parameter 0, and the last parameter the index of the last character (26 for the example). 3. Instead of using a literal 26 in the above, use str.length( )-1

- 43 -

Chapter 7

Making Decisions and Repetitions

Chapter 7 Making Decisions and Repetitions


All the programs that we have written so for are monotonous in the sense that they always perform the same action. Now we look at how computer programs make decisions and repetitions about numbers and variables using the conditional statement and looping statements. These statements are one of the fundamental building blocks of programming. Two-way Decisions: The windshield wipers are controlled with an ON-OFF switch. The following flowchart shows how this decision is made.

In the chart, start at the top, then follow the line to the question: Is it raining? The answer is either true or false. If the answer is true, follow the line labeled True, perform the instructions in the box "wipers on", follow the line to "continue". If the answer is false, follow the line labeled False, perform the instructions in the box "wipers off", follow the line to "continue".
- 44 -

Chapter 7 One-way Decisions:

Making Decisions and Repetitions

Suppose the windshield wipers are automatic. Then the following flowchart shows how this decision is made.

Java Syntax: if ( condition ) statement if ( condition ) statement else statement Example Program: import java.util.Scanner; class NumberTester { public static void main (String[] args) { Scanner scan = new Scanner( System.in ); int num; System.out.println("Enter an integer:"); num = scan.nextInt(); if ( num < 0 ) // is num less than zero? System.out.println("The number " + num + " is negative"); else System.out.println("The number " + num + " is positive"); System.out.println("Good-bye for now"); executed } // method } // class // always if statement if else statement

The words if and else are markers that divide the decision into two sections. The else divides the true branch from the false branch.

- 45 -

Chapter 7

Making Decisions and Repetitions

The if statment always asks a question (often about a variable.) If the answer is true only the true-branch is exectued. If the answer is false only the false-branch is executed. No matter which branch is chosen, execution continues with the statement after the false-branch.

Repetitions: Often when writing a program, it is necessary to repeat a statement or block many times. This task is accomplished with a repetition statement or loops. The while statement: Here is a program with a loop: // Example of a while loop class LoopExample { public static void main (String[] args ) { int count = 1; // start count out at one while ( count <= 3 ) // loop while count is <= 3 { System.out.println( "count is:" + count ); count = count + 1; // add one to count } System.out.println( "Done with the loop" ); } }

The flowchart on the next page shows how the program works. First, count is set to one. Then it is tested to see if it is less than or equal to three. If the test returns true the two statements in the block following the while are executed. The statement count = count + 1 increases the value stored in the variable count by adding one to it. Then execution goes back to the while statement and the process is repeated. If the test returns false, execution goes to the "Done with loop" statment. Then the program ends. Copy this program to a file and run it. Then hack upon it. See if changing a few things does what you expect.

- 46 -

Chapter 7

Making Decisions and Repetitions

Syntax of the while statement: While ( condition ) { statement } Three Things to Coordinate: There are three things to coordinate when your program has a loop: 1. The initial values must be set up correctly. 2. The condition in the while statement must be correct. 3. The change in variable(s) must be done correctly. The while statements are good to use when you do not initially know how many times you want to execute the loop body. Another type of loop statement if for loop that is particularly well suited for executing the body of a loop a specific number of times. The syntax of the for statement is:

- 47 -

Chapter 7 Syntax of the for statement:

Making Decisions and Repetitions

for (initialization; condition; increment) { statement; } Note that the initialization portion is only performed once, but the increment portion is executed after each iteration of the loop. The execution of a for loop is equivalent to the following code that uses a while statement initialization; while ( condition ) { statement; increment; }

Example: Here is a loop written as both a while loop and a for loop. First using while: int number = 1; while (number <= 12) { System.out.println(number + " squared is " + (number * number)); number++; } And here is the same loop using for

for (int number = 1; number <= 12; number++) { System.out.println(number + " squared is " + (number * number)); }

- 48 -

Chapter 7 Review Questions: 1. Is the following section of a program correct?

Making Decisions and Repetitions

if ( num < 0 ) System.out.println("The number " + num + " is negative"); else System.out.println("The number " + num + " is positive"); System.out.print ("positive numbers are greater "); System.out.println("than zero "); System.out.println("Good-bye for now"); 2. How would you fix the above? 3. How could you divide a group of people into: children male adults female adults 4. Could an if statement be nested inside the true branch of another if statement? 5. What is the output of the following: import java.io.*; class DecimalFraction { public static void main (String[] args) throws IOException { float x = 1.0f; // 1.0f means 1.0 float float y = 10.0f; if ( x/y == 0.1 ) System.out.println("Buy the cookie!" ); else System.out.println("No cookie for you."); } }

- 49 -

Chapter 7

Making Decisions and Repetitions

Lab 7
Exercise 1 --- Y2K Problem Detector Write a program that asks a user for their birth year encoded as two digits (like "62") and for the current year, also encoded as two digits (like "99"). The program is to correctly write out the users age in years. Year of Birth: 62 Current year: 99 Your age: 37 ----- Another run of the program -------Year of Birth: 62 Current year: 00 Your age: 38 Exercise 2 --- Wind Chill Index (You will need to include java.Math.* and use floating point input for this exercise.) The wind chill index (WCI) is calculated from the wind speed v in miles per hour and the temperature t in Fahrenheit. Three formulas are used, depending on the wind speed: if (0 <= v <= 4) then WCI = t if (v >=45) then WCI = 1.6t - 55 otherwise, WCI = 91.4 + (91.4 - t)(0.0203v - 0.304(v)1/2 - 0.474) Exercise 3 Write a program that asks the user to enter two words. The program then prints out both words on one line. The words will be separated by enough dots so that the total line length is 30: Enter first word: turtle Enter second word 153 turtle....................153

- 50 -

You might also like