1 / 54

CS 200 Using Objects

CS 200 Using Objects. Jim Williams, PhD. This Week. By Friday All Exam Conflict and Accommodations Requests Install Java (AdoptOpenJDK) & Eclipse Chap 2 Programs (P2): Due Thursday Lecture: Methods, Using Objects. Application: Temperature Conversion.

Télécharger la présentation

CS 200 Using Objects

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. CS 200 Using Objects Jim Williams, PhD

  2. This Week • By Friday • All Exam Conflict and Accommodations Requests • Install Java (AdoptOpenJDK) & Eclipse • Chap 2 Programs (P2): Due Thursday • Lecture: Methods, Using Objects

  3. Application: Temperature Conversion (Degrees Fahrenheit – 32) x 5 / 9 = Degrees Celsius What symbols have different meanings in Java? What changes must be made to implement this equation in Java?

  4. My List • X vs * • equals (==) vs assignment (=) • value is stored on the left hand side of assignment (=) operator • Variables: • name areas of computer memory, declare before use, declare type of data, initialize • Variable names: • start with letter, include letters numbers and _, but no spaces • Conventions: • camelCasing, spell out names • Semicolon at the end of statements

  5. Methods • A named section of code that can be "called" from other code. • Lots of existing methods that you can use rather than writing yourself.

  6. Method Demonstration • Name • Call vs Definition • Arguments vs Parameters • Local Variables vs Parameters • Returning values • Value of a method (returned value) • Testing Methods

  7. Method Summary

  8. Variables • Local • Variables declared within a method. • Must be initialized before reading from them. • Parameters • Variables declared within a method parameter list. • Initialized with arguments from the method call. Scope: Both are stored on the stack and only visible within the method they are declared.

  9. Testing Methods Methods written to run test cases to help validate and debug your code. • Unit testing: Run multiple tests on a method • Regression testing: retest method after changes

  10. API • Application Programmer Interface • Example: Search for "Java 8 Math" • Call class/static methods with the class name

  11. API vs Code API:What Code: How

  12. Calling Class/static Methods • Call class/static methods with the class name. double numInts = Math.pow( 2, 32); double root = Math.sqrt( 16); int num1 = 16; int num2 = 3; double result = num2 + Math.sqrt( num1);

  13. Magic Numbers (bad practice) Numbers with unexplained meaning: public class H { public static void main(String []args) { double s = 71 / 39.3701; } }

  14. Identifiers: Careful Naming • Names of classes, methods, variables and constants guide reader and follow course conventions. public class Height { public static void main(String []args) { final double INCHES_IN_METER = 39.3701; double heightInInches = 71; //or user input double heightInMeters = heightInInches / INCHES_IN_METER; } }

  15. Number Systems Decimal 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Binary 0, 1

  16. Decimal 1 8 9 100 10 1 = 189

  17. Binary 1 1 1 0 8 4 2 1 = 14

  18. Binary 0 1 0 1 8 4 2 1 = 5

  19. TopHat What is 10110 (binary) in decimal?

  20. TopHat What is 19 (decimal) in binary?

  21. Hexadecimal (group bits by nibble) 1000 = 8 1001 = 9 1010 = A 1011 = B 1100 = C 1101 = D 1110 = E 1111 = F 0000 = 0 0001 = 1 0010 = 2 0011 = 3 0100 = 4 0101 = 5 0110 = 6 0111 = 7 Learn the patterns to be able to recreate this.

  22. What is 23 decimal in hexadecimal? • First convert to binary • Then group bits into nibbles, right to left • Convert nibbles to hexadecimal 16, 0, 4, 2, 1 0001 0111 17 (hexadecimal) Be able to convert between binary, decimal and hexadecimal.

  23. TopHat What is 26 (decimal) in hexadecimal?

  24. TopHat: What character is this? http://www.ssec.wisc.edu/~tomw/java/unicode.html Don't need to memorize unicode but be able to look up in a table. 0000 0000 0100 0010 Unicode: 0x003E 62 > 0x003F 63 ? 0x0040 64 @ 0x0041 65 A 0x0042 66 B 0x0043 67 C

  25. What character is this? char letter = '\u0043'; http://www.ssec.wisc.edu/~tomw/java/unicode.html Unicode: 0x003E 62 > 0x003F 63 ? 0x0040 64 @ 0x0041 65 A 0x0042 66 B 0x0043 67 C

  26. TopHat What will print out and why? System.out.println('a' + 'b');

  27. Reference Types Contrast with Primitive types

  28. Primitive vs Reference Data Type Analogy • Primitive: • Giving you a birthday present • Reference: • Giving you an invitation with the address to a party where you will receive a birthday present.

  29. Primitive vs Reference Data Types Reference • Store a reference to another location in memory that contains value Integer num = 9; Integer num = new Integer(9); Primitive • Store value int i = 5; num i 5 9

  30. Demo: Stack vs Heap

  31. Memory Areas: Stack vs Heap Heap • All references point to heap (objects on heap) Stack • Variables declared as local or parameters • May have primitive or reference data type

  32. Demo: Java Visualizer int i = 3; Integer k = 4; Integer m = k; String s = "hi";

  33. TopHat Is num2 on the stack or the heap? public static void main(String[] args) { int num = 4; Integer num2 = 5; }

  34. Reference Types for Primitives • Useful to illustrate difference between primitive and reference variables • Wrapper classes contain helpful methods for the corresponding primitive data type. • e.g., search: Java 8 Integer • Later in course: useful for storing primitive data in generic data structures

  35. int to String Conversions String weekNum = 3; String weekNum = "" + 3; Wrapper classes contain useful methods. String numStr = Integer.toString( 4); int num = Integer.parseInt( numStr);

  36. Wrapper Classes • Boxing: Putting primitive into instance of wrapper class Integer num; num = new Integer( 8 ); • Unboxing: retrieve primitive from instance int num = num.intValue(); • auto-boxing/unboxing: when compiler inserts code to box/unbox.

  37. TopHat: What is in the d3 variable? Double d1 = new Double(10); double d2 = d1; d1 = 14.1; Double d3 = d1; d1 = d2; System.out.println( d3);

  38. Instance vs. Class (static) Methods Class (static) Methods • method definition has “static” modifier • use name of class when calling Math.max( 10, 20); Instance (non-static) Methods • method definition does Not have “static” modifier • use instance of class when calling String str = "hello"; char ch = str.charAt(1);

  39. TopHat: Calling String methods String strA = "This is a string"; char aChar = strA.charAt( 3);

  40. TopHat: Calling String methods String strA = "This is a string"; System.out.println( strA.substring( 3, 5));

  41. Random Number Generator Random randGen; //Declare reference variable randGen = new Random(); //create instance // randGen.setSeed( 123); //set state int valueA = randGen.nextInt( 5); //get a value from 0 to 4 int valueB = randGen.nextInt( 5); int valueC = randGen.nextInt( 5);

  42. TopHat Which expression will result in x having a value between 2 and 10, inclusive? Assume: Random rand = new Random();

  43. Scanner • Import the Scanner class import java.util.Scanner; • Read from console/standard in Scanner in = new Scanner(System.in); • Read from a String Scanner input = new Scanner("123 cs200"); • Scanner Tutorial

  44. Scanner Instance/object Methods • Use reference to access the same scanner. Scanner elephant = new Scanner(System.in); int num = elephant.nextInt(); String name = elephant.next(); String line = elephant.nextLine(); elephant.close();

  45. Read In Values Using Scanner Whitespace: space, tab, newline Token: a sequence of non-whitespace characters. 14 23.0 hello This, is a sentence. 2nd line 3rd line 43

  46. Using Scanner Scanner in = new Scanner( "Hello JAVA!\nlines\n"); • one long string of characters

  47. Read tokens using Scanner • Read next token, skip leading whitespace, stop on whitespace after token next() //return a string nextInt() //try to return value as an int nextDouble() //try to return value as a double 14 23.0 \nhello\n 22, 16.5 cs200.

  48. Misconception Scanner nextInt() method does NOT mean read in the next integer. nextInt() Means: read the next token and try to convert to be an int.

  49. TopHat What are the values in word, num1 & num2? String note = "1.0 2\nAlex two words"; Scanner input = new Scanner( note); String word = input.next(); int num1 = input.nextInt(); double num2 = input.nextDouble();

  50. Read a line using Scanner • Read up to and including next newline (\n), return everything prior to newline as a string (may be 0 length). nextLine() //returns a string 14 23.0 \nhello\n 22, 16.5 cs200.

More Related