AP Computer Science A

September 4 to 28.

Ch. 3: Java Basics.


LNK2LRN™2007/08

Plans for the Week and Assignments:

1. TUESDAY(09/04): Setting-up the NetBeans IDE and testing file

operations.  HW: Read p.122-133, then solve prob.1, 8, 11, and 13 on

pages 131-133.

2. WEDNESDAY(09/05): Program 3_1 Greeter. HW: Read

p.133-141, then solve prob.1, 8, and 14 on pages 142-143.

3. THURSDAY(09/06): Program 3_2 HelloWorldAddition. HW: Read

p.143-148, then solve prob.1 to 5, 9, 12, and 15 on pages 149-150.

4. FRIDAY(09/07): Check answers to all assigned homework.

HW: Complete Review handout #3_1.

5. MONDAY(09/10): Program 3_3 EvenOdd. HW: Read p.150-154,

then solve prob.1 to 4 on pages 154-155.

6. TUESDAY(09/11): Program 3_4 AddTwoNumbersDisplaySum.

HW: Read p.155-163, then solve prob.2 to 4 on page 168.

7. WEDNESDAY(09/12): Program 3_5 Euclid'sGCD. HW: Read

p.163-168, then solve prob.6 to 10 on page 168.

8. THURSDAY(09/13): No School.

9. FRIDAY(09/14): Check answers to all assigned homework, and

begin programming Round 1. HW: Complete Review handout #3_2.

10. MONDAY(09/17): Program 3_6 CylinderVolume. HW: Solve

prob.11 to 16 on pages 168-169.

11. TUESDAY(09/18): Program 3_7 CylinderVolumeAndSurfaceArea.

HW: Solve prob.17 to 22 on page 169.

12. WEDNESDAY(09/19): Program 3_8 SphereVolumeAndSurfaceArea.

HW: Complete Review handout #3_3.

13. THURSDAY(09/20): Check all assigned homework and REVIEW for

Test on Ch.3(3.1-3.5).  HW: Complete Review handout #3_3.

14. FRIDAY(09/21): TEST on Ch.3(3.1-3.5) - Java Basics.

HW: Go to web site for notes on the rest of Ch.3 - Inputs and Type-Casting.

15. MONDAY(09/24): Using the System.currentTimeMillis() method, and

begin programming Round 2. HW: Read p.169-174, then solve prob.1, 2, 7,

8, and 9 on pages 178-179.

16. TUESDAY(09/25): Using the Keyboard class. HW: Read p.174-178,

then solve prob.5, 6, and 10 pages 179-180.

17. WEDNESDAY(09/26): Conversion between types, implicit and explicit.

HW: Read p.180-184, then solve prob.1 to 5 on page 184.

18. THURSDAY(09/27): Compound assignment operators, and Random

Number Generator Assignment. HW: Read p.185, then solve prob.1 and 2 on

page 185.

19. FRIDAY(09/28): No School - Fall Vacation Day. HW: Work on, Random

Number Generator Assignment, due Monday. Good idea to use a Plane Curve.

 

Very Important: If you have any questions or were absent from class,

see me before school (8:00 - 8:30 AM), during Lunch, 7th hour, or after

school. Best to send an email to rpersin@fau.edu.

 

Website Notes for Ch.3 : Java Basics.

I. Classes and Methods.

1. Every Java application contains a class that defines a method called

main(). The name of this class is the name that you use as the argument

to the Java interpreter when you run the application. You can call the class

what you want, but the method which is executed first in an application is

always called main().

2. When you run your Java application the method main() will typically

cause methods belonging to other classes to be executed, but the simplest

possible Java application program consists of one class containing just the

method main().

3. As we shall see below, the main() method has a particular fixed form,

and if it is not of the required form, it will not be recognized by the Java

interpreter as the method where execution starts.

4. The code for the program is:

5. The program consists of a definition for a class we have called

OurFirstProgram. The class definition only contains one method, the

method main(). The first line of the definition for the method main()

is always of the form:

public static void main(String[] args)

6. The code for the method appears between the pair of curly braces.

Our version of the method has only one executable statement:

System.out.println("Krakatoa, EAST of Java??");

II. Data and Variables

1. A variable is a named piece of memory that you use to store information

in your Java program – a piece of data of some description. Each named

piece of memory that you define in your program will only be able to store

data of one particular type.

2. If you define a variable to store integers, for example, you cannot use it

