Transcript 13X11

Java Lecture 2
CS 1311
Beginning Java
(Sort of Boring
but Oh So Necessary Syntax Stuff)
X11
13
Ever have one of those days...
X11
13
Books
• Thinking in Java -- Bruce Eckel
– Free on the web [search for Eckel]
– Also available in paper
• Java in a Nutshell -- David Flanagan (O'Reilly)
– Mostly reference
– Actually 3 books
• Kurt:
• Just Java 2 (4th Edition) Peter van der Linden
X11
13
Online
• http://www.javasoft.com
• Tutorial is excellent
X11
13
Beginning Java
•
•
•
•
•
•
•
•
•
•
Identifiers
Comments
Keywords
Data types
Expressions and operators
Operator precedence
The assignment statement
Organizing code
Selection statements
Iteration statements
X11
13
Structure
• Java "programs" consist of files containing
classes.
• The classes will consist of variable declarations
and modules which will be called methods (and
constructors)
• All of this is written in a language quite different in
appearance from Scheme.
• If Scheme is your first programming experience
then things may seem backwards at first
• If you have prior experience with other languages
it may seem familiar but watch out!
X11
13
Identifiers
• Used to name things
– Variables
– Methods
– Classes
• CaSe SeNsItIvE
• Rules
– Underscore or letter
– 0 or more underscores, letters, numbers
– Any length!
X11
13
Identifiers
• Style
– Class names capitalized
– Variables and method names start with lower case
letter. If multi-word capitalize all but first.
– Constants in all caps
• Examples
class Widget
class LinkedList
Variables: x, n pressure, isEmpty,
hasMore, steamTemp
Constants: FEETPERMILE, HOURSPERWEEK
Comments
// until end of line
/* This is a multiline comment
it continues for
* as many lines as I want
* these stars mean nothing!
*
and now for the end -->>>
*/
X11
13
Careful
/*
Comments about this section
yada - yada - yada
*/
x = 3;
y = 4;
z = 5;
// Here is some
// info about
// these lines
X11
13
Careful
/*
Comments about this section
yada - yada - yada
// (note)
x = 3;
// Here is some
y = 4;
// info about
z = 5;
// these lines
*/
X11
13
Careful
/*
Comments about this section
yada - yada - yada
x = 3;
y = 4;
z = 5;
// Here is some
// info about
// these lines
X11
13
Keywords
abstract
boolean
break
byte
case
catch
char
class
const*
continue
default
do
double
else
extends
final
finally
float
for
goto*
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
X11
13
Data types
•
•
•
•
•
What is data typing?
Why is it used?
What's good about it?
What's bad about it?
Java is considered a strongly typed language.
X11
13
Java Primitive Data Types
•
•
•
•
•
•
•
•
boolean -- true/false
byte
short
Whole Numbers
int
long
float
Fractional Numbers (with decimal digits)
double
char -- typically used for printable characters
X11
13
Java Primitive Data Types
•
•
•
•
•
•
•
•
boolean -- true/false
byte
short
Whole Numbers
int
long
float
Fractional Numbers (with decimal digits)
double
char -- typically used for printable characters
X11
13
Primitive Data Type Ranges
Type
Size Min
false*
Max
Default
true*
false
boolean
1
char
16
byte
8
-128
127
(byte) 0
short
16
-32,768
32,767
(short) 0
int
32
-2,147,483,648
2,147,483,647
0
long
64
-9,223,372,036,854,775,808
9,223,372,036,854,775,807
0L
float
32
Approx
±3.4E+38 with 7 significant digits
0.0F
double
64
Approx
±1.7E+308 with 15 significant digits
0.0D
'\u0000' (null)
void
* Not truly min and max.
X11
13
Declarations
int i;
int a, b, c;
double d = 42.0;
float f = 38.0; /* ERROR */
float f = 38.0F;
char ch1;
char ch2 = 's';
boolean isFull = true;
boolean isFull;
Equivalent?
isFull = true;
X11
13
Constants
public
public
public
public
public
public
etc.
static
static
static
static
static
static
final
final
final
final
final
final
int FEETPERMILE = 5280;
String MYGTNUM="gt1234x";
boolean DEBUG = true;
int JAN = 1;
int FEB = 2;
int MAR = 3;
if(DEBUG)
{
/* Do Something */
}
X11
13
Mysterious Strings
• Strings are objects
• They are different from every other language!!!
• Don't use strings to figure out how Java works
– They have all kinds of special rules
String someStr = "This is a string";
someStr = "Strings can be " + "concatenated.";
someStr = "If they won't fit on one line " +
"you need to do it like this";
someStr = "They can be printed";
System.out.println(someStr);
X11
13
References
• Variables which hold a "reference" or "pointer" to
an object.
• Can be thought of as the address of an object in
memory
• Normally don't manipulate (like in C)
– So no need for address of/dereferencing operators
<Type i.e. name of some class> <identifier>;
String name;
Can also initialize in same statement
Queue myQueue;
CokeMachine cc;
• More later...
X11
13
Expressions
• Unlike Scheme, expressions in Java don't have to
return a value.
• Java uses infix notation so
(and (< 25 (+ (* x x) (* y y))) (> x 0))
• becomes
(x * x + y * y < 25) && (x > 0)
• Note: && means "AND" not the same as &
X11
13
Operators
Arithmetic:
+ - * / %
Relational:
> < == <= >= !=
Logical:
&& || !
Assignment:
=
Scheme
Predicates
+= -= *= /= &= |=
^= %= <<= >>= >>>=
Conditional:
? :
Bit manipulation: & | ~ ^ << >> >>>
Funky (Inc/Dec): ++ --
X11
13
Operators
Arithmetic:
+ - * / %
Relational:
> < == <= >= !=
Logical:
&& || !
Assignment:
=
+= -= *= /= &= |=
^= %= <<= >>= >>>=
Conditional:
? :
Bit manipulation: & | ~ ^ << >> >>>
Funky (Inc/Dec): ++ --
X11
13
Operator Precedence
1 + 2 * 3
• When in doubt use parentheses
• (Don't tell Gosling)
X11
13
The following table shows the precedence assigned to the operators. The operators in this
table are listed in precedence order: the higher in the table an operator appears, the higher
its precedence. Operators with higher precedence are evaluated before operators with a
relatively lower precedence. Operators on the same line have equal precedence.
postfix operators
unary operators
creation or cast
multiplicative
additive
shift
relational
equality
bitwise AND
bitwise exclusive OR
bitwise inclusive OR
logical AND
logical OR
conditional
assignment
[] . (params) expr++ expr-++expr --expr +expr -expr ~ !
new (type)expr
* / %
+ << >> >>>
< > <= >= instanceof
== !=
When operators of equal precedence appear
&
in the same expression, a rule must govern
^
which is evaluated first. All binary operators
|
except for the assignment operators are
&&
evaluated in left-to-right order. Assignment
operators are evaluated right to left.
||
? :
= += -= *= /= %= &= ^= |= <<=
>>= >>>=
X11
13
The assignment statement
x = 1 + 1;
• Evaluate expression on right side
• Place result in variable on left side
• Left side must be capable of storing a value
3 = x; // Bad idea!
• End assignment statements with a ;
• Legal?
a = b = c = 0;
• Good idea?
• = not ==
X11
13
The Classic Duality
• Programming languages have always wrestled
with the difference between assigning a
value and the equality relational operator
• Equality (Boolean Result)
– BASIC
A = B
– Pascal
A = B
– FORTRAN
A .EQ. B
– C
A == B
– Pseudocode A = B
– Scheme
(= A B)
– Java
A == B
• Assignment
– BASIC
– Pascal
– FORTRAN
– C
– Pseudocode
– Scheme
– Java
LET A = B
A := B
A = B
A = B
A  B
(set! A B)
A = B
X11
13
Common Errors
• Misuse of ++ or -• Confusing = and ==
• Using
& instead of &&
| instead of ||
X11
13
Warning!
• Just because a language will let you do
something doesn't mean it's a good idea
_ += _-- - ++_;
/* Clear? */
X11
13
Organizing code
• Block statements
– Surround statements with curly braces
{
int i;
x = 1;
y = 2;
i = x + y;
}
– Can be used in place of a single statement
– Note: variables declared in a block have scope only in
the block!
X11
13
Organizing code
• Null statement
– Just a lone semicolon ;
– Not necessarily your friend!
X11
13
Selection statements
•
•
•
•
Used to control flow of program
If
If with Else
Complex if constructions
• Switch
X11
13
if
if(<boolean_value>)
<Executed if boolean is true>
<Executed in any case>
if(x > 0)
System.out.println("X greater than zero!");
X11
13
if
if(y > 0);
System.out.println("Always gets printed!");
if(z > 0 && isEmpty)
{
x = y;
System.out.println("Hello");
}
X11
13
if/else
if(<boolean_value>)
<Executed if boolean is true>
else
<Executed if boolean is true>
<Executed in all cases>
if(a == b)
{
System.out.println("Always use curlies");
}
else
{
System.out.println("What do you think?");
}
X11
13
if/else -- Another style
if(a == b) {
System.out.println("Always use curlies");
} else {
System.out.println("What do you think?");
}
X11
13
Complex
if(a == b) {
System.out.println("A equals B");
} else {
if(c == d) {
System.out.println("C equals D");
} else {
if(e == f) {
System.out.println("E equals F");
} else {
System.out.println("None");
}
X11
13
Complex
if(a == b)
System.out.println("A equals B");
else if(c == d)
System.out.println("C equals D");
else if(e == f)
System.out.println("E equals F");
else
System.out.println("None");
X11
13
Complex
if(a == b)
{
System.out.println("A equals B");
}
else if(c == d)
{
System.out.println("C equals D");
}
else if(e == f)
{
System.out.println("E equals F");
}
else
{
System.out.println("None");
}
X11
13
Complex
if(a == b)
System.out.println("A equals B");
else if(c == d)
System.out.println("C equals D");
else if(e == f)
System.out.println("E equals F");
else
System.out.println("None");
X11
13
Complex
if(a == b)
System.out.println("A equals B");
else if(c == d)
System.out.println("C equals D");
else if(e == f)
System.out.println("E equals F");
else
System.out.println("None");
X11
13
Complex
if(a == b)
System.out.println("A equals B");
else if(c == d)
System.out.println("C equals D");
else if(e == f)
System.out.println("E equals F");
else
System.out.println("None");
X11
13
Nesting
if(a == b) {
if(c == d) {
/* do something here */
} else {
/* do something else */
}
} else {
if(x == y) {
/* what to do? */
} else {
/* another option */
}
}
X11
13
Nesting
if(a == b) {
if(c == d) {
/* do something here */
} else {
/* do something else */
}
} else {
if(x == y) {
/* what to do? */
} else {
/* another option */
}
}
X11
13
Switch
• Used when there is a single value to test
– basically an int
• and multiple "cases"
• Common error: forgetting break
X11
13
Switch
switch (month) {
case APR:
case JUN:
case SEP:
case NOV:
numDays = 30;
break;
case FEB:
if(year % 4 == 0)
numdays = 29;
else
numdays = 28;
break;
default:
numdays = 31;
Any potential problems?
}
X11
13
Iteration statements
• while loop
– Tests at beginning of loop
– Executed 0 or more times
• do while loop
– Tests at end of loop
– Executed at least once
• for loop
– Equivalent to while loop
– Very popular!
X11
13
While Loop
while(<boolean_Value>)
<statement>
Example:
i = 0;
while(i < 10)
i++;
X11
13
While Loop
int i = 1;
int total = 0;
while(i <= 10)
{
total += i;
i++;
}
Note: No ;
X11
13
Do While Loop
do
<statement>
while(<boolean>);
X11
13
Do While Loop
int choice;
do
{
choice = menu();
switch(choice)
{
/* details omitted */
}
} while(choice != 0);
Note
X11
13
For Loop
for(<init>; <testExpr>; <increment>)
<statement>
<init> and <increment> can be multiple
statements separated by commas
<init>, <testExpr> and <increment> are all
optional!
for(;;) // Legal statment
X11
13
For Loop
for(i=0; i < MAX; i++)
System.out.println(i);
for(i=0; i < MAX; i++)
{
System.out.println(i);
}
System.out.println(i);
for(int i=0; i <= MAX; i++)
{
System.out.println(i);
}
System.out.println(i);
X11
13
For Loop
for(i=0, total=0; i < MAX; i++)
System.out.println(i);
for(i=0; i < MAX && something; i++);
{
System.out.println(i);
}
for(int i=0, j=10; i <= MAX; i++,j--)
{
System.out.println("Sum = " + i + j);
}
X11
13
while -- for equivalence
total = 0;
i = 0
while(i < MAX)
{
/* Work */
total += i;
i++;
}
total = 0;
for(i = 0; i < MAX; i++)
{
/* Work */
total += i;
}
X11
13
Questions?
X11
13
X11
13