1 / 58

Java Lecture 2

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)

rpatchen
Télécharger la présentation

Java Lecture 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Ever have one of those days...

  3. 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

  4. Online • http://www.javasoft.com • Tutorial is excellent

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

  6. 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!

  7. Identifiers • Used to name things • Variables • Methods • Classes • CaSe SeNsItIvE • Rules • Underscore or letter • 0 or more underscores, letters, numbers • Any length!

  8. 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

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

  10. Careful /* Comments about this section yada - yada - yada */ x = 3; // Here is some y = 4; // info about z = 5; // these lines

  11. Careful /* Comments about this section yada - yada - yada // (note) */ x = 3; // Here is some y = 4; // info about z = 5; // these lines

  12. Careful /* Comments about this section yada - yada - yada x = 3; // Here is some y = 4; // info about z = 5; // these lines

  13. 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

  14. 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.

  15. 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)

  16. 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)

  17. 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.

  18. 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?

  19. 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 */ }

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

  21. 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

  22. 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 &

  23. Operators Arithmetic: + - * / % Relational: > < == <= >= != Logical: && || ! Assignment: = += -= *= /= &= |= ^= %= <<= >>= >>>= Conditional: ? : Bit manipulation: & | ~ ^ << >> >>> Funky (Inc/Dec): ++ -- Scheme Predicates

  24. Operators Arithmetic: + - * / % Relational: > < == <= >= != Logical: && || ! Assignment: = += -= *= /= &= |= ^= %= <<= >>= >>>= Conditional: ? : Bit manipulation: & | ~ ^ << >> >>>Funky (Inc/Dec): ++ --

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

  26. 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.

  27. 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 ==

  28. 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

  29. Common Errors • Misuse of ++ or -- • Confusing = and == • Using & instead of && | instead of ||

  30. Warning! • Just because a language will let you do something doesn't mean it's a good idea _ += _-- - ++_; /* Clear? */

  31. 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!

  32. Organizing code • Null statement • Just a lone semicolon ; • Not necessarily your friend!

  33. Selection statements • Used to control flow of program • If • If with Else • Complex if constructions • Switch

  34. if if(<boolean_value>) <Executed if boolean is true> <Executed in any case> if(x > 0) System.out.println("X greater than zero!");

  35. if if(y > 0); System.out.println("Always gets printed!"); if(z > 0 && isEmpty) { x = y; System.out.println("Hello"); }

  36. 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?"); }

  37. if/else -- Another style if(a == b) { System.out.println("Always use curlies"); } else { System.out.println("What do you think?"); }

  38. 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"); }

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

  40. 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"); }

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

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

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

  44. Nesting if(a == b) { if(c == d) { /* do something here */ } else { /* do something else */ } } else { if(x == y) { /* what to do? */ } else { /* another option */ } }

  45. Nesting if(a == b) { if(c == d) { /* do something here */ } else { /* do something else */ } } else { if(x == y) { /* what to do? */ } else { /* another option */ } }

  46. Switch • Used when there is a single value to test • basically an int • and multiple "cases" • Common error: forgetting break

  47. 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?

  48. 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!

  49. While Loop while(<boolean_Value>) <statement> Example: i = 0; while(i < 10) i++;

  50. While Loop int i = 1; int total = 0; while(i <= 10) { total += i; i++; } Note: No ;

More Related