to store a value that is a decimal fraction, such as 0.75. Since the type of

data that each variable can store is fixed, whenever you use a variable in

your program the compiler is able to check that it is not being used in a

manner or a context that is inappropriate to its type.

3. If a method in your program is supposed to process integers, the compiler

will be able to detect when you inadvertently try to use the method with

some other kind of data, for example, a string or a numerical value that is

not integral.

4. Explicit data values that appear in your program are called literals. Each

literal will also be of a particular type: 25, for instance, is an integer value

of type int.

5. Before you can use a variable you must specify its name and type in a

declaration statement. Before we look at how you write a declaration for a

variable, we should consider what flexibility you have in choosing a name.

III. Variable Names

1. The name that you choose for a variable, or indeed the name that you

choose for anything in Java, is called an identifier. An identifier can be any

length, but it must start with a letter, an underscore (_), or a dollar sign ($).

The rest of an identifier can include any characters except those used as

operators in Java (such as +, –, or *), but you will be generally better off

if you stick to letters, digits, and the underscore character.

2. Java is case sensitive, so the names Newton and newton are not the

same. You must not include blanks or tabs in the middle of a name, so

Joe Smith is out, but you could have JoeSmith or even Joe_Smith.

3. Subject to the restrictions we have mentioned, you can name a variable

almost anything you like, except for two additional restraints – you can't

use keywords in Java as a name for something, and a name can't be

anything that is a constant value.

4. Keywords are words that are an essential part of the Java language.

The restriction on constant values is there because, although it is obvious

why a name can't be 1234 or 37.5, constants can also be alphabetic, such

as true and false for example. 

5. Clearly, it makes sense to choose names for your variables that give a

good indication of the sort of data they hold. If you want to record the

size of a hat, for example, hatSize is not a bad choice for a variable name

whereas qqq would be a bad choice. It is a common convention in Java to

start variable names with a lower case letter and, where you have a name

that combines several words, to capitalize the first letter of each word, as

in hatSize or moneyWellSpent. You are in no way obliged to follow this

convention but since almost all the Java world does, it helps to do so.

Take a look at http://www.javasoft.com/docs/codeconv/.

IV. Variables and Types.

1. As we mentioned earlier, each variable that you declare can store

values of a type determined by the data type of that variable. You

specify the type of a particular variable by using a type name in the

variable declaration. For instance, here's a statement that declares a

variable that can store integers:

int numberOfCats;

2. The data type in this case is int, the variable name is numberOfCats,

and the semicolon marks the end of the statement. The variable,

numberOfCats, can only store values of type int.

3. The only things in Java that are not objects are variables that

correspond to one of eight basic data types, defined within the language.

These fundamental types, also called primitive types, allow you to define

variables for storing data that fall into one of three categories:

  • Numeric values, which can be either integer or floating point

  • Variables which store a single Unicode character

  • Logical variables that can assume the values true or false

All of the type names for the basic variable types are keywords in Java so

you must not use them for other purposes.

 

V. Integer Data Types

1. There are four types of variables that you can use to store integer data.

All of these are signed, that is, they can store both negative and positive

values. The four integer types differ in the range of values they can store,

so the choice of type for a variable depends on the range of data values

you are likely to need.

2. The four integer types in Java are:

Data Type

Description

byte

Variables of this type can have values from -128 to +127 and occupy 1 byte (8 bits) in memory

short

Variables of this type can have values from -32768 to 32767 and occupy 2 bytes (16 bits) in memory

int

Variables of this type can have values from -2147483648 to 2147483647 and occupy 4 bytes (32 bits) in memory

long

Variables of this type can have values from -9223372036854775808 to 9223372036854775807 and occupy 8 bytes (64 bits) in memory

3. Let's take a look at declarations of variables of each of these types:

byte smallerValue;
short pageCount;
int wordCount;
long bigValue;

Each of these statements declares a variable of the type specified.

4. The range of values that can be stored by each integer type in Java, as

shown in the table above, is always the same, regardless of what kind of

computer you are using. This is also true of the other basic types that we

will see later in this chapter, and has the rather useful effect that your

program will execute in the same way on computers that may be quite

different. This is not necessarily the case with other languages.

5. Of course, although we have expressed the range of possible values for

each type as decimal values, integers are stored internally as binary

numbers, and it is the number of bits available to store each type that

determines the maximum and minimum values.

VI. Integer Values

1. Any integer literal that you specify is of type int by default. Thus 1,

