580 likes | 596 Views
Java Lecture 2. CS 1311 Beginning Java (Sort of Boring but Oh So Necessary Syntax Stuff). 13 X 11. Ever have one of those days. 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)
E N D
Java Lecture 2 CS 1311 Beginning Java (Sort of Boring but Oh So Necessary Syntax Stuff) 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
Online • http://www.javasoft.com • Tutorial is excellent
Beginning Java • Identifiers • Comments • Keywords • Data types • Expressions and operators • Operator precedence • The assignment statement • Organizing code • Selection statements • Iteration statements
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!
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
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 -->>> */
Careful /* Comments about this section yada - yada - yada */ x = 3; // Here is some y = 4; // info about z = 5; // these lines
Careful /* Comments about this section yada - yada - yada // (note) */ x = 3; // Here is some y = 4; // info about z = 5; // these lines
Careful /* Comments about this section yada - yada - yada x = 3; // Here is some y = 4; // info about z = 5; // these lines
Keywords abstract default if private throw boolean do implements protected throws break double import public transient byte else instanceof return try case extends int short void catch final interface static volatile char finally long super while class float native switch const* for new synchronized continue goto* package this
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.
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)
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)
Primitive Data Type Ranges Type Size Min Max Default boolean 1 false* true* false char 16 '\u0000' (null) 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 void * Not truly min and max.
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?
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 */ }
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);
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
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 &
Operators Arithmetic: + - * / % Relational: > < == <= >= != Logical: && || ! Assignment: = += -= *= /= &= |= ^= %= <<= >>= >>>= Conditional: ? : Bit manipulation: & | ~ ^ << >> >>> Funky (Inc/Dec): ++ -- Scheme Predicates
Operators Arithmetic: + - * / % Relational: > < == <= >= != Logical: && || ! Assignment: = += -= *= /= &= |= ^= %= <<= >>= >>>= Conditional: ? : Bit manipulation: & | ~ ^ << >> >>>Funky (Inc/Dec): ++ --
Operator Precedence 1 + 2 * 3 • When in doubt use parentheses • (Don't tell Gosling)
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.
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 ==
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 LET A = B • Pascal A := B • FORTRAN A = B • C A = B • Pseudocode A B • Scheme (set! A B) • Java A = B
Common Errors • Misuse of ++ or -- • Confusing = and == • Using & instead of && | instead of ||
Warning! • Just because a language will let you do something doesn't mean it's a good idea _ += _-- - ++_; /* Clear? */
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!
Organizing code • Null statement • Just a lone semicolon ; • Not necessarily your friend!
Selection statements • Used to control flow of program • If • If with Else • Complex if constructions • Switch
if if(<boolean_value>) <Executed if boolean is true> <Executed in any case> if(x > 0) System.out.println("X greater than zero!");
if if(y > 0); System.out.println("Always gets printed!"); if(z > 0 && isEmpty) { x = y; System.out.println("Hello"); }
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?"); }
if/else -- Another style if(a == b) { System.out.println("Always use curlies"); } else { System.out.println("What do you think?"); }
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"); }
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");
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"); }
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");
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");
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");
Nesting if(a == b) { if(c == d) { /* do something here */ } else { /* do something else */ } } else { if(x == y) { /* what to do? */ } else { /* another option */ } }
Nesting if(a == b) { if(c == d) { /* do something here */ } else { /* do something else */ } } else { if(x == y) { /* what to do? */ } else { /* another option */ } }
Switch • Used when there is a single value to test • basically an int • and multiple "cases" • Common error: forgetting break
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?
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!
While Loop while(<boolean_Value>) <statement> Example: i = 0; while(i < 10) i++;
While Loop int i = 1; int total = 0; while(i <= 10) { total += i; i++; } Note: No ;