Download presentation
Presentation is loading. Please wait.
Published byElfrieda Barber Modified over 6 years ago
1
Last Time (Midterm Exam!) Before that – methods. Spring 2006
CISC101 - Prof. McLeod
2
Announcements Assn 2 due tonight. Spring 2006 CISC101 - Prof. McLeod
3
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 Spring 2006 CISC101 - Prof. McLeod
4
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.) Spring 2006 CISC101 - Prof. McLeod
5
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”. Spring 2006 CISC101 - Prof. McLeod
6
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 int to double, however.) Spring 2006 CISC101 - Prof. McLeod
7
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. Spring 2006 CISC101 - Prof. McLeod
8
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… Spring 2006 CISC101 - Prof. McLeod
9
Method Exercise 2, Cont. Test the operation of both methods using an array literal. Spring 2006 CISC101 - Prof. McLeod
10
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… Spring 2006 CISC101 - Prof. McLeod
11
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) Spring 2006 CISC101 - Prof. McLeod
12
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 ?) Spring 2006 CISC101 - Prof. McLeod
13
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. Spring 2006 CISC101 - Prof. McLeod
14
Wrapper Classes - Cont. char Character int Integer long Long float
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. char Character int Integer long Long float Float double Double Spring 2006 CISC101 - Prof. McLeod
15
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” Spring 2006 CISC101 - Prof. McLeod
16
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? Spring 2006 CISC101 - Prof. McLeod
17
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. Spring 2006 CISC101 - Prof. McLeod
18
Wrapper Classes – Cont. The Double wrapper 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. Spring 2006 CISC101 - Prof. McLeod
19
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) Spring 2006 CISC101 - Prof. McLeod
20
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. Spring 2006 CISC101 - Prof. McLeod
21
String Class, So Far String literals:
“Press <enter> to continue.” String variable declaration: String testStuff; or: String testStuff = “A testing string.”; String concatenation (“addition”): String testStuff = “Hello”; System.out.println(testStuff + “ to me!”); Would print the following to the console window: Hello to me! Spring 2006 CISC101 - Prof. McLeod
22
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 String before being concatenated. Spring 2006 CISC101 - Prof. McLeod
23
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 Spring 2006 CISC101 - Prof. McLeod
24
String Class, So Far – Cont.
For example, the code: System.out.println(“Hello\nclass!”); prints the following to the screen: Hello class! Spring 2006 CISC101 - Prof. McLeod
25
String Class, Methods Since String’s are Objects they can have methods. String methods include: length() equals(OtherString) equalsIgnoreCase(OtherString) toLowerCase() toUpperCase() trim() charAt(Position) substring(Start) substring(Start, End) Spring 2006 CISC101 - Prof. McLeod
26
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 not static, so you must invoke them from a String object. Spring 2006 CISC101 - Prof. McLeod
27
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 Spring 2006 CISC101 - Prof. McLeod
28
String Class - Cont. char aChar;
aChar = testStuff.charAt(2); // aChar is ‘t’ i = testStuff.indexOf(“test”); // i is 2 Spring 2006 CISC101 - Prof. McLeod
29
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. Spring 2006 CISC101 - Prof. McLeod
30
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. Spring 2006 CISC101 - Prof. McLeod
31
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) Spring 2006 CISC101 - Prof. McLeod
32
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. Spring 2006 CISC101 - Prof. McLeod
33
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. Spring 2006 CISC101 - Prof. McLeod
34
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. Spring 2006 CISC101 - Prof. McLeod
35
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 Spring 2006 CISC101 - Prof. McLeod
36
StringTokenizer class - Cont.
Screen output: The String has 6 tokens. The tokens are: This is a String - Wow! Spring 2006 CISC101 - Prof. McLeod
37
Aside - Scanner Class Also has a built-in tokenizer.
We’ll use this tokenizer when reading text files. Spring 2006 CISC101 - Prof. McLeod
38
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()); Spring 2006 CISC101 - Prof. McLeod
39
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. Spring 2006 CISC101 - Prof. McLeod
40
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…) Spring 2006 CISC101 - Prof. McLeod
41
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 Spring 2006 CISC101 - Prof. McLeod
42
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: Spring 2006 CISC101 - Prof. McLeod
43
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) { … }][ finally { }] Spring 2006 CISC101 - Prof. McLeod
44
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. Spring 2006 CISC101 - Prof. McLeod
45
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? Spring 2006 CISC101 - Prof. McLeod
46
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. Spring 2006 CISC101 - Prof. McLeod
47
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” Spring 2006 CISC101 - Prof. McLeod
48
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! Spring 2006 CISC101 - Prof. McLeod
49
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 Spring 2006 CISC101 - Prof. McLeod
50
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” Spring 2006 CISC101 - Prof. McLeod
51
Text File Output in Java 5.0, Cont.
The Object writeFile, owns a couple of familiar methods: print() and println(). When you are done writing, don’t forget to close the file with: writeFile.close(); Way easy!! Spring 2006 CISC101 - Prof. McLeod
52
Text File Input in Java 5.0 Use the FileReader and Scanner classes. Our usual import statements: import java.util.Scanner; import java.io.FileReader; import java.io.FileNotFoundException; We’ll get to that last one in a minute. Spring 2006 CISC101 - Prof. McLeod
53
Text File Input in Java 5.0, Cont.
In a program: fileIn = new FileReader("Test.txt"); Scanner fileInput = new Scanner(fileIn); Unfortunately the FileReader constructor (what’s a “constructor” anyways?) throws a kind of exception that cannot be ignored - so the code above cannot be used exactly in this way. Spring 2006 CISC101 - Prof. McLeod
54
Text File Input in Java 5.0, Cont.
This works: FileReader fileIn = null; try{ fileIn = new FileReader("Test.txt"); } catch (FileNotFoundException e) { // Do something useful here? Scanner fileInput = new Scanner(fileIn); Spring 2006 CISC101 - Prof. McLeod
55
Text File Input in Java 5.0, Cont.
To get the file contents, and print them to the console, for example: while (fileInput.hasNextLine()) { System.out.println(fileInput.nextLine()); } Spring 2006 CISC101 - Prof. McLeod
56
Aside - Scanner Class’ Tokenizer
The Scanner class has a built in String Tokenizer. Set the delimiters using the useDelimiter(delimiter_String) method. Obtain the tokens by calling the next() method. The hasNext() method will return false when there are no more tokens. Spring 2006 CISC101 - Prof. McLeod
57
Text File I/O Sample Programs
TextFileIODemo.java Saves a file with text provided by the user and then opens the file again and displays the contents to the screen. TextFileIODemoWithChooser.java Same program as above except the use of the JFileChooser class is demonstrated as an alternate means of getting a filename from the user. Spring 2006 CISC101 - Prof. McLeod
58
Without using FileReader
You can also send a File object to the Scanner class when you instantiate it instead of a FileReader object. You will still need to do this in a try catch block as shown in the previous slide. See the second demo program. Spring 2006 CISC101 - Prof. McLeod
59
The File Class File is a class in the java.io.* package.
It contains useful utility methods that will help prevent programs crashing from file errors. For example: File myFile = new File(“test.dat”); myFile.exists(); // returns true if file exists myFile.canRead(); // returns true if can read from file myFile.canWrite(); // returns true if can write to file Spring 2006 CISC101 - Prof. McLeod
60
The File Class, Cont. myFile.delete(); // deletes file and returns true if successful myFile.length(); // returns length of file in bytes myFile.getName(); // returns the name of file (like “test.dat”) myFile.getPath(); // returns path of file (like “C:\AlanStuff\JavaSource”) Spring 2006 CISC101 - Prof. McLeod
61
The File Class, Cont. All of these methods can be used without having to worry about try/catch blocks, which is nice! See the second demo program for a few examples of File class method use. Spring 2006 CISC101 - Prof. McLeod
62
Binary and Random Access
Binary files contain data exactly as it is stored in memory – you can’t read these files in Notepad! Text file is sequential access only. What does that mean? Random access can access any byte in the file at any time, in any order. More about Binary and Random File Access later! Spring 2006 CISC101 - Prof. McLeod
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.