13 x 11 java lecture 2 cs 1311 beginning java (sort of boring but oh so necessary syntax stuff) 13 x...

58
13X11 Java Lecture 2 CS 1311 Beginning Java (Sort of Boring but Oh So Necessary Syntax Stuff) 13X11

Upload: jean-goodman

Post on 14-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

13X11

Java Lecture 2

CS 1311

Beginning Java

(Sort of Boring

but Oh So Necessary Syntax Stuff)

13X11

13X11

Ever have one of those days...

13X11

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

13X11

Online

• http://www.javasoft.com

• Tutorial is excellent

13X11

Beginning Java

• Identifiers• Comments• Keywords• Data types• Expressions and operators• Operator precedence• The assignment statement• Organizing code• Selection statements• Iteration statements

13X11

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!

13X11

Identifiers

• Used to name things– Variables– Methods– Classes

• CaSe SeNsItIvE• Rules

– Underscore or letter– 0 or more underscores, letters, numbers– Any length!

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

13X11

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 -->>> */

13X11

Careful

/*

Comments about this section

yada - yada - yada

*/

x = 3;// Here is some

y = 4; // info about

z = 5; // these lines

13X11

Careful

/*

Comments about this section

yada - yada - yada

// (note) */

x = 3;// Here is some

y = 4; // info about

z = 5; // these lines

13X11

Careful

/*

Comments about this section

yada - yada - yada

x = 3;// Here is some

y = 4; // info about

z = 5; // these lines

13X11

Keywords

abstract default if private throwboolean do implements protected throwsbreak double import public

transientbyte else instanceof return trycase extends int short voidcatch final interface static

volatilechar finally long super whileclass float native switchconst* for new synchronizedcontinue goto* package this

13X11

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.

13X11

Java Primitive Data Types

• boolean -- true/false• byte• short• int• long• float• double• char -- typically used for printable characters

Whole Numbers

Fractional Numbers (with decimal digits)

13X11

Java Primitive Data Types

• boolean -- true/false• byte• short• int• long• float• double• char -- typically used for printable characters

Whole Numbers

Fractional Numbers (with decimal digits)

13X11

Primitive Data Type RangesType Size Min Default

boolean false

Max

1 false* true*

char '\u0000' (null)16

byte (byte) 08 -128 127

short (short) 016 -32,768 32,767

int 032 -2,147,483,648 2,147,483,647

long 0L64 -9,223,372,036,854,775,808 9,223,372,036,854,775,807

float 0.0F32 Approx ±3.4E+38 with 7 significant digits

double 0.0D64 Approx ±1.7E+308 with 15 significant digits

void

* Not truly min and max.

13X11

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;

isFull = true;Equivalent?

13X11

Constants

public static final int FEETPERMILE = 5280;

public static final String MYGTNUM="gt1234x";

public static final boolean DEBUG = true;

public static final int JAN = 1;

public static final int FEB = 2;

public static final int MAR = 3;

etc.

if(DEBUG)

{

/* Do Something */

}

13X11

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);

13X11

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;

Queue myQueue;

CokeMachine cc;

• More later...

Can also initialize in same statement

13X11

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 &

13X11

Operators

Arithmetic: + - * / %

Relational: > < == <= >= !=

Logical: && || !

Assignment: =

+= -= *= /= &= |=

^= %= <<= >>= >>>=

Conditional: ? :

Bit manipulation: & | ~ ^ << >> >>> Funky (Inc/Dec): ++ --

SchemePredicates

SchemePredicates

13X11

Operators

Arithmetic: + - * / %

Relational: > < == <= >= !=

Logical: && || !

Assignment: =

+= -= *= /= &= |=

^= %= <<= >>= >>>=

Conditional: ? :

Bit manipulation: & | ~ ^ << >> >>> Funky (Inc/Dec): ++ --

13X11

Operator Precedence

1 + 2 * 3• When in doubt use parentheses• (Don't tell Gosling)

13X11

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 [] . (params) expr++ expr-- unary operators ++expr --expr +expr -expr ~ ! creation or cast new (type)expr multiplicative * / % additive + - shift << >> >>> relational < > <= >= instanceof equality == != bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | logical AND && logical OR || conditional ? : assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

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.

13X11

The assignment statementx = 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 ==

13X11

The Classic Duality

• Programming languages have always wrestled with the difference between assigning a value and the equality relational operator

• 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

• 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 LET A = B– Pascal A := B– FORTRAN A = B– C A = B– Pseudocode A B– Scheme (set! A B)– Java A = B

• Assignment– BASIC LET A = B– Pascal A := B– FORTRAN A = B– C A = B– Pseudocode A B– Scheme (set! A B)– Java A = B

13X11

Common Errors

• Misuse of ++ or --

• Confusing = and ==

• Using

& instead of &&

| instead of ||

13X11

Warning!

• Just because a language will let you do something doesn't mean it's a good idea

_ += _-- - ++_;

/* Clear? */

13X11

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!

13X11

Organizing code

• Null statement

– Just a lone semicolon ;

– Not necessarily your friend!

13X11

Selection statements

• Used to control flow of program• If• If with Else• Complex if constructions

• Switch

13X11

if

if(<boolean_value>)

<Executed if boolean is true>

<Executed in any case>

if(x > 0)

System.out.println("X greater than zero!");

13X11

if

if(y > 0);

System.out.println("Always gets printed!");

if(z > 0 && isEmpty)

{

x = y;

System.out.println("Hello");

}

13X11

if/elseif(<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?");

}

13X11

if/else -- Another styleif(a == b) {

System.out.println("Always use curlies");

} else {

System.out.println("What do you think?");

}

13X11

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");

}

13X11

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");

13X11

Complexif(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");}

13X11

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");

13X11

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");

13X11

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");

13X11

Nestingif(a == b) {

if(c == d) {

/* do something here */

} else {

/* do something else */

}

} else {

if(x == y) {

/* what to do? */

} else {

/* another option */

}

}

13X11

Nestingif(a == b) {

if(c == d) {

/* do something here */

} else {

/* do something else */

}

} else {

if(x == y) {

/* what to do? */

} else {

/* another option */

}

}

13X11

Switch

• Used when there is a single value to test– basically an int

• and multiple "cases"

• Common error: forgetting break

13X11

Switchswitch (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?

13X11

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!

13X11

While Loop

while(<boolean_Value>)

<statement>

Example:

i = 0;

while(i < 10)

i++;

13X11

While Loop

int i = 1;

int total = 0;

while(i <= 10)

{

total += i;

i++;

}Note: No ;

13X11

Do While Loop

do

<statement>

while(<boolean>);

13X11

Do While Loop

int choice;

do

{

choice = menu();

switch(choice)

{

/* details omitted */

}

} while(choice != 0);Note

13X11

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

13X11

For Loopfor(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);

13X11

For Loopfor(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);

}

13X11

while -- for equivalence

total = 0;

i = 0

while(i < MAX)

{

/* Work */

total += i;

i++i++;

}

total = 0;

for(i = 0; i < MAX; i++i++)

{

/* Work *//* Work */

total += i;total += i;

}

13X11

Questions?

13X11