Transcript ppt
Last Time
• How and why java programs run the way they do.
• A quick look and three development
environments.
Winter 2006
CISC121 - Prof. McLeod
1
Stuff…
• CD’s with development tools for loan?
Winter 2006
CISC121 - Prof. McLeod
2
Today
• Simple program structure, or the class as an
object.
• The rest of the slides contain everything you need
to know to build expressions in Java.
– You will need to read whatever slides we
don’t get to on your own!
Winter 2006
CISC121 - Prof. McLeod
3
A Simple Java Program
public class HelloProg
{
public static void main (String [] args)
{
System.out.println ("Hello there!");
} // end main method
} // end HelloProg class
• The “//” denotes an in-line comment. Everything else on
the line is ignored by the compiler.
Winter 2006
CISC121 - Prof. McLeod
4
A Simple Java Program – Cont.
• The compiler ignores any “white space” in your
source code – returns, line feeds, tabs, extra
spaces and comments.
• Here’s our little program without white space
(imagine this all on one line):
public class HelloProg{public static void main(String[]
args){System.out.println("Hello there!");}}
• This does still run, but it is hard to read…
Winter 2006
CISC121 - Prof. McLeod
5
The main Method
• For the runtime engine to run a program, it must
know where to start.
• By design, the starting point is always the
execution of the main method.
• The engine expects the main method to be
declared exactly as shown – the only thing you
can change is the name of the String array, called
“args” in this little program.
Winter 2006
CISC121 - Prof. McLeod
6
A Class is an Object
• An Object is a container that hold attributes (or
“data”) and methods (also called “functions”):
public class MyClass {
attribute
attribute
attribute
method
method
method
method
• No code can exist
outside a class.
• Other than attributes
and methods, the only
thing a class can contain
is another class! (Called
“inner classes”).
} // end class MyClass
Winter 2006
CISC121 - Prof. McLeod
7
Variables
• What is a variable, anyways?
• Variables can be declared as attributes or within
methods.
• Attributes can use some additional declaration
“modifiers”, so let’s look at declaring variables in
methods first!
• Simple variable declaration syntax:
variable_type variable_name;
Winter 2006
CISC121 - Prof. McLeod
8
Variables, Cont.
• variable_type can be an Object or a primitive
type.
• What is a primitive type?
• What’s an Object?
An Object is a Class and a Class is an Object!
Winter 2006
CISC121 - Prof. McLeod
9
Primitive Types
• Unfortunately not everything in Java is an Object.
• Primitive Types are used to declare variables
that will not be Objects either.
• This is done for convenience and more efficient
use of memory.
• Primitive Type variables fall into the categories of
integer types, real types, characters and
booleans.
Winter 2006
CISC121 - Prof. McLeod
10
Integer Primitive Types
• byte, short, int, long
• For byte, from -128 to 127, inclusive (1 byte).
• For short, from -32768 to 32767, inclusive (2
bytes).
• For int, from -2147483648 to 2147483647,
inclusive (4 bytes).
• For long, from -9223372036854775808 to
9223372036854775807, inclusive (8 bytes).
• A “byte” is 8 bits, where a “bit” is either 1 or 0.
Winter 2006
CISC121 - Prof. McLeod
11
Aside - Number Ranges
• Where do these min and max numbers come
from?
• Memory limitations and the system used by Java
(two’s complement) to store numbers determines
the actual numbers.
• The Wrapper classes can be used to provide the
values - for example:
Integer.MAX_VALUE // returns the value 2147483647
• More on these topics later!
Winter 2006
CISC121 - Prof. McLeod
12
Real Primitive Types
• Also called “Floating Point” Types:
• float, double
• For float, (4 bytes) roughly ±1.4 x 10-38 to ±3.4
x 1038 to 7 significant digits.
• For double, (8 bytes) roughly ±4.9 x 10-308 to
±1.7 x 10308 to 15 significant digits.
Winter 2006
CISC121 - Prof. McLeod
13
Character Primitive Type
• char
• from '\u0000' to '\uffff' inclusive, that is,
from 0 to 65535 (base 10) or 0 to ffff (base 16, or
“hexadecimal”). A variable of the “char” type
represents a Unicode character.
• Can also be represented as ‘a’ or ‘8’, etc.
Winter 2006
CISC121 - Prof. McLeod
14
Boolean Primitive Type
• boolean is either true or false.
Winter 2006
CISC121 - Prof. McLeod
15
String Objects
• String’s are not primitive data types, but are
Objects.
• A String can be declared in the same way as a
primitive type using the keyword: String.
Winter 2006
CISC121 - Prof. McLeod
16
Variable Declaration
• Java is a “declarative” language.
• In other words, variables must be declared before they
can be used.
• To declare a variable, use the Java “keyword” appropriate
for the type of variable you are declaring followed by a
variable name you have created, followed by a semicolon.
• Examples:
int aNum;
char aLetter;
double totalVolume;
String userPrompt;
Winter 2006
CISC121 - Prof. McLeod
17
Legal Variable Names
• Java names may contain any number of letters,
numbers and underscore (“_”) characters, but
they must begin with a letter.
• Standard Java Naming Convention:
– Names beginning with lowercase letters are variables
or methods.
– Names beginning with uppercase letters are class
names.
– Successive words within a name are capitalized.
– Names in all capital letters are constants.
• (We’ll get to “constants” shortly).
Winter 2006
CISC121 - Prof. McLeod
18
Literal Values
• Integers, for example:
12
-142
0
333444891
• If you write these kinds of numbers into your
program, Java will assume them to be of type
“int”, and store them accordingly.
• If you want them to be of type “long”, then you
must append a “L” to the number:
43L
Winter 2006
9999983475L
CISC121 - Prof. McLeod
-22233487L
19
Literal Values - Cont.
• Real or “Floating Point” numbers, for example:
4.5
-1.0
3.457E-10
-3.4E45
• These literals will be assumed to be of the
“double” type.
• If you want them to be stored as “float” types,
append an “F”:
3.456F
Winter 2006
5.678E-10F
CISC121 - Prof. McLeod
-321.0F
20
Literal Values - Cont.
• char literals:
‘A’
‘5’
‘\u0032’
• boolean literals:
true
false
• String literals:
“Hello there!”
Winter 2006
“456.7”
CISC121 - Prof. McLeod
“West of North”
21
Variable Declaration - Cont.
• int and double variables initially are given a
value of zero unless they are initialized to a value.
• Java may prevent you from using variables that
are not initialized.
• So, it is sometimes good practice to initialize your
variables before use, for example:
int numDaysInYear = 365;
double avgNumDaysInYear = 365.25;
String greetingLine = “Hello there!”;
long counter = 0;
Winter 2006
CISC121 - Prof. McLeod
22
Variable Declaration - Cont.
• All these statements could be carried out in two
lines, for example:
int numDaysInWeek = 7;
Is the same as:
int numDaysInWeek;
numDaysInWeek = 7;
Winter 2006
CISC121 - Prof. McLeod
23
Constants
• The Java modifier keyword, final can be used
to make sure a variable value is no longer
“variable”.
• It becomes a constant, because Java will not
allow your program to change its value once it has
been declared:
final int NUM_DAYS_IN_YEAR = 365;
final double MM_PER_INCH = 25.4;
Winter 2006
CISC121 - Prof. McLeod
24
Type Casting
• When a value of one type is stored into a variable
of another type.
• Casting in one direction is automatic, you do not
have to deliberately or “explicitly” cast:
• A value to the left can be assigned to a variable to
the right without explicit casting:
byte > short > int > long > float > double
Winter 2006
CISC121 - Prof. McLeod
25
Type Casting - Cont.
• For example in the statement:
double myVar = 3;
the number 3 is automatically cast to a double (3.0) before
it is stored in the variable “myVar”.
• However, if you tried the following:
int anotherVar = 345.892;
the compiler would protest loudly because a double
cannot be stored in an int variable without loss of
precision. Wrong direction!
Winter 2006
CISC121 - Prof. McLeod
26
Type Casting - Cont.
• If you really want to cast in the other direction,
then you must make an explicit cast. For
example:
int anotherVar = (int)345.892;
is legal. The “(int)” part of the statement casts
the double to an int. The variable
anotherVar would hold the value 345
• Note how numbers are truncated, not rounded!
Winter 2006
CISC121 - Prof. McLeod
27
Arithmetic Operators
• The standard binary arithmetic operators in Java are:
– Addition (+)
– Subtraction (-)
– Multiplication (*)
– Division (/)
– Modulus or Remainder (%) (ie. 12 % 5 yields 2)
• All of these operations apply to all numeric primitive data
types.
• All require values on both sides of the operator (why they
are called “binary operators”).
Winter 2006
CISC121 - Prof. McLeod
28
Integer Arithmetic
• Arithmetic operations between integers produce
integer results by truncating the answer —
fractional parts are discarded
• Examples:
3 / 4 stores as 0
4 / 4 stores as 1
5 / 4 stores as 1
• Integer arithmetic is unsuitable for calculations
involving real-world continuous quantities
Winter 2006
CISC121 - Prof. McLeod
29
Real or Floating Point Arithmetic
• Floating-point arithmetic is used with float and
double values. It produces the expected results:
4.0 / 3.0 = 1.3333333333333
• However, these numbers have range and
precision limits:
Type
float
double
Winter 2006
Range
±1038
±10308
Precision
6-7 decimal digits
15-16 decimal digits
CISC121 - Prof. McLeod
30
Mixed Type Arithmetic Expressions
• Suppose you have a “mixed type” expression involving an
arithmetic operator.
• To evaluate the expression, Java will cast one side to
match the other.
• For example if one side is an int and the other side is a
double, the int will be automatically cast to a double
before the operation takes place.
• For example:
9 /
9 /
4 *
4.0
Winter 2006
2 stores as 4
2.0 stores as 4.5
12 stores as 48
* 12 stores as 48.0
CISC121 - Prof. McLeod
31
Strings and the “+” Operator
• Not only can “+” operate on numeric values, but it
can also handle String’s on either or both sides.
• If one side is not a String, it will be changed to
one, and then it will be concatenated to the
String on the other side:
4 + “you” stores as “4you”
“apples” + “oranges” + 9 + 9 stores as
“applesoranges99”
3 + 7 + “little piggies” stores as “10little piggies”
• Expressions are evaluated from left to right,
unless precedence rules apply.
Winter 2006
CISC121 - Prof. McLeod
32
Unary Arithmetic Operators
• Unary operators include “+” and “-”, where “-aNum”
negates the value produced by aNum, for example.
• They also include the increment (++) and decrement (--)
operators which increase or decrease an integer value by
1.
• Preincrement and predecrement operators appear
before a variable. They increment or decrement the value
of the variable before it is used in the expression.
• Example:
int i = 4, j = 2, k;
k = ++i - j;
// i = 5, j = 2, k = 3
Winter 2006
CISC121 - Prof. McLeod
33
Unary Arithmetic Operators - Cont.
• Postincrement and postdecrement operators
appear after a variable. They increment or
decrement the value of the variable after it is used
in the expression.
• Example:
int i = 4, j = 2, k;
k = i++ - j;
// i = 5, j = 2, k = 2
• Keep expressions involving increment and
decrement operators simple!
Winter 2006
CISC121 - Prof. McLeod
34
Assignment Operators
=
*=
/=
-=
+=
Winter 2006
set equal to
multiply and set equal to
divide and set equal to
subtract and set equal to
add and set equal to
CISC121 - Prof. McLeod
35
Assignment Operators - Cont.
• An assignment statement in Java has the form
variableName = expression;
• The expression is evaluated, and the result of the
expression is stored in the specified variable.
• Assignment statements and arithmetic operations can be
combined in a single symbol. For example,
variableName += expression;
is equivalent to
variableName = variableName + expression;
Winter 2006
CISC121 - Prof. McLeod
36
Logical Binary Operators
• Return either true or false.
==
!=
>
<
>=
<=
equals to
not equals to
greater than
less than
greater than or equal to
less than or equal to
&, &&
|, ||
logical “And”
logical “Or”
Winter 2006
CISC121 - Prof. McLeod
37
Aside – “|” or “||”?
• What’s the difference?
• A single “|” or “&” always evaluates both sides of the
expression, whether it is necessary or not.
• “&&” stops if the left side is false, “||” stops if the left side
is true.
• When would this make a difference?
• For example:
int x = 0, y = 4;
boolean test = x != 0 & y / x > 1;
– Gives an error, using “&&” would not. Why?
Winter 2006
CISC121 - Prof. McLeod
38
Logical Operators - Cont.
• The one “unary” logical operator is “!”.
• Called the “Not” operator.
• It reverses the logical value of a boolean.
• For example:
!(5 > 3) evaluates to false
Winter 2006
CISC121 - Prof. McLeod
39
Logical Operators - Cont.
• “Truth” tables for the “And” and “Or” operators:
&&
||
testa
testa
testb true
false
testb true
false
true
false
true
true
true
false false false
Winter 2006
true
false true
CISC121 - Prof. McLeod
false
40
Precedence Rules
• Operator precedence rules determine which operations
take place in what order:
–
–
–
–
–
–
–
Unary operations are done first.
Then *, /, %
Then +, Then <, >, <=, >=
Then ==, !=
Then &, &&, |, ||
Then =, *=, +=, -=, /=
• Use “( )” to control order of operations, as the expression
inside “( )” will be evaluated before stuff outside of “( )”.
Winter 2006
CISC121 - Prof. McLeod
41
Expressions
• Expressions are combinations of variables, literal
values, and operators.
• For example:
int aNum = 4 + 3 * 7; // aNum
int aNum = (4 + 3) * 7;
//
(4 > 7) || (10 > -1)
//
(5.5 >= 5) && (4 != 1.0)
//
double circ = 3.14 * 2 * r;
…
Winter 2006
CISC121 - Prof. McLeod
is 25
aNum is 49
yields true
yields true
42