CSC 211
CSC 211
USING JAVA
LECTURE NOTE (PART 1)
Environment Setup
This section guides you on how to download and set up Java on your machine. Following are the
steps to set up the environment.
To write your Java programs, you will need a text editor. There are even more sophisticated IDEs
available. But for now, you can consider one of the following:
Notepad: On Windows machine, you can use any simple text editor like Notepad
(Recommended), TextPad.
Netbeans: A Java IDE that is open-source and free, which can be downloaded
from http://www.netbeans.org/index.html.
Eclipse: A Java IDE developed by the eclipse open-source community and can be
downloaded from http://www.eclipse.org
The first time through, each of these steps will probably take you a few tries to get right. I won’t go
into the details here of how you do each of these steps; it depends on the particular computer and
Java programming environment that you are using. But in general, you will type the program using
some sort of text editor and save the program in a file. Then, you will use some command to try to
compile the file. You’ll either get a message that the program contains syntax errors, or you’ll get a
compiled version of the program. In the case of Java, the program is compiled into Java bytecode,
not into machine language. Finally, you can run the compiled program by giving some appropriate
command. For Java, you will actually use an interpreter to execute the Java bytecode. Your
programming environment might automate some of the steps for you—for example, the
compilation step is often done automatically—but you can be sure that the same three steps are
being done in the background.
Here is a Java program to display the message “Hello World!”. Don’t expect to understand what’s
going on here just yet; some of it you won’t really understand until a few chapters from now:
System.out.println("Hello World!");
This command is an example of a subroutine call statement. It uses a “built-in subroutine” named
System.out.println to do the actual work. Recall that a subroutine consists of the instructions
for performing some task, chunked together and given a name. That name can be used to “call” the
subroutine whenever that task needs to be performed. A built-in subroutine is one that is already
defined as part of the language and therefore automatically available for use in any program. When
you run this program, the message “Hello World!” (without the quotes) will be displayed on
standard output. Unfortunately, I can’t say exactly what that means! Java is meant to run on many
different platforms, and standard output will mean different things on different platforms. However,
you can expect the message to show up in some convenient or inconvenient place. (If you use a
command-line interface, like that in Oracle’s Java Development Kit, you type in a command to tell
the computer to run the program. The computer will type the output from the program, Hello
World!, on the next line. In an integrated development environment such as Eclipse, the output
might appear somewhere in one of the environment’s windows.)
You must be curious about all the other stuff in the above program. Part of it consists of comments.
Comments in a program are entirely ignored by the computer; they are there for human readers
only. This doesn’t mean that they are unimportant. Programs are meant to be read by people as well
as by computers, and without comments, a program can be very difficult to understand. Java has
two types of comments. The first type begins with // and extends to the end of a line. There is a
comment of this form on the last line of the above program. The computer ignores the // and
everything that follows it on the same line. The second type of comment starts with /* and ends
with */, and it can extend over more than one line. The first three lines of the program are an
example of this second type of comment.
Everything else in the program is required by the rules of Java syntax. All programming in Java is
done inside “classes.” The first line in the above program (not counting the comment) says that this
is a class named HelloWorld. “HelloWorld,” the name of the class, also serves as the name of the
program. Not every class is a program. In order to define a program, a class must include a
subroutine named main, with a definition that takes the form:
When you tell the Java interpreter to run the program, the interpreter calls this main() subroutine,
and the statements that it contains are executed. These statements make up the script that tells the
computer exactly what to do when the program is executed. The main() routine can call other
Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps:
Open notepad and add the code as above.
Save the file as: HelloWorld.java.
Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\.
Type 'javac HelloWorld.java' and press enter to compile your code. If there are no errors in
your code, the command prompt will take you to the next line (Assumption : The path
variable is set).
No spaces are allowed in identifiers; HelloWorld is a legal identifier, but “Hello World” is not. Upper
case and lower case letters are considered to be different, so that HelloWorld, helloworld,
HELLOWORLD, and hElloWorLD are all distinct names.
Certain words are reserved for special uses in Java, and cannot be used as identifiers. These reserved
words include: class, public, static, if, else, while, and several dozen other words. (Remember that
reserved words are not identifiers, since they can’t be used as names for things.)
Java is actually pretty liberal about what counts as a letter or a digit. Java uses the Unicode character
set, which includes thousands of characters from many different languages and different alphabets,
and many of these characters count as letters or digits. However, I will be sticking to what can be
typed on a regular English keyboard.
The pragmatics of naming includes style guidelines about how to choose names for things. For
example, it is customary for names of classes to begin with upper case letters, while names of
variables and of subroutines begin with lower case letters; you can avoid a lot of confusion by
following this standard convention in your own programs. Most Java programmers do not use
underscores in names, although some do use them at the beginning of the names of certain kinds of
variables. When a name is made up of several words, such as HelloWorld or interestRate, it is
customary to capitalize each word, except possibly the first; this is sometimes referred to as camel
case, since the upper case letters in the middle of a name are supposed to look something like the
humps on a camel’s back.
Finally, I’ll note that in addition to simple identifiers, things in Java can have compound names which
consist of several simple names separated by periods. (Compound names are also called qualified
names.) You’ve already seen an example: System.out.println. The idea here is that things in Java can
contain other things. A compound name is a kind of path to an item through one or more levels of
containment. The name System.out.println indicates that something called “System” contains
something called “out” which in turn contains something called “println”.
<variable> = <expression>;
where <expression> represents anything that refers to or computes a data value. When the
computer comes to an assignment statement in the course of executing a program, it evaluates the
expression and puts the resulting data value into the variable. For example, consider the simple
assignment statement
rate = 0.07;
The <variable> in this assignment statement is rate, and the <expression> is the number 0.07.
The computer executes this assignment statement by putting the number 0.07 in the variable rate,
replacing whatever was there before. Now, consider the following more complicated assignment
statement, which might come later in the same program:
Here, the value of the expression “rate * principal” is being assigned to the variable interest. In the
expression, the * is a “multiplication operator” that tells the computer to multiply rate times
principal. The names rate and principal are themselves variables, and it is really the values stored in
those variables that are to be multiplied. We see that when a variable is used in an expression, it is
the value stored in the variable that matters; in this case, the variable seems to refer to the data in
the box, rather than to the box itself. When the computer executes this assignment statement, it
takes the value of rate, multiplies it by the value of principal, and stores the answer in the box
referred to by interest. When a variable is used on the left-hand side of an assignment statement, it
refers to the box that is named by the variable.
(Note, by the way, that an assignment statement is a command that is executed by the computer at
a certain time. It is not a statement of fact. For example, suppose a program includes the statement
Data Types
A variable in Java is designed to hold only one particular type of data; it can legally hold that type of
data and no other. The compiler will consider it to be a syntax error if you try to violate this rule by
assigning a variable of the wrong type to a variable. We say that Java is a strongly typed language
because it enforces this rule.
There are eight so-called primitive types built into Java. The primitive types are named byte, short,
int, long, float, double, char, and boolean. The first four types hold integers (whole numbers such as
17, -38477, and 0). The four integer types are distinguished by the ranges of integers they can hold.
The float and double types hold real numbers (such as 3.6 and -145.99). Again, the two real types
are distinguished by their range and accuracy. A variable of type char holds a single character from
the Unicode character set. And a variable of type boolean holds one of the two logical values true or
false.
Any data value stored in the computer’s memory must be represented as a binary number, that is as
a string of zeros and ones. A single zero or one is called a bit. A string of eight bits is called a byte.
Memory is usually measured in terms of bytes. Not surprisingly, the byte data type refers to a single
byte of memory. A variable of type byte holds a string of eight bits, which can represent any of the
integers between -128 and 127, inclusive. (There are 256 integers in that range; eight bits can
represent 256—two raised to the power eight—different values.) As for the other integer types,
• short corresponds to two bytes (16 bits). Variables of type short have values in the range
-32768 to 32767.
• int corresponds to four bytes (32 bits). Variables of type int have values in the range
-2147483648 to 2147483647.
• long corresponds to eight bytes (64 bits). Variables of type long have values in the range
-9223372036854775808 to 9223372036854775807.
You don’t have to remember these numbers, but they do give you some idea of the size of integers
that you can work with. Usually, for representing integer data you should just stick to the int data
type, which is good enough for most purposes.
The float data type is represented in four bytes of memory, using a standard method for encoding
real numbers. The maximum value for a float is about 10 raised to the power 38.
A float can have about 7 significant digits. (So that 32.3989231134 and 32.3989234399 would both
have to be rounded off to about 32.398923 in order to be stored in a variable of type float.) A
double takes up 8 bytes, can range up to about 10 to the power 308, and has about 15 significant
digits. Ordinarily, you should stick to the double type for real values.
A variable of type char occupies two bytes in memory. The value of a char variable is a single
character such as A, *, x, or a space character. The value can also be a special character such a tab or
a carriage return or one of the many Unicode characters that come from different languages. Values
of type char are closely related to integer values, since a character is actually stored as a 16-bit
Literals
A data value is stored in the computer as a sequence of bits. In the computer’s memory, it doesn’t
look anything like a value written on this page. You need a way to include constant values in the
programs that you write. In a program, you represent constant values as literals.
A literal is something that you can type in a program to represent a value. It is a kind of name
for a constant value. For example, to type a value of type char in a program, you must surround it
with a pair of single quote marks, such as ’A’, ’*’, or ’x’. The character and the quote marks make up
a literal of type char. Without the quotes, A would be an identifier and * would be a multiplication
operator. The quotes are not part of the value and are not stored in the variable; they are just a
convention for naming a particular character constant in a program. If you want to store the
character A in a variable ch of type char, you could do so with the assignment statement
ch = ’A’;
Certain special characters have special literals that use a backslash, \, as an “escape character”.
In particular, a tab is represented as ’\t’, a carriage return as ’\r’, a linefeed as ’\n’, the single quote
character as ’\’’, and the backslash itself as ’\\’. Note that even though you type two characters
between the quotes in ’\t’, the value represented by this literal is a single tab character.
Numeric literals are a little more complicated than you might expect. Of course, there are the
obvious literals such as 317 and 17.42. But there are other possibilities for expressing numbers in a
Java program. First of all, real numbers can be represented in an exponential form such as 1.3e12 or
12.3737e-108. The “e12” and “e-108” represent powers of 10, so that 1.3e12 means 1.3 times 1012
and 12.3737e-108 means 12.3737 times 10−108. This format can be used to express very large and
very small numbers. Any numeric literal that contains a decimal point or exponential is a literal of
type double. To make a literal of type float, you have to append an “F” or “f” to the end of the
number. For example, “1.2F” stands for 1.2 considered as a value of type float. (Occasionally, you
need to know this because the rules of Java say that you can’t assign a value of type double to a
variable of type float, so you might be confronted with a ridiculous-seeming error message if you try
to do something like “x = 1.2;” if x is a variable of type float. You have to say “x = 1.2F;". This is one
reason why I advise sticking to type double for real numbers.)
Even for integer literals, there are some complications. Ordinary integers such as 177777 and -32 are
literals of type byte, short, or int, depending on their size. You can make a literal of type long by
adding “L” as a suffix. For example: 17L or 728476874368L. As another complication, Java allows
binary, octal (base-8), and hexadecimal (base-16) literals. I don’t want to cover number bases in
detail, but in case you run into them in other people’s programs, it’s worth knowing a few things:
is a boolean-valued expression that evaluates to true if the value of the variable rate is greater than
0.05, and to false if the value of rate is not greater than 0.05. As you’ll see in in the subsequent
chapters, boolean-valued expressions are used extensively in control structures. Of course, boolean
values can also be assigned to variables of type boolean. For example, if test is a variable of type
boolean, then both of the following assignment statements are legal:
test = true;
test = rate > 0.05;
with a linefeed at the end, you would have to type the string literal:
You can also use \t, \r, \\, and Unicode sequences such as \u00E9 to represent other special
characters in string literals.
Variables in Programs
A variable can be used in a program only if it has first been declared. A variable declaration
statement is used to declare one or more variables and to give them names. When the computer
executes a variable declaration, it sets aside memory for the variable and associates the variable’s
name with that memory. A simple variable declaration takes the form:
<type-name> <variable-name-or-names>;
The <variable-name-or-names> can be a single variable name or a list of variable names separated
by commas. (We’ll see later that variable declaration statements can actually be somewhat more
complicated than this.) Good programming style is to declare only one variable in a declaration
statement, unless the variables are closely related in some way. For example:
int numberOfStudents;
String name;
double x, y;
boolean isFinished;
char firstInitial, middleInitial, lastInitial;
It is also good style to include a comment with each variable declaration to explain its purpose in the
program, or to give other information that might be useful to a human reader.
For example:
In this chapter, we will only use variables declared inside the main() subroutine of a program.
Variables declared inside a subroutine are called local variables for that subroutine. They exist only
inside the subroutine, while it is running, and are completely inaccessible from outside. Variable
declarations can occur anywhere inside the subroutine, as long as each variable is declared before it
is used in any way. Some people like to declare all the variables at the beginning of the subroutine.
/*
* This class implements a simple program that
* will compute the amount of interest that is
* earned on N17,000 invested at an interest
* rate of 0.027 for one year. The interest and
* the value of the investment after one year are
* printed to standard output.
*/
public class Interest {
public static void main(String[] args) {
/* Declare the variables. */
double principal; // The value of the investment.
double rate; // The annual interest rate.
double interest; // Interest earned in one year.
/* Do the computations. */
principal = 17000;
rate = 0.027;
interest = principal * rate; // Compute the interest.
principal = principal + interest;
// Compute value of investment after one year, with interest.
// (Note: The new value replaces the old value of principal.)
/* Output the results. */
System.out.print("The interest earned is ₦");
System.out.println(interest);
System.out.print("The value of the investment after one year
is ₦");
System.out.println(principal);
} // end of main()
} // end of class Interest
This program uses several subroutine call statements to display information to the user of the
program. Two different subroutines are used: System.out.print and
System.out.println.
The difference between these is that System.out.println adds a linefeed after the end of the
information that it displays, while System.out.print does not. Thus, the value of interest,
which is displayed by the subroutine call “System.out.println(interest);”, follows on
the same line as the string displayed by the previous System.out.print statement. Note that
the value to be displayed by System.out.print or System.out.println is provided in
parentheses after the subroutine name. This value is called a parameter to the subroutine. A
parameter provides a subroutine with information it needs to perform its task. In a subroutine call
statement, any parameters are listed in parentheses after the subroutine name. Not all subroutines
Input.nextDouble()
Input.nextLong()
Input.nextLine()// for reading entire line of input
Input.nextBoolean()// accepts only true or false as input
OPERATORS
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Other Operators
Example
The following simple example program demonstrates the relational operators.
Copy and paste the program in Test.java file and compile and run this program. :
The following table lists the bitwise operators. Assume integer variable A holds 60 and variable B
holds 13 then:
Binary AND Operator copies a bit to the result if it exists (A & B) will give 12
&
in both operands. which is 0000 1100
Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49
^
operand but not both. which is 0011 0001
Example
The following simple example program demonstrates the bitwise operators. Copy and paste the
The following table lists the logical operators. Assume Boolean variables A holds true and variable B
holds false, then:
Example
The following simple example program demonstrates the logical operators. Copy and paste the
following Java program in Test.java file and compile and run this program:
a && b = false
a || b = true
!(a && b) = true
Simple assignment operator, Assigns values from right side C = A + B will assign
=
operands to left side operand value of A + B into C
Add AND assignment operator, It adds right operand to the left C += A is equivalent
+=
operand and assign the result to left operand to C = C + A
C <<= 2 is same as C =
<<= Left shift AND assignment operator
C << 2
C >>= 2 is same as
>>= Right shift AND assignment operator
C = C >> 2
C &= 2 is same as C =
&= Bitwise AND assignment operator
C&2
C ^= 2 is same as C
^= bitwise exclusive OR and assignment operator
=C^2
C |= 2 is same as C
|= bitwise inclusive OR and assignment operator
=C|2
Example
The following simple example program demonstrates the assignment operators.
Copy and paste the following Java program in Test.java file and compile and run this program:
OTHER OPERATORS
There are few other operators supported by Java Language:
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The goal of the operator is to decide which value
should be assigned to the variable. The operator is written as:
EXAMPLE
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
instanceof Operator
NOTE: This is only for documentation purposes. This operator is used only for object reference
variables. The operator checks whether the object is of a particular type(class type or interface type).
The instanceof operator is wriiten as:
If the object referred by the variable on the left side of the operator passes the IS‐A check for the
class/interface type on the right side, then the result will be true. Following is the example:
EXAMPLE
String name = = 'James';
boolean result = name instanceof String;
// This will return true since name is type of String
This operator will still return true if the object being compared is the assignment compatible with
the type on the right. Following is one more example:
EXAMPLE
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}
Example
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
CONTROL STRUCRURES
DECISION MAKING
There are three types of decision making statements in Java. They are:
if .. else tatements
switch statements
if(Boolean_expression){
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
This is if statement
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
Example:
SYNTAX:
The syntax of an if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}
EXAMPLE:
public class Test {
public static void main(String args[]){
int x = 30;
SYNTAX:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
EXAMPLE:
SYNTAX:
The syntax is:
switch(expression){
case value1 :
//Statements
break; //optional
case value2 :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
LOOPS
There may be a situation when we need to execute a block of code several number of times, and is
often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays and we will not
explain it.
while Loop
A while loop is a control structure that allows you to repeat a task a certain number of times.
SYNTAX:
The syntax of a while loop is:
while(Boolean_expression)
do … while Loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
SYNTAX:
The syntax of a do...while loop is:
do
{
//Statements
} while(Boolean_expression);
EXAMPLE:
for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
SYNTAX:
The syntax of a for loop is:
EXAMPLE:
SYNTAX:
The syntax of a break is a single statement inside any loop:
break;
EXAMPLE:
public class Test {
public static void main(String args[]) {
int x;
for(x=0; x<=50; x++ ) {
if( x == 3 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
SYNTAX:
The syntax of a continue is a single statement inside any loop:
continue;
EXAMPLE:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
SUBROUTINES
One way to break up a complex program into manageable pieces is to use subroutines. A subroutine
consists of the instructions for carrying out a certain task, grouped together and given a name.
Elsewhere in the program, that name can be used as a stand-in for the whole set of instructions. As a
computer executes a program, whenever it encounters a subroutine name, it executes all the
instructions necessary to carry out the task associated with that subroutine.
Subroutines can be used over and over, at different places in the program. A subroutine can even be
used inside another subroutine. This allows you to write simple subroutines and then use them to
help write more complex subroutines, which can then be used in turn in other subroutines. In this
way, very complex programs can be built up step-by-step, where each step in the construction is
reasonably simple. Subroutines in Java can be either static or non-static.
Subroutine Definitions
A subroutine must be defined somewhere. The definition has to include the name of the subroutine,
enough information to make it possible to call the subroutine, and the code that will be executed
each time the subroutine is called. A subroutine definition in Java takes the form:
The <statements> between the braces, { and }, in a subroutine definition make up the body of the
subroutine. These statements are the inside, or implementation part of the subroutine. They are the
instructions that the computer executes when the method is called.
The <modifiers> that can occur at the beginning of a subroutine definition are words that set certain
characteristics of the subroutine, such as whether it is static or not. The modifiers that you’ve seen
so far are “static” and “public”. There are only about a half-dozen possible modifiers altogether.
If the subroutine is a function, whose job is to compute some value, then the <return-type> is used
to specify the type of value that is returned by the function. It can be a type name such as String or
int or even an array type such as double[ ]. If the subroutine is not a function, then the <return-type>
return area;
}
return circumference;
}
A class can include other things besides subroutines. In particular, it can also include variable
declarations. Of course, you can declare variables inside subroutines. Those are called local
variables. However, you can also have variables that are not part of any subroutine. To distinguish
such variables from local variables, we call them member variables, since they are members of a
Example
Consider the class BankingSystem which implements some of the basic banking transactions like
withdrawal, deposit, and checking balance.
import java.util.*;
public class BankingSystem{
switch(response){
case 1:
System.out.println("Enter the amount to
withdraw: ");
amount = input.nextDouble();
withdraw(amount);
break;
case 2:
System.out.println("Enter the amount to
deposit: ");
amount = input.nextDouble();
deposit(amount);
break;
case 3:
showBalance();
break;
default:
System.out.println("Invalid input");
}
}
Built-in Subroutines
Recall that a subroutine is a set of program instructions that have been chunked together and
given a name. A subroutine is designed to perform some task. To get that task performed in a
program, you can “call” the subroutine using a subroutine call statement. In the previous lectures,
you learned how to write your own subroutines, but you can get a lot done in a program just by
calling subroutines that have already been written for you. In Java, every subroutine is contained
either in a class or in an object. Some classes that are standard parts of the Java language contain
predefined subroutines that you can use. A value of type String, which is an object, contains
subroutines that can be used to manipulate that string. These subroutines are “built into” the Java
language. You can call all these subroutines without understanding how they were written or how
they work. Indeed, that’s the whole point of subroutines: A subroutine is a “black box” which can be
used without knowing what goes on inside.
Let’s first consider subroutines that are part of a class. One of the purposes of a class is to group
together some variables and subroutines, which are contained in that class. These variables and
subroutines are called static members of the class. You’ve seen one example: In a class that defines a
program, the main() routine is a static member of the class. The parts of a class definition that
define static members are marked with the reserved word “static”, such as the word “static” in
public static void main...
When a class contains a static variable or subroutine, the name of the class is part of the full name of
the variable or subroutine. For example, the standard class named System contains a subroutine
named exit. To use that subroutine in your program, you must refer to it as System.exit. This full
name consists of the name of the class that contains the subroutine, followed by a period, followed
by the name of the subroutine. This subroutine requires an integer as parameter, so you would
actually use it with a subroutine call statement such as System.exit(0); Calling
System.exit will terminate the program and shut down the Java Virtual Machine. You could use
it if you had some reason to terminate the program before the end of the main routine. (The
parameter tells the computer why the program was terminated. A parameter value of 0 indicates
that the program ended normally. Any other value indicates that the program was terminated
because an error was detected, so you could call System.exit(1) to indicate that the program is
ending because of an error. The parameter is sent back to the operating system; in practice, the
value is usually ignored by the operating system.)
System is just one of many standard classes that come with Java. Another useful class is called
Math. This class gives us an example of a class that contains static variables: It includes the variables
Math.PI and Math.E whose values are the mathematical constants π and e. Math also contains a
large number of mathematical “functions.” Every subroutine performs some specific task. For some
subroutines, that task is to compute or retrieve some data value. Subroutines of this type are called
functions. We say that a function returns a value. Generally, the returned value is meant to be used
somehow in the program that calls the function.
You are familiar with the mathematical function that computes the square root of a number. The
corresponding function in Java is called Math.sqrt. This function is a static member subroutine of the
class named Math. If x is any numerical value, then Math.sqrt(x) computes and returns the square
root of that value. Since Math.sqrt(x) represents a value, it doesn’t make sense to put it on a line by
itself in a subroutine call statement such as Math.sqrt(x); // This doesn’t make sense!
or you might use an assignment statement to tell the computer to store that value in a variable:
lengthOfSide = Math.sqrt(x);
The function call Math.sqrt(x) represents a value of type double, and it can be used anyplace
where a numeric literal of type double could be used.
The Math class contains many static member functions. Here is a list of some of the more
important of them:
• The usual trigonometric functions, Math.sin(x), Math.cos(x), and Math.tan(x). (For all the
trigonometric functions, angles are measured in radians, not degrees.)
• The inverse trigonometric functions arcsin, arccos, and arctan, which are written as:
Math.asin(x), Math.acos(x), and Math.atan(x). The return value is expressed in radians, not degrees.
• The exponential function Math.exp(x) for computing the number e raised to the power
x, and the natural logarithm function Math.log(x) for computing the logarithm of x in the base e.
• Math.floor(x), which rounds x down to the nearest integer value that is less than or equal to x.
Even though the return value is mathematically an integer, it is returned as a value of type double,
rather than of type int as you might expect. For example, Math.floor(3.76) is 3.0. The function
Math.round(x) returns the integer that is closest to x, and Math.ceil(x) rounds x up to an integer.
(“Ceil” is short for “ceiling”, the opposite of “floor.”)
• Math.random(), which returns a randomly chosen double in the range 0.0 <= Math.random() < 1.0.
(The computer actually calculates so-called “pseudorandom” numbers, which are not truly random
but are effectively random enough for most purposes.) We will find a lot of uses for Math.random in
future examples.
For these functions, the type of the parameter—the x or y inside the parentheses—can be any value
of any numeric type. For most of the functions, the value returned by the function is of type double
no matter what the type of the parameter. However, for Math.abs(x), the value returned will be the
same type as x; if x is of type int, then so is Math.abs(x). So, for example, while Math.sqrt(9) is the
double value 3.0, Math.abs(9) is the int value 9. Note that Math.random() does not have any
parameter. You still need the parentheses, even though there’s nothing between them. The
parentheses let the computer know that this is a subroutine rather than a variable. Another example
of a subroutine that has no parameters is the function System.currentTimeMillis(), from the System
class. When this function is executed, it retrieves the current time, expressed as the number of
milliseconds that have passed since a standardized base time (the start of the year 1970, if you care).
One millisecond is one thousandth of a second. The return value of System.currentTimeMillis() is of
type long (a 64-bit integer). This function can be used to measure the time that it takes the
computer to perform a task. Just record the time at which the task is begun and the time at which it
is finished and take the difference. Here is a sample program that performs a few mathematical
/*
* This program performs some mathematical computations and displays
the
* results. It also displays the value of the constant Math.PI. It
then
* reports the number of seconds that the computer spent on this
task.
*/
public class TimedComputation {
public static void main(String[] args) {
long startTime; // Starting time of program, in milliseconds.
long endTime; // Time when computations are done, in milliseconds.
double time; // Time difference, in seconds.
startTime = System.currentTimeMillis();
double width, height, hypotenuse; // sides of a triangle
width = 42.0;
height = 17.0;
hypotenuse = Math.sqrt( width*width + height*height );
System.out.print("A triangle with sides 42 and 17 has hypotenuse
");
System.out.println(hypotenuse);
System.out.println("\nMathematically, sin(x)*sin(x) + "
+ "cos(x)*cos(x) - 1 should be 0.");
System.out.println("Let’s check this for x = 1:");
System.out.print(" sin(1)*sin(1) + cos(1)*cos(1) - 1 is ");
System.out.println( Math.sin(1)*Math.sin(1)
+ Math.cos(1)*Math.cos(1) - 1 );
System.out.println("(There can be round-off errors when"
+ " computing with real numbers!)");
System.out.print("\nHere is a random number: ");
System.out.println( Math.random() );
System.out.print("The value of Math.PI is ");
System.out.println( Math.PI );
endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;
System.out.print("\nRun time in seconds was: ");
System.out.println(time);
} // end main()
} // end class TimedComputation