-9999, and 123456789 are all literals of type int. If you want to define an

integer of type long, and the value that you assign to the variable is bigger

than an int, you need to append an L to the value. The values 1L, -9999L,

and 123456789L are all of type long. You can also use a lower case letter l,

but don't – it is too easily confused with the digit 1.

2. You are perhaps wondering how you specify literals of type byte or short.

Because of the way integer arithmetic works in Java, they just aren't

necessary in the main. We will see a couple of instances where an integer

literal may be interpreted by the compiler as type byte or short later in this

chapter, but these situations are the exception.

3. As you saw earlier, we can declare a variable of type long with the

statement:

long bigOne;

This statement is a declaration for the variable bigOne. This specifies that

the variable bigOne will store a value of type long. When this statement is

compiled, 8 bytes of memory will be allocated for the variable bigOne.

4. Java does not automatically initialize a variable such as this. If you want

your variables to have an initial value rather than a junk value left over from

when the memory was last used, you must specify your own value in the

declaration. To declare and initialize the variable bigOne to 2999999999,

you just write:

long bigOne = 2999999999L;

5. You can declare and define multiple variables in a single statement.

For example:

long bigOne = 999999999L, largeOne = 100000000L;

6. You can declare as many variables as you like in a single statement,

although it is usually better to stick to declaring one variable in each

statement as it helps to make your programs easier to read. A possible

exception occurs with variables that are closely related – an (x,y)

coordinate pair representing a point, for example, which you might

reasonably declare as:

int xCoord = 0, yCoord = 0;       // Point coordinates

7. On the same line as the declaration of these two variables, we have a

comment following the double slash, explaining what they are about. The

compiler ignores everything from the double slash until the end of the line.

8. You can also spread a single declaration over several lines if you want.

This also can help to make your program more readable. For example:

int miles    = 0,          // One mile is 8 furlongs
    furlongs = 0,          // One furlong is 220 yards
    yards    = 0,          // One yard is 3 feet
    feet     = 0;

9. Naturally, you must be sure that an initializing value for a variable is

within the range of the type concerned, otherwise the compiler will

complain. Your compiler is intelligent enough to recognize that you can't

get a quart into a pint pot, or, alternatively, a long constant into a

variable of type int, short, or byte.

10. To complete the set we can declare and initialize a variable of type

byte and one of type short with the following two statements:

byte luckyNumber = 7;
short smallNumber = 1234;

11. Most of the time you will find that variables of type int will cover your

needs for dealing with integers, with long ones being necessary now and

again when you have some really big integer values to deal with.

12. Variables of type byte and short do save a little memory, but unless

you have a lot of values of these types to store, that is, values with a

very limited range, they won't save enough to be worth worrying about.

13. They also introduce complications when you use them in calculations,

as we shall see shortly, so generally you should not use them unless it is

absolutely necessary. Of course, when you are reading data from some

external source, a disk file for instance, you will need to make the type

of variable for each data value correspond to what you expect to read.

VII. Floating Point Data Types

1. Numeric values that are not integral are stored as floating point

numbers. A floating point number has a fixed number of digits of accuracy

but with a very wide range of values. You get a wide range of values,

even though the number of digits is fixed, because the decimal point can

"float".

2. For example the values 0.000005, 500.0, and 5000000000000.0 can be

written as 5x10-6, 5x102, and 5x1012 respectively – we have just one digit

'5' but we move the decimal point around.

3. There are two basic floating point types in Java, float and double. These

give you a choice in the number of digits precision available to represent

your data values, and in the range of values that can be accommodated:

Data Type

Description

float

Variables of this type can have values from -3.4E38 (-3.4x1038) to +3.4E38 (+3.4x1038) and occupy 4 bytes in memory. Values are represented with approximately 7 digits accuracy.

double

