Odds and Ends
CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Odds and Ends Some small topics on the side … Basic Exception Handling Class variables (static methods and fields) Command-line arguments Input through JOptionPane
Exceptions
CS 21a 09/18/05 L14: Odds & Ends Slide 4 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Basic Exception Handling Exception: something unexpected that can occur in the execution of a program wrong number format NullPointerException ArrayIndexOutOfBoundsException divide by zero attempt to open a file that does not exist etc. Java provides a way to handle exceptions that are thrown: the try-catch statement
CS 21a 09/18/05 L14: Odds & Ends Slide 5 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Try-catch Statement Syntax: try { … } catch ( Exception e ) {... } Example: try { System.out.println( 5 / x ); } catch ( Exception e ) { System.out.println( “div by zero” ); } Note the formatting convention.
CS 21a 09/18/05 L14: Odds & Ends Slide 6 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Breaking out of the try Block try { statement1; statement2; // if exception occurs here, // statement3 will be skipped statement3; } catch ( Exception e ) { statement4; // executed after exception occurs }
CS 21a 09/18/05 L14: Odds & Ends Slide 7 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Try-catch Chain try { … file operation … } catch( FileNotFoundException se ) { … if file is not found … } catch( EOFException ee ) { … if no more data to read … } catch( IOException e ) { … for all other cases not yet covered … } … you can catch “Exception” to catch any kind of Exception works because of polymorphism OR … You can use a “try-catch chain” to catch specific exceptions
CS 21a 09/18/05 L14: Odds & Ends Slide 8 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Ignoring exceptions Some exceptions do not need to be caught but will generate a runtime error if they occur Examples: NullPointerException, ArrayIndexOutOfBoundsException If enclosed in a try-catch statement, users can choose to handle them Other exceptions need to be caught Examples: when dealing with Input/Output You may either: enclose the statements in a try- catch statement and handle the situation or place the clause throws Exception at the end of the method header (recall console.readLine() example)
CS 21a 09/18/05 L14: Odds & Ends Slide 9 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved More on Exceptions (CS 21b) Stuff we’ll discuss in more detail in CS 21b Different types of Exceptions Generating your own exceptions Other features Don’t worry about these for now!
Class (static) variables and methods
CS 21a 09/18/05 L14: Odds & Ends Slide 11 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Class (static) fields and methods Things we’ve seen, but not fully explained Built-in Constants Math.PI, FlowLayout.CENTER, Color.green, etc. Built-in functions Math.sqrt(), Math.abs(), Integer.parseInt(), Double.isNaN() Static methods public static void main( String[] args ) Static fields your own constants public static final int MY_CONSTANT These are all “static” fields or methods
CS 21a 09/18/05 L14: Odds & Ends Slide 12 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Static Fields means that the field is shared by all instances of the same class aka “class variable” as opposed to “instance variable” e.g., in BankAccount, balance is an “instance variable” – each instance has its own independent copy However, if all BankAccounts share a minimum balance value, we can make a static field for that
CS 21a 09/18/05 L14: Odds & Ends Slide 13 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Example: Minimum Balance Account SV129 Account SV506 Account SV008 balance Account minBalance There is one copy of minBalance for the whole class and shared by all instances. The Account class instances of the Account class
CS 21a 09/18/05 L14: Odds & Ends Slide 14 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Static Methods Normally, a method applies to a particular instance e.g., you can’t just call deposit() from an applet. (Which account are you deposting to?) you have to call aliceAccount.deposit(), where aliceAccount is a pre-existing BankAccount a static method is a method that does not refer to a particular instance That’s why we call them using ClassName.methodName() there’s no instance that “owns” it. It “belongs” to the class in BlueJ, we right-click on the class, not on the instances Useful for “functions” that don’t depend on an instance e.g., Math.sqrt( double d ) Note: they cannot refer to instance variables can only use static fields and methods that’s why convenience methods used by main have to be static
CS 21a 09/18/05 L14: Odds & Ends Slide 15 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved public class BankAccount { private static int curNum = 0; private int balance; public BankAccount( int initBal ) { balance = initBal; BankAccount.curnum++; } public void deposit( int amount ) { balance += amount; } public void withdraw( int amount ) { balance -= amount; } public int getBalance() { return balance; } Another example In this code, we use the static field curNum to keep track of the number of BankAccounts created. Whenever we create a bank account, the value of curNum increases by 1. CurNum is accessible by all instances of BankAccount
Command-Line Arguments
CS 21a 09/18/05 L14: Odds & Ends Slide 17 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Using command-line arguments Arguments entered from the command line e.g. java InputSampler abc 123 “abc” and “123” are command-line arguments public static void main( String[] args ) String[] args stores these arguments args.length = 0 if no arguments are entered args.length = 2 if you run the example above Usage String x = args[0]; //if args.length > 0
CS 21a 09/18/05 L14: Odds & Ends Slide 18 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Using command-line arguments Very easy and straightforward to use. No need to include classes. Only takes in Strings. You will need to convert to ints or doubles, if needed. Works only if you put in command-line arguments. Otherwise, you get an ArrayIndexOutOfBounds exception if you try to access an index that does not exist. Hence, the need to check for the length of the array.
JOptionPane
CS 21a 09/18/05 L14: Odds & Ends Slide 20 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Using JOptionPane import javax.swing.*; String showInputDialog( String prompt ) Usage: String x = JOptionPane.showInputDialog ( “Enter string: ” );
CS 21a 09/18/05 L14: Odds & Ends Slide 21 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Using JOptionPane Provides a nice GUI window for user to provide input, when in a Java application Need to import javax.swing to use it Only takes in Strings. You will need to convert to ints or doubles, if needed. Need to call System.exit( 0 ); at the last line of main() so that the program exits