1 / 78

CSC 332 – Algorithms and Data Structures

CSC 332 – Algorithms and Data Structures. Java Overview. Dr. Paige H. Meeker Computer Science Presbyterian College, Clinton, SC. Answers to previous assignment. Problem 1 :

zahur
Télécharger la présentation

CSC 332 – Algorithms and Data Structures

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. CSC 332 – Algorithms and Data Structures Java Overview Dr. Paige H. Meeker Computer Science Presbyterian College, Clinton, SC

  2. Answers to previous assignment Problem 1: Create a class called “LeapYear” that will accept console input from the user of a year and return a statement (true or false) if that year is a leap year. Sample output: What year would you like to test? <user input> 1984 It is true that 1984 is a leap year.

  3. Calculating Leap Years public boolean isLeap(int year) { if ((year % 100) == 0) if ((year % 400) == 0) return true; else return false; if ((year % 4) == 0) return true; return false; }

  4. Answers to previous assignment Problem 2: Write a program to determine all pairs of positive integers, (a,b), such that • a < b < 1000 • (a2 + b2 + 1)/(ab) is an integer.

  5. Positive Integer Calculation for (int i = 1; i < 1000; i++) for (int j = 1; j < 1000; j++) if (i < j) { int a = i*i; int b = j*j; if (((a+b+1)%(i*j)) == 0) System.out.println ("a = "+i+" b = "+j); }

  6. Answers to previous assignment Problem 3: Create a class called “Roman” that will accept console input from the user of an integer and return its Roman numeral equivalent. For conversion information, see: http://www.yourdictionary.com/crossword/romanums.html http://www.novaroma.org/via_romana/numbers.html

  7. Roman Numeral Calculation private static int[] numbers = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; private static String[] letters = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; public String convert(int arabic) { String roman = ""; for (int i = 0; i < numbers.length; i++) { while (arabic >= numbers[i]) { roman += letters[i]; arabic -= numbers[i]; } } return roman; }

  8. Lecture 2: Java Overview • Primitive Java • Reference Types • Objects and Classes • Inheritance

  9. Primitive Java • Conditional Statements • Relational and Equality Operators • Logical Operators • if • while • for • do • break and continue • Switch • Methods • Comments • main • Primitive Types • Constants • Declaration and Initialization of Primitive Types • Basic Operators • Assignment • Binary • Unary • Type Conversions

  10. Reference Types • Define • Basics • Dot operator • Declaration • = vs == • Parameter passing • Strings • Arrays • Exceptions • I/O

  11. Objects and Classes • Definition • Javadoc • Basic Methods • Constructors • Mutator/Accessor • toString(), equals() • main() • Static • “this” • instanceOf • Packages • Creating / Importing

  12. Inheritance • Definition • Hierarchies • Type compatibility • Super and Final • Overriding vs Overloading • Abstract methods / Classes • Multiple Inheritance • Interface • Generic Components

  13. Primitive Java: Basics to Begin With • Java code lives in files that end in .java • Compiler is javac • javac generates bytecode found in .class files • Bytecodes are portable, interpreted by the Java interpreter “java” aka the Java Virtual Machine

  14. Primitive Java: Basics to Begin With • The name of the source file must match the name of the class, including case conventions.

  15. Primitive Java:Comments • // indicates a single line comment • /* indicates a multi-line comment */ • /** indicates a comment that provides information to the javadoc utility to generate documentation from the comments */ • Well commented code is the sign of a good programmer!!

  16. Primitive Java:Primitive Types • 8 primitive types: • byte • short • int • long • float • double • char • boolean

  17. Primitive Java:Constants • Integer constants can be represented in decimal, octal, or hexadecimal notation • Character constants are enclosed in single quotes • String constants are enclosed in double quotes

  18. Primitive Java:Declaration and Initialization of Primitive Types Variables declared by providing: • Name • Type • (Hopefully) Initial Value Name must be an identifier • Any combination of letters/digits/_ but can’t start with a digit. • Reserved Words not allowed • Java is case-sensitive (age != Age)

  19. Primitive Java:Declaration and Initialization of Primitive Types Naming Conventions: • Typically, variables start with a lower case letter and new words start with an uppercase letter. • minimumWage • operatorTest • Etc…

  20. Primitive Java:Basic Operators • Assignment • =, +=, -=, *=, /= • Binary Arithmetic Operators • +,-,*,=,% • Unary Operators • -, ++, -- • Type Conversions

  21. Primitive Java:Conditional Statements Relational and Equality Operators • Equality Operators: == and != • Relational Operators: <, <=, >, >=

  22. Primitive Java:Conditional Statements Logical Operators • AND && • OR || • NOT !

  23. Primitive Java:If Statement if (expression) { statements; } Next statements; if (expression) { statements; } else { more statements; } Next statements;

  24. Primitive Java:While Statement while (expression) { statements; } Next statements;

  25. Primitive Java:For Statement for (initialization; test; update) { statements; } Next statements;

  26. Primitive Java:Do Statement do { statements; } while (expression); Next statements;

  27. Primitive Java:break outer: while (…) { while (…) { if (disaster) break outer; // Go to after outer labeled loop } Statement where break would go if no outer; } //Control passes here after outer loop is exited.

  28. Primitive Java:continue for (int i; i <= 100; i++) { if (i%10 == 0) continue; System.out.println(i); }

  29. Primitive Java:switch The switch statement is used to select among several small integer (or character) values

  30. Primitive Java:Conditional Operator ? : Shorthand for simple if-else statements: testExpr ? yesExpr : noExppr Example: minVal = x<=y ? x : y;

  31. Primitive Java:methods • Function or Procedure • Header: • Name • Parameter List • Return Type • Overloading

  32. Primitive Java:Constants • static • final

  33. Reference Types:Definition Any type that is not one of the 8 primitive types is a reference type. This includes: • Strings • Arrays • File Streams • Classes you Create

  34. Reference Types:Reference Variables • Variable that stores the memory address where an object resides • (see figure 2.1, p. 28)

  35. Reference Types:Reference Variables • Only operators allowed on references themselves: • Assignment = • Equality comparison == or != • Operations allowed on object being referenced: • Type conversion • Access internal field or call method (dot operator) • Use instanceof operator to verify stored object is of a certain type

  36. Reference Types:Basics • dot operator (.) • Used to select a method that is applied to an object • Can access individual components of an object if they are viewable

  37. Reference Types:Basics • Declaration of Objects • Declaration simply provides a name for an object, not the actual object. • Must construct the object using “new” • Construction can specify an initial state for the object

  38. Reference Types:Basics Garbage Collection When a constructed object is no longer referenced by any variable, the memory it consumes is reclaimed and made available

  39. Reference Types:Basics Meaning of = Stored values are copied lhs = rhs lhs now refers to the same object as rhs. Objects are not copied this way. If you need to copy, use the “clone” method

  40. Reference Types:Basics Parameter Passing Call-by-value Figure 2.3

  41. Reference Types:Basics Meaning of == lhs == rhs if and only if they reference the same object. To compare the actual objects referenced, you need an “equals” method

  42. Reference Types:Strings Strings behave as reference types except that concatenation is allowed (using operators + and +=) RULES: • Strings behave as objects except for the allowance of concatenation • Strings are immutable

  43. Reference Types:Strings Concatenation “this”+ “ that” //generates this that “abc”+5 //generates abc5 Comparison • Use equals() and compareTo() methods Other methods • length - compute string length • charAt - get a single character • substring – get a substring

  44. Reference Types:Strings • toString() converts primitive types and object to Strings

  45. Reference Types:Arrays • A basic mechanism for storing a collection of identically typed entities • Each entity accessed via the array indexing operator [] • Arrays always start at 0

  46. Reference Types:Arrays Declaration: int [] array1 = new int [100] //creates array of 100 ints int [] array2 = {3, 4, 5} Try to get the size right the first time – expanding arrays involves copying each individual value over – a sometimes costly process

  47. Reference Types:ArrayLists ArrayList is used for expanding arrays • add method increases size by 1 and adds new item to array at appropriate position, expanding capacity if necessary • Can only add objects – no primitive types allowed!

  48. Reference Types:Multidimensional Arrays Arrays accessed by more than one index – an array of arrays!

  49. Reference Types:Exception Handling Exceptions are used to handle “exceptional occurrences” such as errors. A try block encloses code that might generate an exception, and a catch block processes the exception. If things must be cleaned up before the exception is completed, the finally clause is used.

  50. Reference Types:Exception Handling: finally clause Three ways “finally” is used 1. The try block executes without exception – control will pass to finally block. This will be true even if try block exits prior to the last statement via a return, break, or continue.

More Related