Variables of this type can have values from -1.7E308 (-1.7x10308) to +1.7E308 (+1.7x10308) and occupy 8 bytes in memory. Values are represented with approximately 17 digits accuracy. The smallest non-zero value that you can have is roughly (4.9x10-324.

VIII. Floating Point Values

1. When you are specifying floating point literals they are of type double

bydefault, so 1.0 and 345.678 are both of type double. When you want to

specify a value of type float, you just append an f, or an F, to the value,

so 1.0f and 345.678F are both constants of type float.

2. If you are new to programming it is important to note that you must not

include commas as separators when specifying numerical values in your

program code. Where you might normally write a value as 99,786.5, in your

code you must write it without the comma, as 99786.5.

3. When you need to write very large or very small floating point values,

you will usually want to write them with an exponent – that is, as a decimal

value multiplied by a power of 10. You can do this in Java by writing the

number as a decimal value followed by an E, or an e, preceding the power

of 10 that you require.

4. For example, the distance from the Earth to the Sun is approximately

149,600,000 kilometers, more conveniently written as 1.496E8. Since the

E (or e) indicates that what follows is the exponent, this is equivalent to

1.496x108.

5. At the opposite end of the scale, the mass of an electron is around

0.0000000000000000000000000009 grams. This is much more convenient,

not to say more readable, when it is written as 9.0E-28 grams.

 

IX. Declaring Floating Point Variables

1. You declare floating point variables in a similar way to that we've

already used for integers. We can declare and initialize a variable of type

double with the statement:

double sunDistance = 1.496E8;

2. Declaring a variable of type float is much the same. For example:

float electronMass = 9E-28F;

You can of course declare more than one variable of a given type in a

single statement:

float hisWeight = 185.2F, herWeight = 108.5F;

3. Note that you must put the F or f for literals of type float. If you leave

it out, the literal will be of type double, and the compiler won't convert it

automatically to type float.

X. Arithmetic Calculations

1. You store the result of a calculation in a variable by using an

assignment statement. An assignment statement consists of a variable

name followed by an assignment operator, followed by an arithmetic

expression, followed by a semicolon. Here is a simple example of an

assignment statement:

numFruit = numApples + numOranges;       // Calculate the total fruit

2. Incrementing a variable by a given amount is a common requirement in

programming. Look at the following assignment statement:

numApples = numApples + 1;

3. You can write multiple assignments in a single statement. Suppose you

have three variables a, b, and c, of type int, and you want to set all three

to 777. You can do this with the statement:

a = b = c = 777;

4. With simple assignments of a constant value to a variable of type short

or byte, the constant will be stored as the type of the variable on the left

of the =, rather than type int. For example:

short value = 0;
value = 10;

XI. Integer Calculations

1. The basic operators you can use on integers are +, -, *, and /, which

have the usual meanings – add, subtract, multiply, and divide, respectively.

Each of these is a binary operator; that is, they combine two operands to

produce a result, 2 + 3 for example.

2. An operand is a value to which an operator is applied. The priority or

precedence that applies when an expression using these operators is

evaluated is the same as you learned in school.

3. Multiplication and division are executed before any addition or

subtraction operations, so the expression:

20 – 3*3 – 9/3

will produce the value 8, since it is equivalent to 20 – 9 – 3.

4. As you will also have learned in school, you can use parentheses in

arithmetic calculations to change the sequence of operations.

Expressions within parentheses are always evaluated first, starting

with the innermost when they are nested. Therefore the expression:

(20 – 3)*(3 – 9)/3

is equivalent to 17*(-6)/3 which results in -34.

5. Of course, you use these operators with variables that store integer

values as well as integer literals. You could calculate a value for area

of type int from values stored in the variables length and width, also

of type int, by writing:

area = length * width;

6. The arithmetic operators we have described so far are binary operators,

so called because they require two operands. There are also unary versions

of the + and – operators that apply to a single operand to the right of the

operator.

7. Note that the unary – operator is not just a sign, as in a literal such

as –345, it is an operator that has an effect. When applied to a variable it

results in a value that has the opposite sign to that of the value stored in

the variable.

8. For example, if the variable count has the value -10, the expression

–count has the value +10. Of course, applying the unary + operator to the

 value of a variable results in the same value.

9. Key in the example below and save it in a file Fruit.java. You will

remember from before that each file will contain a class, and that the

name of the file will be the same as that of the class with the extension

 .java. Store the file in a directory that is separate from the hierarchy

containing the SDK. You can give the directory any name that you want,

even the name Fruit if that helps to identify the program that it contains.

10. In some Java development environments, the output may not be

displayed long enough for you to see it. If this is the case, you can add a

few lines of code to get the program to wait until you press Enter before

it ends. The additional lines to do this are shown shaded in the following

listing:

import java.io.IOException;  // For code that delays ending the program

public class Fruit {
  public static void main(String[] args) {
    // Declare and initialize three variables
    int numOranges = 5;                 // Count of oranges
    int numApples = 10;                 // Count of apples
    int numFruit = 0;                   // Count of fruit

    numFruit = numOranges + numApples;  // Calculate the total fruit count

    // Display the result
    System.out.println("A program that totals fruit.");
    System.out.println("Total fruit is " + numFruit);
    // Code to delay ending the program
    System.out.println("(press Enter to exit)");

    try {
      System.in.read();               // Read some input from the keyboard

    } catch (IOException e) {         // Catch the input exception
      return;                         // and just return
    }
  }
}

We won't go into this extra code here. If you need to, just put it in for the

moment. You will understand exactly how it works later in the book.

If you run this program, the output will be similar to the following window:

 

11. Our program consists of just one class, Fruit, and just one method,

main(). Execution of an application always starts at the first executable

statement in the method main(). There are no objects of our class Fruit

defined, but the method main() can still be executed because we have

specified it as static. 12. The method main() is always specified as public

and static and with the return type void. We can summarize the effects of

these on the method as:

public

Specifies that the method is accessible from outside the Fruit class.

static

Specifies that the method is a class method that is to be executable, even though no class objects have been created. (Methods that are not static can only be executed for a particular object of the class, as we will see later.)

void

Specifies that the method does not return a value.

 

XII. Integer Division and Remainders

1. When you divide one integer by another and the result is not exact, any

remainder is discarded, so the final result is always an integer. The division

3/2, for example, produces the result 1, and 11/3 produces the result 3.

2. This makes it easy to divide a given quantity equally amongst a given

number of recipients. To divide numFruit equally between four children, you

could write:

int numFruitEach = 0;                // Number of fruit for each child
numFruitEach = numFruit/4;

3. Of course, there are times where you may want the remainder. On these

occasions you can calculate the remainder using the modulus operator, %.

If you wanted to know how many fruit were left after dividing the total

by 4, you could write:

int remainder = 0;
remainder = numFruit % 4;   // Calculate the remainder after division by 4

4. You could add this to the program too if you want to see the modulus

operator in action. The modulus operator has the same precedence as

multiplication and division, and is therefore executed in a more complex

expression before any add or subtract operations.

XIII. The Increment and Decrement Operators

1. If you want to increment an integer variable by one, instead of using

an assignment you can use the increment operator, which is written as

two successive plus signs, ++. For example, if you have an integer

variable count declared as:

int count = 10;

you can then write the statement:

++count;     // Add 1 to count

which will increase the value of count to 11.

2. If you want to decrease the value of count by 1 you can use the

decrement operator, --:

--count;     // Subtract 1 from count

3. At first sight, apart from reducing the typing a little, this does not

seem to have much of an advantage over writing:

count = count – 1;     // Subtract 1 from count

4. One big advantage of the increment and decrement operators is that

you can use them in an expression. A further property of the increment

and decrement operators is that they work differently in an expression

depending on whether you put the operator in front of the variable, or

following it.

5. When you put the operator in front of a variable it's called the prefix

form. The converse case, with the operator following the variable, is

called the postfix form.

6. The effect of the postfix increment operator is to change the value of

a variable after the original value has been used in an expression. The

postfix decrement operator works similarly, and both operators can be

applied to any type of integer variable.

XIV. Mixed Arithmetic Expressions

1. You can mix values of the basic types together in a single expression.

The way mixed expressions are treated is governed by some simple rules

that apply to each operator in such an expression.

2. The rules, in the sequence in which they are checked, are:

    (a) If either operand is of type double, the other is converted to

         double before the operation is carried out.

    (b) If either operand is of type float, the other is converted to float

         before the operation is carried out.

    (c) If either operand is of type long, the other is converted to long

         before the operation is carried out.

3. The first rule in the sequence that applies to a given operation is the

one that is carried out. If neither operand is double, float, or long, they

must be int, short, or byte, so they use 32-bit arithmetic as we saw

earlier.

XV. Explicit Casting

1. It may well be that the default treatment of mixed expressions listed

above is not what you want. For example, if you have a double variable

result, and you compute its value using two int variables three and two

with the values 3 and 2 respectively, with the statement:

result = 1.5 + 3/2;

the value stored will be 2.5, since 3/2 will be executed as an integer

operation and will produce the result 1.

2. You may have wanted the term 3/2 to produce the value 1.5 so the

overall result would be 3.0. You could do this using an explicit cast:

result = 1.5 + (double)3/2;

3. This causes the value stored in three to be converted to double before

the divide operation takes place. Then the first rule applies for the divide

operation, and the operand two is also converted to double before the

divide is executed. Hence the value of result will be 3.0.

XVI. Casting in Assignments

1. When the type of the result of an expression on the right of an

assignment statement differs from the type of the variable on the left,

an automatic cast will be applied as long as there is no possibility of

losing information.

2. If you think of the basic types that we have seen so far as being in

the sequence:  byte -> short -> int -> long -> float -> double

then an automatic conversion will be made as long as it is upwards

through the sequence, that is, from left to right. If you want to go in

the opposite direction, from double to float or long, for example, then

you must use an explicit cast.

XVII. The op= Operators

1. The op= operators are used in statements of the form:

lhs op= rhs;

where op can be any of the operators +, -, *, /, %, plus some others

you haven't seen yet. The above is basically a shorthand representation

of the statement:

lhs = lhs op (rhs);

2. The right hand side is in brackets because it is worked out first – then

the result is combined with the left hand side using the operation, op.

Let's look at a few examples of this to make sure it's clear. To increment

an int variable count by 5 you can write:

count += 5; 

3. This has the same effect as the statement:

count = count + 5;

Of course, the expression to the right of the op= operator can be

anything that is legal in the context, so the statement:

result /= a % b/(a + b);

is equivalent to:

result = result/(a % b/(a + b));

4. The complete set of op= operators appears in the precedence table

later in this chapter.

XVIII. Mathematical Functions and Constants

1. Sooner or later you are likely to need mathematical functions in your

programs, even if it's only obtaining an absolute value or calculating a

square root. Java provides a range of methods that support such

functions as part of the standard library stored in the package

java.lang, and all these are available in your program automatically.

2. The methods that support various additional mathematical functions

are implemented in the class Math as static methods, so to reference a

particular function you can just write Math and a period in front of the

name of the method you wish to use.

3. For example, to use sqrt(), which calculates the square root of what

you place between the parentheses, you would write the expression

Math.sqrt(aNumber) to produce the square root of the floating point

value in the variable aNumber.

4. The class Math includes a range of methods for standard

trigonometric functions. These are:

Method

Function

Argument Type

Result Type

sin(arg)

sine of the argument

double in radians

double

cos(arg)

cosine of the argument

double in radians

double

tan(arg)

tangent of the argument

double in radians

double

asin(arg)

sin-1 (arc sine) of the argument

double

double in radians with values from –(/2 to (/2.

acos(arg)

cos-1 (arc cosine) of the argument

double

double in radians, with values from 0.0 to (.

atan(arg)

tan-1 (arc tangent) of the argument

double

double in radians with values from –(/2 to (/2.

atan2 (arg1,arg2)

tan-1 (arc tangent) of arg1/arg2

Both double

double in radians with values from –( to (.

5. As with all methods, the arguments that you put between the

parentheses following the method name can be any expression that

produces a value of the required type. If you are not familiar with the

trigonometric operations  we will go over them in school.

6. You also have a range of useful numerical functions that are

implemented in the class Math. These are:

Method

Function

Argument type

Result type

abs(arg)

Calculates the absolute value of the argument

int, long, float, or double

The same type as the argument

max (arg1,arg2)

Returns the larger of the two arguments, both of the same type

int, long, float, or double

The same type as the argument

min (arg1,arg2)

Returns the smaller of the two arguments, both of the same type

int, long, float, or double

The same type as the argument

ceil(arg)

Returns the smallest integer that is greater than or equal to the argument

double

double

floor(arg)

Returns the largest integer that is less than or equal to the argument

double

double

round(arg)

Calculates the nearest integer to the argument value

float or double

Of type int for a float argument, of type long for a double argument

rint(arg)

Calculates the nearest integer to the argument value

double

double

IEEEremainder (arg1,arg2)

Calculates the remainder when arg1 is divided by arg2

Both of type double

Of type double

7. Where more than one type of argument is noted in the table, there are

actually several methods, one for each type of argument, but all have the

same name. We will see how this is possible in Java when we look at

implementing class methods later.

8. The mathematical functions available in the class Math are:

Method

Function

Argument Type

Result Type

sqrt(arg)

Calculates the square root of the argument

double

double

pow (arg1,arg2)

Calculates the first argument raised to the power of the second argument arg1arg2

Both double

double

exp(arg)

Calculates e raised to the power of the argument earg

double

double

log(arg)

Calculates the natural logarithm (base e) of the argument

double

double

random()

Returns a pseudo-random number greater than or equal to 0.0 and less than 1.0

None

double

9. The toRadians()method in the class Math will convert a double argument

that is an angular measurement in degrees to radians.

10. There is a complementary method, toDegrees(), to convert in the

opposite direction. The Math class also defines double values for e and π,

which you can access as Math.E and Math.PI respectively.

11. The following program will calculate the radius of a circle in feet and

inches, given that it has an area of 100 square feet:

public class MathCalc {
  public static void main(String[] args) {
    // Calculate the radius of a circle
    // which has an area of 100 square feet
    double radius = 0.0;
    double circleArea = 100.0;
    int feet = 0;
    int inches = 0;
    radius = Math.sqrt(circleArea/Math.PI);
    feet = (int)Math.floor(radius); // Get the whole number of feet
    inches = (int)Math.round(12.0*(radius – feet));
    System.out.println("The radius of a circle with area " + circleArea +
                       " square feet is\n " + 
                       feet + " feet " + inches + " inches");
  }
}

Save the program as MathCalc.java. When you compile and run it, you

should get:

The radius of a circle with area 100.0 square feet is
 5 feet 8 inches

12. How It Works: The first calculation, after defining the variables we

need, uses the sqrt() method to calculate the radius. Since the area of

a circle with radius r is given by the formula πr2, the radius must be

√(area/π), and we specify the argument to the sqrt() method as the

expression circleArea/Math.PI, where Math.PI references the value of π.

13. The result is in feet as a double value. To get the number of whole

feet we use the floor() method. Note that the cast to int is essential in

this statement otherwise you will get an error message from the

compiler. The value returned from the floor() method is type double,

and the compiler will not cast this to int for you automatically because

the process potentially loses information.

14. Finally, we get the number of inches by subtracting the value for

whole feet from the original radius, multiplying the fraction of a foot by

12 to get the equivalent inches, and then rounding the result to the

nearest integer using the round() method.

15. Note how we output the result. We specify the combination (or

concatenation) of strings and variables as an argument to the println()

method. The statement is spread over two lines for convenience here.

The \n in the output specifies a newline character, so the output will

be on two lines. Any time you want the next bit of output to begin a

new line, just add \n to the output string. You can't enter a newline

character just by typing it because when you do that the cursor just

moves to the next line. That's why it's specified as \n.

As far as IDE's are concerned, we will switch to JCreator in school.

At home you can use whatever you want: NetBeans, JCreator, or even

Eclipse for that matter.

 

These 4 programs, numbered 3_1,  3_2,  3_3,  and 3_4  will be

the basis for our work as we complete Ch.3.

/* This is Program 3_1 Greeter*/

public class Hello
{
public static void main (String[] args)
      {
            System.out.println("Hello World");

/* You supply the rest of the code*/
       }
}

 

//Program3_2

public class Hellosum
{
public static void main (String[] args)
{
System.out.println("Hello World");
int sum;
sum = 2000 + 4;
System.out.println("Did you know that the sum of 2000 and 4 is " + sum + "?");
}
}

 

//Program3_3

import javax.swing.JOptionPane;
public class EvenOdd
{
public static void main (String[] args)
{
String numStr, result;
int num, again;
do
{
numStr = JOptionPane.showInputDialog ("Enter an integer: ");
num = Integer.parseInt(numStr);
result = "That number is " + ((num%2 == 0) ? "even" : "odd");
JOptionPane.showMessageDialog (null, result);
again = JOptionPane.showConfirmDialog (null, "Do Another?");
}
while (again == JOptionPane.YES_OPTION);
}
}

 

//Program3_4

// Add 2 numbers and display the sum

public class Addition {
//main(): application entry point
public static void main(String[] args) {
//declare variables x,y
int x = 2;
int y = 3;
//add x,y to get sum
int sum = x + y;
//Display x,y,sum
System.out.println("First Number to Add: " + x);
System.out.println("Second Number to Add: " + y);
System.out.println("Sum of Both Numbers: " + sum);
}//ends main
}//ends addition

 

 

 

 

Click Round_1 and Round_2 for your programming assignments.

Anti-Phishing Game.

 

animated open door gifARCHIVES:   CH.1  

JAVA RESOURCES and WEBSITES TO VISIT:

Prime Numbers

Review of Java

Elements of Java

Honda ASIMO

System.currentTimeMillis()

Space Invaders 25th Anniversary