620 likes | 637 Views
Learn about method overloading in Java programming, its benefits, rules, and practical exercises. Explore Wrapper classes, System class methods, and examples. Enhance your Java skills with Prof. McLeod's CISC101 course.
E N D
Last Time • (Midterm Exam!) • Before that – methods. CISC101 - Prof. McLeod
Announcements • Assn 2 due tonight. CISC101 - Prof. McLeod
Today • Look at midterm solution. • Review method overloading. • A few useful Java classes: • Other handy System class methods • Wrapper classes • String class • StringTokenizer class • Classes for File I/O CISC101 - Prof. McLeod
Method Overloading • A method can have the same name in many different classes (“println”, for example). • “Overloading” is when a method name is used more than once within the same class. • The rule is that no two methods with the same name within a class can have the same number and/or types of parameters in the method declarations. (The “NOT” rule.) CISC101 - Prof. McLeod
Method Overloading - Cont. • Why bother? – Convenience! • Allows the user to call a method without requiring him to supply values for all the parameters. • One method name can be used with many different types and combinations of parameters. • Allows the programmer to keep an old method definition in the class for “backwards compatibility”. CISC101 - Prof. McLeod
Method Overloading - Cont. • How does it work? • Java looks through all methods until the parameter types match with the list of arguments supplied by the user. If none match, Java tries to cast types in order to get a match. (Only “widening” casting like intto double, however.) CISC101 - Prof. McLeod
Method Overloading - Cont. • Final notes on overloading: • You can have as many overloaded method definitions as you want, as long as they are differentiated by the type and/or number of the parameters listed in the definition. • Note that you cannot use the return type to differentiate overloaded methods. CISC101 - Prof. McLeod
Method Exercise 2 • Add a method (called average) to the class containing your main method that returns, as a double, the average of an array of ints supplied as a parameter. This method should also take two more parameters: the starting and finishing positions in the array, over which to carry out the calculation. • Write an overloaded version of this same method that only has one parameter – just the array. Note that this method only needs one line of code… CISC101 - Prof. McLeod
Method Exercise 2, Cont. • Test the operation of both methods using an array literal. CISC101 - Prof. McLeod
Other Classes in Java • Classes we have used so far: • System • Math • Scanner • JOptionPane • Java has hundreds of other classes scattered over many different libraries (or “packages”) • We don’t have time to visit them all, but… CISC101 - Prof. McLeod
System Class • We have used: • .out object (with print, println and printf methods) • .in object (as a parameter to the Scanner class’ instantiation) • .exit(0) (to halt a program) CISC101 - Prof. McLeod
Other Useful System Class Methods • System.currentTimeMillis() • Returns, as a long, the number of milliseconds elapsed since midnight Jan. 1, 1970. • System.getProperties() • All kinds of system specific info - see the API. • System.getProperty(string) • Displays single system property. • System.nanoTime() • Time in nanoseconds (? Does this work ?) CISC101 - Prof. McLeod
Wrapper Classes • Sometimes it is necessary for a primitive type value to be an Object, rather than just a primitive type. • Some data structures only store Objects. • Some Java methods only work on Objects. • Wrapper classes also contain some useful constants and a few handy methods. CISC101 - Prof. McLeod
Wrapper Classes - Cont. • Each primitive type has an associated wrapper class: • Each wrapper class Object can hold the value that would normally be contained in the primitive type variable, but now has a number of useful static methods. CISC101 - Prof. McLeod
Integer Wrapper Class - Example Integer number = new Integer(46);//”Wrapping” Integer num = new Integer(“908”); Integer.MAX_VALUE // gives maximum integer Integer.MIN_VALUE // gives minimum integer Integer.parseInt(“453”) // returns 453 Integer.toString(653) // returns “653” number.equals(num) // returns false int aNumber = number.intValue(); // aNumber is 46 – “Unwrapping” CISC101 - Prof. McLeod
Aside - Why an “equals” Method for Objects? • The String class also has “equals” and “equalsIgnoreCase”. • These wrapper classes also have an equals method. • Why not use the simple boolean comparators (==, !=, etc.) with Objects? • These comparators just compare memory addresses. • How are you going to sort Objects? CISC101 - Prof. McLeod
Aside - Why an “equals” Method for Objects?, Cont. • == can only compare memory addresses when Objects are compared. • Most Data Container Objects will have both an equals method and a compareTo method. • The equals method tests for equality using whatever you define as “equal”. • The compareTo method returns a postive or negative int value (or zero to indicate “equal”), again depending on how you define one Object to be greater or less than another. CISC101 - Prof. McLeod
Wrapper Classes – Cont. • TheDoublewrapper class has equivalent methods: Double.MAX_VALUE // gives maximum double value Double.MIN_VALUE // gives minimum double value Double.parseDouble(“0.45E-3”) // returns 0.45E-3 • parseDouble is only available in Java 2 and newer versions. CISC101 - Prof. McLeod
Character Wrapper Class • Many useful methods to work on characters: • “character” is a char • getNumericValue(character) • isDigit(character) • isLetter(character) • isLowerCase(character) • isUpperCase(character) • toLowerCase(character) • toUpperCase(character) CISC101 - Prof. McLeod
Wrapper Classes – Summary • Wrapper classes serve a dual purpose: • They can wrap primitive types to make objects out of them. • The have useful static methods. • See the API documentation for more detail on wrapper classes. CISC101 - Prof. McLeod
String Class, So Far • Stringliterals: “Press <enter> to continue.” • Stringvariable declaration: String testStuff; or: String testStuff = “A testing string.”; • Stringconcatenation (“addition”): String testStuff = “Hello”; System.out.println(testStuff + “ to me!”); Would print the following to the console window: Hello to me! CISC101 - Prof. McLeod
String Class, So Far - Cont. • Note that including another type in a String concatenation calls an implicit “toString” method. So, in: System.out.println(“I am “ + 2); the number 2 is converted to a Stringbefore being concatenated. CISC101 - Prof. McLeod
String Class, So Far – Cont. • Escape sequences in Strings: • These sequences can be used to put special characters into a String: \” a double quote \’ a single quote \\ a backslash \n a linefeed \r a carriage return \t a tab character CISC101 - Prof. McLeod
String Class, So Far – Cont. • For example, the code: System.out.println(“Hello\nclass!”); prints the following to the screen: Hello class! CISC101 - Prof. McLeod
String Class, Methods • Since String’s are Objects they can have methods. • Stringmethods include: length() equals(OtherString) equalsIgnoreCase(OtherString) toLowerCase() toUpperCase() trim() charAt(Position) substring(Start) substring(Start, End) CISC101 - Prof. McLeod
String Class, Methods – Cont. indexOf(SearchString) replace(oldChar, newChar) startsWith(PrefixString) endsWith(SuffixString) valueOf(integer) • String’s do not have any attributes. • See the API Docs for details on all the String class methods. • String class methods are notstatic, so you must invoke them from a String object. CISC101 - Prof. McLeod
String Class - Cont. • Examples: int i; boolean aBool; String testStuff = “A testing string.”; i = testStuff.length(); // i is 17 aBool = testStuff.equals(“a testing string.”); // aBool is false aBool = testStuff.equalsIgnoreCase(“A TESTING STRING.”); // aBool is true CISC101 - Prof. McLeod
String Class - Cont. char aChar; aChar = testStuff.charAt(2); // aChar is ‘t’ i = testStuff.indexOf(“test”); // i is 2 CISC101 - Prof. McLeod
Aside - More about String’s • Is “Hello class” (a String literal) an Object? Yup, “Hello class!”.length() would return 12. • String’s are actually stored as arrays of char’s. • So, a String variable is actually just a pointer to an array in memory. CISC101 - Prof. McLeod
StringTokenizer class • This useful class is in the “java.util” package, so you need to have an import java.util.*; or import.java.util.StringTokenizer; statement at the top of your program. • This class provides an easy way of parsing strings up into pieces, called “tokens”. • Tokens are separated by “delimiters”, that you can specify, or you can accept a list of default delimiters. CISC101 - Prof. McLeod
StringTokenizer class - Cont. • The constructor method for this class is overloaded. • So, when you create an Object of type StringTokenizer, you have three options: new StringTokenizer(String s) new StringTokenizer(String s, String delim) new StringTokenizer(String s, String delim, boolean returnTokens) CISC101 - Prof. McLeod
StringTokenizer class - Cont. • s is the String you want to “tokenize”. • delim is a list of delimiters, by default it is: “ \t\n\r” or space, tab, line feed, carriage return. • You can specify your own list of delimiters if you provide a different String for the second parameter. CISC101 - Prof. McLeod
StringTokenizer class - Cont. • If you supply a true for the final parameter, then delimiters will also be provided as tokens. • The default is false - delimiters are not provided as tokens. CISC101 - Prof. McLeod
StringTokenizer class - Cont. • Creating a StringTokenizer Object, for example: String aString = "This is a String - Wow!"; StringTokenizer st = new StringTokenizer(aString); • Now the Object st has inherited a bunch of useful methods from the StringTokenizer class. CISC101 - Prof. McLeod
StringTokenizer class - Cont. • Here is example code using the methods: String aString = "This is a String - Wow!"; StringTokenizer st = new StringTokenizer(aString); System.out.println("The String has " + st.countTokens() + " tokens."); System.out.println("\nThe tokens are:"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } // end while CISC101 - Prof. McLeod
StringTokenizer class - Cont. • Screen output: The String has 6 tokens. The tokens are: This is a String - Wow! CISC101 - Prof. McLeod
Aside - Scanner Class • Also has a built-in tokenizer. • We’ll use this tokenizer when reading text files. CISC101 - Prof. McLeod
StringTokenizer Example • See SystemPropertiesDemo.java. String allProperties = System.getProperties().toString(); System.out.println("\nTokenized string:"); StringTokenizer st = new StringTokenizer(allProperties, ","); while (st.hasMoreTokens()) System.out.println(st.nextToken()); CISC101 - Prof. McLeod
File I/O • Files provide a convenient way to store and re-store to memory larger amounts of data. • We will use arrays to store the data in memory, and we’ll talk about these things later. • Three kinds of file I/O to discuss: • Text • Binary • Random access • For now, we’ll stick with text I/O. CISC101 - Prof. McLeod
Text File Output in Java 5.0 • Use the PrintWriter class. (As usual), you must import the class: import java.io.PrintWriter; • In your program: PrintWriter fileOut = new PrintWriter(outFilename); • (outFilename is a String filename we obtained somewhere else…) CISC101 - Prof. McLeod
Text File Output in Java 5.0, Cont. • Unfortunately the instantiation of the PrintWriter object can cause a FileNotFoundException to be thrown and you must be ready to catch it: try { writeFile = new PrintWriter(outputFile); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(0); } // end try catch CISC101 - Prof. McLeod
Aside – Try/Catch Blocks • I’ve been avoiding them… • An Exception is another way for a method to provide output – in particular an error condition. • Exceptions are not “returned” by a method, instead you have to write code to catch them. • You only catch an exception when there is some kind of error condition. • To catch an exception you must use a “Try/Catch” block: CISC101 - Prof. McLeod
Aside – Try/Catch Blocks, Cont. • Syntax of a “try-catch block”: try { // block of statements that might // generate an exception } catch (exception_type identifer) { // block of statements }[ catch (exception_type identifer) { // block of statements … }][ finally { // block of statements }] CISC101 - Prof. McLeod
Aside – Try/Catch Blocks, Cont. • You must have at least one “catch block” after the “try block” (otherwise the try block would be useless!) • You can have many catch blocks, one for each exception you are trying to catch. • The code in the “finally” block is always executed, whether an exception is thrown, caught, or not. CISC101 - Prof. McLeod
Aside – Try/Catch Blocks, Cont. • A method can throw more than one kind of exception. Why would you want to do this? • You can also include more than one line of code that can throw an exception inside a try block. Why would you not want to do this? CISC101 - Prof. McLeod
Aside – Try/Catch Blocks, Cont. • There are two kinds of exceptions: “checked” and “un-checked” • “Checked” exceptions must be caught – so you must enclose the method that throws a checked exception in a try/catch block – the compiler will force you to do so. • The PrintWriter() constructor throws this kind of exception, so we have to use a try/catch block. • The Scanner class’ nextInt() method throws an InputMismatchException that you don’t have to catch. CISC101 - Prof. McLeod
How to Avoid the Pain!! • The java compiler will tell you if you are attempting to execute code that must be in a try/catch block. • In Eclipse select the line of code that must be put in a try/catch block, then: • Choose “Source” from the main menu, then • Choose “Surround with try/catch Block” CISC101 - Prof. McLeod
Aside – Try/Catch Blocks, Cont. • What to do inside the catch block? • Message to the user describing error. • If you cannot easily fix the problem, then exit the program. • Exceptions and try/catch blocks are not part of the CISC101 syllabus, so they will never be on an exam! • However, for file I/O many problems with files can be encountered! CISC101 - Prof. McLeod
Back to Text File Output in Java 5.0 • Unfortunately the instantiation of the PrintWriter object can cause a FileNotFoundException to be thrown and you must be ready to catch it: try { writeFile = new PrintWriter(outputFile); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(0); } // end try catch CISC101 - Prof. McLeod
Aside - File Paths in Strings • Sometimes you might have to include a path in the filename, such as “C:\Alan\CIS101\Demo.txt” • Don’t forget that if you have to include a “\” in a String, use “\\”, as in: “C:\\Alan\\CISC101\\Demo.txt” CISC101 - Prof. McLeod