Slide 1 Welcome to CMSC298P CMSC298P – Coordinator: Nelson Padua-Perez TA’s Office Hours (TBA) Homework Check class web site1 Install Eclipse Go over the Eclipse Tutorial (see web page entry) Write and compile all the programs discussed in lecture Mac environment for labs We will distribute accounts tomorrow Going over the syllabus Required Attendance Working on homework 1 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 2 Modern Program Development Old way: Text editor (vi, emacs): Program source is typed in and modified. Compiler: Debugger: Modern way: (IDE) Examples: 2 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 3 The Java Programming Language Java – Why is i t special? – An object-oriented programming language – Developed in early 1990’s. – Unlike C++, Java programs are portable between machines – why? • C/C++ programs … • Java bytecode. • A JVM interpreter …. – Has a rich set of libraries. – The Java compiler and interpreter are part of Java Software Development Kit (SDK), also referred to as Java Development Kit (JDK). 3 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 4 Java Programming Concepts A quick overview of fundamental Java concepts. (More details later.) Object: Class: blueprint . Method: Main Method: Statements: Individual instructions. Examples: Declarations – Assignment – Method invocation – Control flow – 4 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 5 A Sample Java Program /** * My first sa mple Java program. File: MyFirstP rogra m.java */ public cla ss MyFirstP rogra m { public static void m ain( String[ ] arg s ) { int secondsPerMinute = 60; // let’ s crea te some varia ble s int minutesPe rLectu re = 50; int tota lSeconds = secondsP erMinute * minutesP erL ecture; System.out.println( " The re a re " + to talSeconds + " seconds in a lec ture.“ ); } } Program Output: There are 3000 sec onds in a lectur e. 5 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 6 A Sample Java Program There are 3000 seconds in a lecture. 6 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 7 A Sample Java Program There are 3000 seconds in a lecture. 7 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 8 A Sample Java Program There are 3000 seconds in a lecture. 8 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 9 Java Program Organization Class: The structure around which all Java programs are based. File name: MyFirstProgram.java: public class My FirstProgram { … (contents of the class go here) … } A class consist of a combination of data units, called variables, and computation units, called methods. 9 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 10 Java Program Organization Methods: This is where all the computa tion begins. public static void main( String[ ] a rgs ) { … (contents of the main method go here ) … } Variables: These are the data i tems tha t the methods operate on. Variables can be of various types, integers, for example: int secondsPerMinute = 60; int minutesPerLecture = 50; 10 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 11 Java Program Organization Statements: Declarations – int x, y, z; String s = “Howdy”; boolean isValid = true; // three integer va riable s // a character string variable // a boolean (true or false) variable Assignments – x = 13; Method invocation – System.out.p rintln( “Print this message“ ); Control flow – Expressions/Operators: x = (2*y – z)/32; 11 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 12 Other Java Elements: Comments Comments: : Line comments: Block comments: interest = ba lance * rate; /* The following lines of code update the ba lance and compute the account interest. */ balance = oldBalance – debits; interest = ba lance * rate; // compute the account interest /* The following lines of code update * the ba lance and compute the account * interest. */ balance = oldBalance – debits; interest = ba lance * rate; It is the block stand out better. 12 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 13 Java I/O and JOptionPane Java Input/Output: JOptionPane: Input dialog: showInputDialog( String prompt ): String name; name = JOptionPane.showInputDialog( "Enter your name“ ); name “Schultzie von Wienerschnitzel III” 13 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 14 More JOptionPane Message Dialog: JOptionPane.showMessageDialog( null, “Your message here” ); Why the null? Don’t worry, just include it. 14 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 15 Java Example with JOptionPane File:J OPSa mple.java /** * A simple exa mple sho wing Java I/ O using JOp tionPane */ import java x. swing.*; // needed to make JOp tionPane accessible public cla ss J OPSample { public static void m ain( String[ ] arg s ) { String nam e = JOptionPane. sho wInputDialog( "Enter you r name“ ); String reply = "Nam e entere d is: " + nam e; JOptionPane.showM essageDialog ( null, rep ly ); System. exit(0 ); // terminate the program } } 15 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 16 Dissecting the Example /** * A simple example showing Java I/O using JOptionPane */ import javax.swing.*; // needed to make JOptionPane accessible public class JOP Sample { public static void main( String[ ] a rgs ) { String name = JOptionPane.showInputDialog( "Enter your name“ ); String reply = "Nam e entered is: " + name; JOptionPane.showMessageDialog( null, reply ); System. exit(0); // terminate the program } } 16 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 17 Still More on JOptionPane Confirmation Dialog: int answer; answer = JOptionPane.showConfirmDialog( Java Again,null, alway s “Isn’t include this. great?" ); • JOptionPane. YES_OPTION • JOptionPane. NO_OPTION • JOptionPane. CANCEL_OPTION if “Yes” if “No” if “Cancel” 17 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 18 Another Example with JOptionPane import java x. swing.*; File:J OPSa mple2.java public cla ss J OPSample2 { public static void m ain( String[ ] arg s ) { String nam e = JOptionPane. sho wInputDialog( "Enter you r name" ); String cofirmMe ssage = "Is your nam e re ally " + name + "?"; int answe r = JOp tionPane.showConfirmDialog( null, cofirmMe ssage ); if (answe r == JOptionPane.YES_ OPTI ON ) { JOptionPane.showM essageDialog ( null, "He llo " + name ); } else { JOptionPane.showM essageDialog ( null, "You lied!" ); } System. exit(0 ); // terminate (nee de d with JOp tionPane) } } 18 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 19 Eclipse Introduction • • • • • How to start Eclipse How to create a Project How to create a program – “Hello World” – JOPSample2 How to compile a program How to run a program 19 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 20 Primitive Data Types Java’s primitive data types: Integer Types: int byte, short long Floating-Point Types: float double Other types: boolean char String (?): is not a primitive type. 20 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 21 Data Types and Variables Strong Type Checking: Java checks that all expressions involve compatible types. int x, y; double d; String s; boolean b; char c; Foolish human x b c s d = = = = = 7; true; ‘#’; “cat” + “bert”; x – 3; b = 5; y = x + b; c = x; 21 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 22 Common Numeric Operators Arithmetic Operators: – Unary negation: – Multiplication/Division – Addition/Subtraction: Comparison Operators: – Equality/Inequality: – Less than/Greater than: – Less than or equal/Greater than or equal: 22 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 23 Common String Operators String Concatenation: The ‘+’ operator concatenates (joins) two strings. String Comparison: s.equals(t) : s.compareTo(t) : 23 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 24 Converting (Parsing) Strings to Numbers Parsing: String int: int year = Integer.parseInt( “2004” ) String float: float weight = Float.parseFloat( “175.35” ); String double: double pi = Double.parseDouble( “3.1415926” ): Example: String heightStri ng = JO ptionPane .show InputDialog( “Enter height ” ) ; float height = Float .parseFl oat( heightStri ng ); 24 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 25 Control Flow and Conditionals Control flow: Conditionals: – Loops: The if statement: if ( inchesOfSnow > 7 ) System.out.println( “I’m staying home” ); The if-else statement: if ( inchesOfSnow > 7 ) System.out.println( “I’m staying home” ); else System.out.println( “I’m staying home anyway” ); 25 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 26 More on Conditionals Basic Structure: Logical Operators: Logical “and”: && Logical “or”: || Logical “not”: ) if ( temp >= 97 && temp <= 99 ) System.out.println( “Patient is healthy” ); if ( months >= 3 || miles >= 3000 ) System.out.println( “Change your oil” ); ! if ( ! phone.equals( “301-555-1212” ) System.out.println( “Sorry, wrong number” ); 26 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 27 Example of Conditionals /** * An examp le using J OptionPane and con ditionals */ import java x. swing.*; File: J OPConditional.ja va public cla ss J OPConditional { } public static void m ain( String[ ] arg s ) { int answe r = JOp tionPane.showConfirmDialog( null, "I sn't J ava g rea t?" ); if (answe r == JOptionPane.YES_ OPTI ON ) JOp tionPane.sho wMe ssageDialog( null, " Wise c hoice." ); else JOp tionPane.sho wMe ssageDialog( null, " Wrong an swer." ); System. exit(0 ); } 27 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 28 Another Example of Conditionals File: Simple Te st.ja va /** * A simple intelligence te st */ import java x. swing.*; public cla ss Simple Te st { public static void main( String[ ] a rgs ) { String choice = JOptionPane.showInputDialog ( " What is the world's g rea test university? (hint: U MCP)" ); if ( choice.equals( “U MCP” ) ) // correct respon se J OptionPane.showM essageDialog ( null, “Wi se choice.” ); e lse // incorrect re sponse J OptionPane.showM essageDialog ( null, “So rry, you blew it. ” ); Sy stem.e xit(0); // terminate the program } } 28 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 29 while Loop Example Task: int x = 10; while ( x >= 0 ) { System.out.println( x + “ bottles of beer on the wall” ); x = x-1; } System.out.println( “Done” ); Output: 29 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 30 Example of Loops and Conditionals File: Simple Test2.java /** * A simple intelligence test (with a correctness check) */ import javax.swing.*; public class Simp leTe st2 { public static void main( String[ ] a rgs ) { boolean isCorrect; do { String choice = JOptionPane.showInputDialog( “What is the world' s grea test unive rsity? (hint: UMCP)” ); if ( choice.equals( “UMCP” ) ) { // correct response isCorrect = true; } else { // incorrect response isCorrect = false; JOptionPane.showMessageDialog( null, “You ble w it. Try again.” ); } } while ( ! isCorrect ); // keep trying until correct } } JOptionPane.showMessageDialog( null, “Wise choice.” ); System. exit(0); // terminate program 30 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 31 Sample Sample Execution Execution isCorrect isCorrectisisset set to to true true and andso so loop loopexits exits 31 31 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 32 Constants (Literals) Specifying constants: Integer Types: byte short int long Floating-Point Types: double Decimal notation: Scientific notation: float 32 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 33 Character and String Constants char constants: – letters and digits: – punctuation symbols: – escape sequences: String constants: Escape sequences: \” double quote \’ single quote \\ backslash \n new-line character (start a new line) \t tab character Examples: 33 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 34 Variable Names Recall: – Java’s primitive types: boolean, char, byte, short, int, long, float, double. Valid Variable Names: These rules apply to all Java names, or identifiers, including methods and class names. – Starts with: a letter (a-z or A-Z), dollar sign ($), or underscore (_). – Followed by: zero or more letters, dollar signs, underscores, or digits (0-9). – Uppercase and lowercase are different (total ≠ Total ≠ TOTAL). – Cannot be any of the reserved names. These are special names (keywords) reserved for the compiler. Examples: class, float, int, if, then, else, do, public, private, void, … See page 35 in Lewis and Loftus for a complete listing. 34 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 35 Variable Name Conventions Naming Conventions: Conventions tha t have developed over time. Variables and methods: Class names: Named constants 35 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 36 Short-Circuiting Short-circuiting in Logical Operators:. Why is this useful? Also works with ||: 36 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 37 Operator Precedence Operator Precedence: Unary ops: +x, -x, ++x, --x, x++, x-- , !x Multiplicative ops: *, /, % Addition/Subtraction: +, Comparisons: <, <=, >, >= Equality: ==, != Logical ops: &&, || (&& is higher than ||) Assignments: =, +=, -=, *=, /=, etc. Example: if ( 2 * x ++ < 5 * z + 3 && - w != x / 2 * y ) … Equivalent: if ( ( (2*(x ++)) < ((5*z) + 3) ) && ((-w) != ((x /2)*y)) ) … 37 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 38 Type Casting Casting: Automatic (Implicit) Casting: double float long int short byte 38 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 39 Type Casting Automatic Casting Examples: int intVar = 12; double doubleVar = 5; long longVar = intVar; int intVar2 = longVar; float floatVar1 = 2.3; float floatVar2 = 2.3f; intVar2 = 2.0 * intVar; 39 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 40 Explicit Casting Someti mes you need to cast one numeric type to another: Explicit cast: Converts one numeric type explicitly into another. ( desired type ) expression Example 1: Avoid truncation from integer division. int x = 23; int y = 4; double d = x / y; double e = (double) x / (double) y; Example 2: int degreesCelsius = … ; int degreesFahrenheit = (int) ( ( 9.0 / 5.0 ) * degreesCelsius ) + 32.0 ); 40 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 41 Objects Object: State: Behavior: Examples: Bank account: State: Behaviors: Voice-mail system: State: Behaviors: Object-oriented programming: 41 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 42 Classes Class: Instance Data: Methods: Example: Bank account Instance data: String accountNumber; String ownersName; String ownersAddress; double currentBalance; Methods: debit: decrease the current balance by a given amount credit: increase the current balance by a given amount addInterest: compute interest and add it to the balance ... Encapsulation: 42 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 43 Creating Objects Primitive type value: Reference to an object: Variable declaration: Primitive types: Class object: Examples: int x = 52; String s = new String( “Schultzie” ); String t = “von Wienerschnitzel”; x s 52 Schultzie t von Wienerschnitzel 43 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 44 Under the Hood: What does “new ” do? Wha t happens when “new” is called: String s = new String( “Schultzie” ); String t = new String( “von Wienerschnitzel” ); x s 52 the Heap Schultzie t von Wienerschnitzel 44 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 45 The Java Class Library Java’s class library: java.lang: java.util: Note: ‘x’ java.text: java.awt: javax.swing: java.io: java.applet: See also Appendix M in L&L and Sun’s Java API Specs (a link can be found in the Resources class web page). 45 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 46 Accessing the Class Library Fully qualified name: Example: javax.swing.JOptionPane.showMe ssageDialog( null, “ This is really inconvenient!” ); String input = javax.swing.JOptionPane.showInputDialog( “I agree!” ); 46 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 47 The Import Statement Import Statement: import javax.swing.JOptionPane; // import class JOptionPane … // no need for “javax.swing” anymore String input = JOptionPane.showInputDialog( “Much better” ); Importing All the Classes: import java.util.*; // import all classes from java.util import javax.swing.*;// import all classes from javax.swing java.lang: 47 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 48 JOptionPane - Revisited JOptionPane: JOptionPane showConfirmDialog( null, “Your prompt here”, “Window title here”, optionType); // (always null for us) // prompt for the user // title for the window // what options to give the use r Example: JOptionPane showConfirmDialog( null, “Are you sure you want to quit?\nI mean really su re?”, “Confirm Quit”, JOptionPane.YES_NO_OPTION); 48 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 49 The String Class - Revisited Let: String s = new String( “Schultzie” ); String t = new String( “sCHultZIE” ); Length: int i = s.length( ); Comparisons: boolean a = s.equals( t ); boolean b = s.equalsIgnoreCase( t ); int j = s.compareTo( t ); int k = s.compareToIgnoreCase( t ); Access character at a given index: (index runs from 0 to length-1) char c = s.charAt( 0 ); char d = s.charAt( 2 ); Change Case: String x = t.toLowerCa se( ); String y = t.toUpperCase( ); (See Page 89 in L&L for more examples.) 49 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 50 The NumberFormat Class NumberFormat: Import: import java.text.*; Currency Conversion: NumberFormat money = NumberFormat.getCurrencyInstance( ); double amount = 123.6; System.out.println( money.format(amount) ); Percentage Conversion: NumberFormat percent = NumberFormat.getPercentInstance( ); double taxRate = 0.0793; System.out.println( percent.format(taxRate) ); 50 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 51 Example of Currency Conversion /* This is a simple cashie r checkout program */ import java.text.*; import javax.swing.*; public class Cashier { public static void main( String[ ] a rgs ) { double priceOfMilk = 3.50; // item prices double priceOfSugar = 1.25; double total = 0.0; // initialize total price String item; do { // read items until 'quit' item = JOptionPane.showInputDialog( "Enter Item (or 'quit') " ); if ( item.equals( "milk" ) ) total += priceOfMilk; else if ( item.equals( "sugar" ) ) total += priceOfSugar; } while ( ! item.equals( "quit" ) ); // convert to currency NumberFormat money = NumberFormat.ge tCurrencyInstance( ); JOptionPane.showMessageDialog( null, "Amount Due: " + money.format( total ) ); System. exit( 0 ); } } 51 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 52 Under Under the the Hood: Hood: Objects Objects vs. vs. Primitive Primitive Types Types Technical Technical Question: Question:Why Whydoes doesJava Javatrea treattpri primi mitive tive types typesand and objects objectsdifferently? differently? String String ss == “S “Schultzie chultzie”;”; ss == “this “this might might be be aa ridiculously ridiculously long long string…”; string…”; xx ss tt 52 52 the theHeap Heap Schultzie Schultzie this thismight mightbe… be… von vonWienerschnitzel Wienerschnitzel 52 52 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 53 Under the Hood: Assignment and Aliasing Remem ber: Java allows Strings to be tre ate d “a lmost” a s if they we re primitive type s. Just for Strings: String t = “von Wienerschnitzel”; is convenient shorthand for what Ja va really does: String t = new String( “von Wienerschnitzel” ); Aliasing: When one objec t referenc e is assigned to another, the memory address is copied, but not the objec t i tself. To crea te a new instance requires a call to “new”. String u = t; String w = new String( t ); // copies the address (reference) // creates a new string initialized to t The variable u is effec tively an alias for t, tha t is, a different na me for the sa me objec t. Beware: Aliasing is considered dangerous, since changing one variable can modify another. the H eap t von Wiene rschnitz el u w von Wiene rschnitz el 53 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 54 Under the Hood: ‘==’ and ‘equals’ Revisited Start with the ini tializations: String t = new String( “von Wienerschnitzel” ); String u = t; // copies the reference (address) String w = new String( t ); // creates a new string initialized to t Consider now the differenc e between == and equals( ) . ==: Tests whet her the references (addresses) are equal. equals( ): Tests whether the contents are equal. if ( u == t ) … if ( w == t ) … if ( u.equals(w) ) // true: u and t refer to the same object // false: w and t refer to different objects // true: u’s and w’s contents are equal Bottom line: Applying == to strings i s legal, but it al most never achieves the result you intended. Use equals( ) instead. the H eap t von Wiene rschnitz el u w von Wiene rschnitz el 54 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 55 Under the Hood: ‘==’ and ‘equals’ Revisited Start with the ini tializations: String t = new String( “von Wienerschnitzel” ); String u = t; String w = new String( t ); Consider now the differenc e between == and equals( ) . ==: . equals( ): if ( u == t ) … if ( w == t ) … if ( u.equals(w) ) Bottom line: the H eap t von Wiene rschnitz el u w von Wiene rschnitz el 55 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 56 Under the Hood: Garbage Collection Garbage: int x = 52; String s = new String( “Schultzie” ); String t = new String( “von Wienerschnitzel” ); s = new String( “Another string” ); Garbage Collection: x s t 52 the Heap Schultzie Another string von Wienerschnitzel 56 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 57 Program Development How do I build a program? Software development lifecycle: Analysis: Design: Implementation: Testing: Maintenance: The “cycle”:. 57 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 58 Anatomy of a Class A class contains declarations of: Instance data: Methods: Typical class file structure: public class Widget { int dataItem1; double dataItem2; String dataIterm3; File: Widget.ja va methodDefinition1(…) { … } Declaration of instance data Declaration of methods methodDefinition2(…) { … } } 58 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ Slide 59 Example: Date Instance Data: int month: int day: int year: Ranges from 1 to 12 (e.g. 1 = Jan, 2 = Feb, etc) Ranges from 1 to 31 (depending on the month) Four digit year (e.g. 2004) Methods: Date( int m, int d, int y ): toString( ): equals( Date d ): 60 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 60 Example: Date.java (part 1) /* * Date: An object that sto res a date */ File: Date.java (pa rt 1) public class Date { private int month; private int day; private int year; // the month (from 1-12) // the day of the month (1-31) // the year (four digits) /* Constructor method initializes a new Date object */ public Date( int m, int d, int y ) { month = m; day = d; year = y; } } // (insert part 2 here) 61 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 61 Creating a Date Object A Date object is created using “new”: Date indepDay = new Date( 7, 4, 1776 ); // July, 4, 1776 This generates a call to the constructor: public Date( int m, int d, int y ) { month = m; day = d; year = y; } 62 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 62 Example: Date.java (part 2) This goes inside the Date cla ss File: Date.java (pa rt 2) /* Converts to a string */ public String toString( ) { return new String( month + "/" + day + "/" + year ); } /* Is this date equal to anothe r? */ public boolean equals( Date d ) { if ( ( year == d.year ) && ( month == d.month ) && ( da y == d.day ) ) return true; else return false; } 63 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 63 Using the “ toString” method Printing a Date object: Date indepDay = new Date( 7, 4, 1776 ); // July, 4, 1776 System.out.println( “Independence day is ” + indepDay.toString( ) ); public String toString( ) { return new String( month + "/" + day + "/" + year ); } Output: Independence day is 7/4/1776 System.out.println( “Independence day is ” + indepDay); 64 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 64 Using the “equals” method Comparing two dates: Date bobsBirthday = new Date( 7, 18, 1985 ); // July 18, 1985 Date carolsBirthday = new Date( 3, 23, 1985 ); // March 23, 1985 if ( bobsBirthday.equals( carolsBirthday ) ) … // (false) This invokes Bob’s equals method: public boolean equals( Date d ) { if ( ( year == d.year ) && ( month == d.month ) && ( da y == d.day ) ) return true; else return false; } Carol’s birthday is the actual parameter. It is substi tuted for the formal parameter “d” in the method. 65 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 65 Example: DateDemo.java /* This file demos the Date cla ss */ File: DateDemo.java public class DateDemo { public static void main( String[ ] a rgs ) { Date bobsBirthday = new Date( 7, 18, 1985 ); Date carolsBirthday = new Date( 3, 23, 1985 ); // July 18, 1985 // March 23, 1985 System.out.p rintln( "His birthday is " + bo bsBirthday.toString( ) ); System.out.p rintln( "He r birthday is " + carolsBirthday. toString( ) ); } } if ( bobsBirthday. equals( ca rolsBirthday ) ) System.out.p rintln( "Sa me birthday" ); else System.out.p rintln( "Different birthdays" ); Output: His birthday i s 7/18/1985 Her birthday is 3/23/1985 Different birthdays 66 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 66 Visibility and Encapsulation Two views of an object: Class user (client): sees the public interface, Class implementer: sees all the class’s data and methods. . Visibility Modifiers: Control how members can be accessed. private: public:. [protected]:. 67 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 67 Visibility and Encapsulation Example: File: Modifiers.java public class Modifiers { public int pubData; private int privData; public void pubMethod( ) { /* omitted */ } private void privM ethod( ) { /* omitted */ } } public class ModifierDemo { public static void main( String[ ] args ) { Modifiers mod = new Modifiers( ); mod.pubData = 1; mod.pubM ethod( ); mod.privData = 1; mod.privMethod( ); } } File: ModifierDemo.java 68 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 68 Visibility: Guidelines Wha t should be visible and what not? Instance data should be private: Example: month could reasonably be any of the following… int from 1-12: int from 0-11: String: “Jan”, “Feb”, Exception: Constants can be made public. public final int DAYS_PER_WEEK = 7; 69 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 69 Visibility: Guidelines Wha t should be visible and what not? Methods in the public interface are public: Utility/Support methods should be private: Conventions: Methods are often further distinguished by their general function. Accessors: Mutators:. Examples: Possible additional methods for the Date class: Accessor: Mutator: int getMonth( ) { return month; } void incrementYear( ) { year++; } 70 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________ Slide 70 Method Return Types and “void” A method can either: Return a value:. Return no value:. Examples: (Parameters and method bodies omitted) public String toString( ) public boolean equals( … ) private double getPressure( … ) public void printHelp( ) private void changeAddress( … ) 71 ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ________________________________________________________________________ ____________________________________________________________________