800 likes | 885 Views
CSC 332 – Algorithms and Data Structures. Java Overview. Dr. Paige H. Meeker Computer Science Presbyterian College, Clinton, SC. Answers to previous assignment. Problem 1 :
E N D
CSC 332 – Algorithms and Data Structures Java Overview Dr. Paige H. Meeker Computer Science Presbyterian College, Clinton, SC
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.
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; }
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.
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); }
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
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; }
Lecture 2: Java Overview • Primitive Java • Reference Types • Objects and Classes • Inheritance
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
Reference Types • Define • Basics • Dot operator • Declaration • = vs == • Parameter passing • Strings • Arrays • Exceptions • I/O
Objects and Classes • Definition • Javadoc • Basic Methods • Constructors • Mutator/Accessor • toString(), equals() • main() • Static • “this” • instanceOf • Packages • Creating / Importing
Inheritance • Definition • Hierarchies • Type compatibility • Super and Final • Overriding vs Overloading • Abstract methods / Classes • Multiple Inheritance • Interface • Generic Components
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
Primitive Java: Basics to Begin With • The name of the source file must match the name of the class, including case conventions.
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!!
Primitive Java:Primitive Types • 8 primitive types: • byte • short • int • long • float • double • char • boolean
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
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)
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…
Primitive Java:Basic Operators • Assignment • =, +=, -=, *=, /= • Binary Arithmetic Operators • +,-,*,=,% • Unary Operators • -, ++, -- • Type Conversions
Primitive Java:Conditional Statements Relational and Equality Operators • Equality Operators: == and != • Relational Operators: <, <=, >, >=
Primitive Java:Conditional Statements Logical Operators • AND && • OR || • NOT !
Primitive Java:If Statement if (expression) { statements; } Next statements; if (expression) { statements; } else { more statements; } Next statements;
Primitive Java:While Statement while (expression) { statements; } Next statements;
Primitive Java:For Statement for (initialization; test; update) { statements; } Next statements;
Primitive Java:Do Statement do { statements; } while (expression); Next statements;
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.
Primitive Java:continue for (int i; i <= 100; i++) { if (i%10 == 0) continue; System.out.println(i); }
Primitive Java:switch The switch statement is used to select among several small integer (or character) values
Primitive Java:Conditional Operator ? : Shorthand for simple if-else statements: testExpr ? yesExpr : noExppr Example: minVal = x<=y ? x : y;
Primitive Java:methods • Function or Procedure • Header: • Name • Parameter List • Return Type • Overloading
Primitive Java:Constants • static • final
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
Reference Types:Reference Variables • Variable that stores the memory address where an object resides • (see figure 2.1, p. 28)
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
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
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
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
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
Reference Types:Basics Parameter Passing Call-by-value Figure 2.3
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
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
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
Reference Types:Strings • toString() converts primitive types and object to Strings
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
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
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!
Reference Types:Multidimensional Arrays Arrays accessed by more than one index – an array of arrays!
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.
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.