Download Introduction to Java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Finally! …a taste of Java!
• History
– 1991 - James Gosling, Sun Microsystems, Inc.
• originally a language for programming home
appliances
– later (1994) used for World Wide Web
applications (since byte code can be downloaded
and run without compiling it)
• Eventually used as a general-purpose programming
language (for the same reason as above plus it is
object-oriented)
1
Three Elements of Java
1. The Java Runtime Environment (JRE)
• Needed to run Java programs
• Most internet browsers now include the JRE.
• If you are going to use Java programs (as opposed
to creating them), this is all you need.
2. The Java programming language
• The language used to create programs.
3. The Java Application Programmer’s Interface (API)
• A (large) collection of pre-written programs in
the software development kit (SDK) that can be
used by your Java programs.
• The “interface” describes how to connect your
programs with the ones in the SDK.
2
Translation of Java to machine code
• A two step process
• Step 1: Compile source code to Java “byte code”.
– “Byte code” is a standard intermediate-level
language.
– Input: Java code in one or more files ending in
.java
– Output: Byte code in one or more files ending in
.class
• Step 2: Interpret Java byte code on a particular
machine
– The interpreter converts each byte code
statement to the specific type of machine code
and then runs that machine code.
3
Why 2 steps?
• Byte code is standard, so you can compile Java programs on any
machine, and run them on any other machine that has a Java
interpreter.
– This means that .class files can be downloaded from the
Internet and run locally.
– Only the original program developer needs a compiler and the
software development kit.
– Avoids having to re-compile the program for every
combination of hardware and operating system.
• The Java interpreter is called a “Virtual Machine” and is part of
the Java Runtime Environment.
– Java virtual machines are specific to one type of computer
and operating system.
– Most internet browsers now include a Java virtual machine.
4
Compile
Java
Source Code
(.java)
Java
Compiler
Run
Java
Byte Code
(.class)
Download
(optional)
.class
.class
Java Virtual
Machine A
Java Virtual
Machine B
(Machine
Code A)
(Machine
Code B)
5
Our First Java Program
• Let’s write a Java program to print
Hello, world!
on the screen
6
Our First Java Program
• Code to begin and end your program:
– (to be explained later)
public class Hello
{
public static void main( String[ ] args )
{
System.out.println( "Hello, world!" );
}
}
7
Java Program Structure
• All Java code must be part of a “class”, and a Java program is
structured as a set of classes.
• Every class has a name:
public class Hello
{
}
• Braces { and } are used to mark the start and end of the class.
• Other class information may also appear with the name:
– A “public” class is one that can be referred to by other
classes.
8
Comments
• Programmers use comments in their code to provide
information to the reader on what the code is doing.
• When a program is compiled, the compiler skips all
comments.
• It is common (and good) practice to use a comment at
the top of the code containing general information
about the file (known as a header).
9
Code Comments
• Single line comment
– Everything from // to the end of the line is the comment
some code // This is a comment
more code
• General comment
– Everything from /* to the next occurrence of */ is a
comment
– Can be part of a line code /* comment */ more code
– Can be several lines
code /* start of comment
more comment
end of comment */ more code
10
Sample Program Header
/**
* Hello.java
* Author
Brigitte Helen Boudreau
* Student ID
123456
*
This program is a simple program that displays
*
Hello, world!
*
* Modifications
*
08/09/2003
BHB
first created
*
25/08/2004
AWW
modified slightly
*/
11
Components of Classes
• Inside a class, there can be
– “attributes”: they store some information
– “methods”: they do some work.
• In our first program, we have zero attributes and one method.
• Each method has 2 parts: a header, and a body.
– The header contains the name and other information about
the method.
• A user of the method needs to know this information.
– The body describes what the method should do.
• Braces { and } are used to mark the start and end of the
method body.
12
Methods
• In our first program, we have one method.
public static void main(String[ ] args) // header
{
System.out.println( "Hello, world!" );
}
– The name of the method is main
• main is a special name: it means “when you run the
program, start here.”
– Other information in the method header will be explained
later; for now, every main method should have this exact
header.
– A method body consists of a set of statements.
• Each statement is terminated by a semi-colon ;
• Our main method has only one statement.
13
Statements
• Our first Java program has one statement:
System.out.println( "Hello, world!" );
• Whatever is between the double quotes will appear on the
screen, and then the output will move to the next line of the
screen.
• System is the name of a special class that comes with Java
– The . operator asks to go inside a class to an attribute or
method.
– The above asks to start the println method contained in
the out attribute of the System class.
– The information between quotes is passed to the println
method.
– On any computer with a Java virtual machine, the System
class keeps track of machine-specific information (such as
how to get information onto the screen).
14
Data in Java
• Java is a “typed” language:
– Every data value must have a type
– The type gives rules for what values are allowed,
and what operations can be done with the values.
• For the computer, values of a certain type usually
take a known amount of storage space in memory.
15
Java Primitive data types
• A data item has a PRIMITIVE type if it represents a
single value, which cannot be decomposed.
• Java has a number of pre-defined primitive data
types. In this course, we will use the following types:
int
represents integers (e.g. 3)
long
represents large integers
double
represents “real” numbers (e.g. 3.0)
char
represents single characters
boolean
represents Boolean (logical) values
16
Variables
• To store a value, we use a variable – a name referring
to the location in which the value is stored.
• Variables must be declared before they can be used.
• A variable declaration has three parts:
– The type of the variable
– The name of the variable
– (Optional) Assign an initial value to the variable.
• Example: int x = 3;
17
Assigning Values
• The equals sign = is used to represent assigning a
value to a variable.
• General form: <variable name> = <expression> ;
• In an assignment statement:
– The expression to the right of = is evaluated.
– The value is put in the memory location
represented by the variable name.
– Whatever value was previously associated with the
variable is replaced (lost).
• Example (assume x and y are declared previously):
x = 3 + y;
18
The Boolean Type
• A Boolean variable is one which can have only 2
possible values: true or false. (These are not
numbers.)
• Boolean variables are used when you need to do logical
tests
– Example “Is X greater than 3?” x > 3
• Boolean operators:
– and (represented by && in Java)
– or (represented by || in Java)
– not (represented by ! in Java)
19
Truth Tables
• A TRUTH TABLE for a compound Boolean expression
shows the results for all possible combinations of the
simple expressions:
X
Y
true
true
true
false
false
true
false
false
X AND Y
x && y
X OR Y
x || y
NOT X
! x
20
Type int
• A variable of type int may take values from
–2147483648 to 2147483647.
– Exceeding the range of legal values results in OVERFLOW, a
run-time error.
• The following operators are available for type int :
+ (addition)
– (subtraction, negation)
* (multiplication)
/ (integer division, where fraction is lost; result is an int)
Example: 7 / 3 = 2
% (remainder from division)
Example: 7 % 3 = 1
== != > < >= <= (comparisons: these take two
values of type int and return a
boolean value)
21
Type long
• A variable of type long may take values from
–9223372036854775808L to
9223372036854775807L.
• To indicate the difference between an int constant
and a long constant, the character L is appended
– Example
– 1 is of type int
– 1L is of type long
• Values of type long take up twice as much memory as
values of type int.
22
Type double (Literals)
•
Type double represents “real” numbers approximately from
-1.7  10308 to 1.7  10308 with 15 accurate significant digits.
– While there are a lot of double values, the set of legal double
values is still finite, and so they are only an approximation to real
numbers.
– After a computation, the computer has to choose the closest
double value to a real result: this can introduce “round-off”
errors.
•
Format of large or small values:
12345600000000000.0 = 0.123456  1017 is 0.123456e17
0.00000123456 = 0.123456  10-5 is 0.123456e-5
•
If the value of e is more negative than about -308, the result is
UNDERFLOW, and the value will be replaced by zero. This happens
quietly, and is not a run-time error.
23
Type double (Operators)
• The following operators are available for type double :
+ (addition)
– (subtraction, negation)
* (multiplication)
/ (division in “real” numbers, result is a double)
> < (comparisons: these take two values of
type double and return a boolean value)
• WARNING: Using == (or != >= <=) to compare two values of
type double is legal, but NOT recommended, because of the
potential for round-off errors.
– Later on, we will see a safe way to do this.
24
Type char
• Characters are individual symbols, enclosed in single
quotes
• Examples
– letters of the alphabet (upper and lower case are
distinct) 'A', 'a'
– punctuation symbol (e.g. comma, period, question
mark)
– single blank space
– parentheses '(',')'; brackets '[',']';
braces '{','}'
– single digit ('0', '1', … '9')
– special characters such as '@', '$', '*', and so
on.
25
Special characters
• Some characters are treated specially because they cannot be
typed easily, or have other interpretations in Java.
– new-line character '\n'
– tab character '\t'
– single quote character '\''
– double quote character '\"'
– backslash character '\\'
• All of the above are single characters, even though they appear
as two characters between the quotes.
• The backslash is used as an escape character: it signifies that
the next character is not to have its “usual” meaning.
26
Strings (1)
• A STRING is a collection of characters.
– There is NO primitive data type in Java for a string.
• We will see later how to deal with strings in general.
• String literals (constants) can be used to help make your
program output more readable.
– String literals are enclosed in double quotes:
"This is a string”
• Watch out for:
– "a" (a string) versus 'a' (a character)
– " " (a string literal with a blank that has length 1) versus
"" (an empty string: a string literal of length 0)
– "257" (a string) versus 257 (an integer)
27
String Concatenation
• Strings can be CONCATENATED (joined) using the +
operator:
– "My name is" + "Alan" gives
"My name isAlan"
• String values can also be concatenated to values of
other types with the + operator.
– "The speed is " + 15.5 gives
"The speed is 15.5"
– Because one of the values for the + operator is a
string , the double is temporarily converted to a
string value "15.5" before doing the
concatenation.
28
Precedence of Operators
• Operators are evaluated left-to-right, with the following
precedence (all operators on the same line are treated equally):
() (expression) [] (array subscript) . (object member)
+ – (to indicate positive or negative values) ! (not)
* / %
+ - (for addition or subtraction of two values, concatenation)
< > >= <=
== !=
&&
||
= (assignment to variable)
29
Operator Precedence
• What is the order of evaluation in the following
expressions?
a + b + c + d + e
a + b * c - d / e
a / (b + c) - d % e
a / (b * (c + (d - e)))
30
The Math class
• The Java class Math provides constants and methods for
common mathematical functions (see text page 43):
Math.PI
the value of 
Math.E
the value of e
Math.abs(x)
absolute value
Math.sin(x)
sine x in radians (also cos, tan)
Math.asin(x)
arcsine (also acos, atan)
Math.log(x)
natural logarithm, x > 0
Math.exp(x)
ex
Math.pow(x,y)
xy
Math.sqrt(x)
square root
Math.floor(x)
next lower integer
Math.ceil(x)
next higher integer
Math.round(x)
closest integer
31
Random Numbers
• Random numbers are often needed for:
– simulations
– games
• The method Math.random() returns a random number x of
type double such that 0 ≤ x < 1.
• Repeated calls will produce a uniform distribution
– that is, the probability that any particular number will be
returned is exactly the same as any other number.
• To adjust the range of random numbers:
y = Math.floor(Math.random() * 5) + 1;
y will be an integer such that 1 ≤ y ≤ 5
32
Console Input and Output
• We have already seen how to print a value on the
screen:
System.out.println( aValue );
• Reading information from the keyboard is not
straightforward in Java
– What you type is treated as a collection of
characters, even if you want to enter a number.
– We have to read an entire line at once, and then
convert the characters to whatever data type is
needed.
33
Java Output methods
• There are two useful Java methods from the class
System:
System.out.println( aValue )
System.out.print( aValue )
– Method println() will append a new-line
character to the output, while print() does not.
• These methods are unusual in that the type of
aValue does not matter.
• Method println() with no parameters can be used
to print a blank line.
34
Java Input
• If one were to use Java’s input methods directly (see
text, section 2.8), the following is needed:
– At the start of the program, create a “buffered
reader”
– Whenever you want to read some input:
• Read a line of characters from the keyboard
• PARSE the input
– For example, if you are expecting the user to enter a
value for type double, parsing checks that the
characters that have been entered form a valid
double.
35
Simplified Keyboard Input
• To simplify your code, a class called Keyboard is
provided. You can download it from the course
website.
• In your assignments and labs, include this file, called
Keyboard.java, in the same directory as your
program. Then you may call the methods in this class
to read a value (or values) from the keyboard.
36
Methods in class Keyboard
• Here are some of the methods available in the class Keyboard.
• Keyboard.readInt()
– Reads a single integer value of type int
• Keyboard.readLong()
• Keyboard.readDouble()
• Keyboard.readChar()
– Read a single character from the keyboard.
• Keyboard.readString()
– Read all characters typed before the user hits ‘enter’
• Keyboard.readBoolean()
– Type the word true or false (no quotes) on the keyboard
and the appropriate boolean value will be created.
37
Examples of using Keyboard
int x = Keyboard.readInt( );
• If you type 123 and press ENTER, x will have the
value 123 .
• Method readDouble works the same way.
boolean b = Keyboard.readBoolean( );
• If you type false and press ENTER, b will have the
value false.
long x = Keyboard.readInt( );
• If you type 123 and press ENTER, x will have the
value of a long integer 123L.
38
What happens if the user
types the wrong value?
• If you use Keyboard.readInt(), you are expecting
the user to type a set of characters that form a legal
integer in the proper range for an int variable.
• If the user types something else:
– A “default value” will be returned that will match
the type of the variable
• false for a boolean
• the lowest possible integer
• a special “not a number” floating point value
• Later on, we will see how to check user input in our
programs.
39
Input and Output Prompts
• When the user is being asked to enter something
from the keyboard, your program should always print
a message first to tell the user what to enter.
• Example:
int x;
System.out.println(“Enter an integer from 0 to 3:”);
x = Keyboard.readInt();
• Likewise, when your program prints a value, there
should be a prompt to explain what the value is:
• Example:
System.out.println(“You typed:” + x );
40
Problem Solving
• We now have enough tools to start solving some
problems.
• For any problem, BEFORE you start writing a
program, determine:
– What are the input values that are needed from
the user?
– What results (outputs) do we need to determine?
– What other values are needed?
• math constants: , e, etc.
• physical constants
– What temporary values might need to be
calculated?
– How do we calculate the results?
41
Example 1
•
Calculate the area of a circle from its radius
• what input values do we need?
• what other values do we need?
• what is our output?
• how do we calculate the result?
42
Example 2
• Calculate the distance travelled by an object under
constant acceleration, given a specified time.
– What input values do we need?
– What other values do we need?
– What is the result?
– How do we calculate the result?
43
Example 3:
• Carbon-14 dating
– General radioactive decay equation:
• Q0: initial quantity of radioactive substance
• Q(t): quantity of radioactive substance at time t (in years)
• : radioactive decay constant for a specific element
• Q(t) = Q0e–t is the rate of decay equation
– Carbon-14 is continuously taken in by a living organism, and
the amount of material at death is assumed to be known.
– Once the intake stops, the carbon-14 decays at the above
rate, where  = 0.00012097 / year
– Measure the percentage of carbon-14 remaining
44
Example 3 continued:
• Solve for t to determine the age:
t decay
1
Q
  log

Q0
• Another useful thing to know: if half of the Carbon14 remains, the sample is about 5730 years old.
• Create a Java program to determine the age:
– what are the inputs?
– what are the outputs?
– what other values do we need?
– how do we calculate the formula?
45