Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CIS3931 - Intro to JAVA Lecture Notes Set 5 26-May-05 Method Overloading • Enables methods to have the same name • They must have different parameter lists • The parameter list allows the compiler/interpreter to distinguish between which to use. Method Overloading Example • int MyMethod(int x) • int MyMethod(double y) • int MyMethod(int a, double b) • Since they all have different parameter lists, they can all be used in the same class and an error will not be raised. Is this correct? • int MyMethod(int x) • double MyMethod(int a) • Are these two methods allowed together? Math Class • Very useful. Provides many methods in a pre-built class. • The following are available in the Math class • Trigonometry functions: sin, cos, tan, acos, atan, asin Exponent Methods • • • • exp – raise e to a power sqrt – returns the square root pow – raise a number to a power log – natural log of a number Rounding in Math Class • ceil – round up to nearest integer • floor – round down to nearest integer Helpful Math • random – Returns a random number greater than or equal to 0.0 and less than 1.0 • abs – return absolute value of a number • min – return minimum of two numbers • max – return max of two numbers Advice • The previous were all important, but are only half of what the Math class can actually do. Make sure you know how to use the methods I mentioned here. How to call them, and what they do. I would recommend playing around with the Math class and experimenting with at least the ones mentioned. View the API for the Math class. Exception Handling • What is an exception? – An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program. • In normal programming, an exception or error would cause a program to crash. Exception Handling • JAVA offers methods to handle exceptions • Exception objects – Created by a method when an error occurs. This object contains information about the error (type, state of program when error occurred …) • Creating an exception object = throwing an exception Exception Handling • When an exception is thrown, the system trying to find a way to handle it. • The system searches through the ordered list of methods that have been called prior to the exception (call stack) Exception Handling • Block of code than can handle exception = exception handler • An exception handler must be able to handle the type of exception thrown • A chose exception handler “catches” the exception • If no handler is found, the program will terminate. Exceptions • Some reasons an exception may be thrown … – Unable to open a file – Array is out of range – Dividing by zero – Unable to parse a stream Exceptions : Throw / Catch • Similar to the raise/handle model in other languages • Exceptions are caused in one of two ways – Program does something illegal – Program execute the “throw” keyword Exceptions : Throw / Catch • The following code will crash a program … public class DivideByZero { public static void main(String[] args) { int i = 1, j =0, k; //Force an error … k = i / j; } } Exceptions : Throw / Catch • Result : Exception in thread “main” java.lang.ArithmeticException: / by zero at DivideByZero.main(DivideByZero.java:14) Exceptions : Throw / Catch • Error message shows that a “ArithmeticException” was thrown by the program • Program died because there was no exception handler available to catch the exception • Use a try / catch block to handle the exception Exceptions : Throw / Catch Try / Catch Block example try { //Some block of code that you could potentially //throw an exception } catch (Exception e) { //Block of code to handle the exception } Exceptions : Throw / Catch • When an exception is thrown in the try block, control is immediately passed to the associated catch block. • Try blocks must have at least one catch block (sometimes multiple are needed). • Every catch block must have one try block associated with it. Throw / Catch : Advantages • Error conditions dealt with only where it makes sense to deal with them – Don’t have to deal with error at ever level between occurrence and where it is handled • Code can be written as if everything will work – Separates error handling from the normal flow of control • Reduced program complexity – Calling functions do not need to error check returned values Exception handling … • Example program … • “Finally” statements • Users can create user defined exceptions … • … will go over this next class. Scanner • Good news, Scanner can now be used on program since 1.5 was added. This can be used instead of Buffered Readers. Scanner • Scanner is contained in java.util.Scanner • You will have to import that class if you wish to use Scanner. import java.util.Scanner; Scanner • You must first create Scanner to obtain input from command window. • This is done with the following command: Scanner input = new Scanner(System.in); Scanner • Next, you must parse the input into something meaningful, as it is now of type Scanner. The example below shows how to parse it into an int int num1 = input.nextInt(); Scanner Example import java.util.Scanner; //Class and main declarations Scanner input = new Scanner( System.in ); System.out.print(“Enter digit: “); int num1 = input.nextInt(); Scanner Exceptions • With Scanner, you do not need to throw any Exceptions as you do with Buffered Readers. In other words, you do not need the throws Exception after declaring main. Strings • You have already played around with Strings somewhat… String input = br.readLine(); The above says to create a String variable called input and place the input from the Buffered Reader into it. Scanner & Strings • To grab a String using Scanner, just use the following: Scanner input = new Scanner(System.in); String name = input.nextLine(); Strings overview • A String is an object in Java, it comes from the String class • The String class is part of java.lang and doesn’t need to be imported since java.lang is imported automatically with every java program. String Methods • There are over 50 different methods which can be called when you use the String class. Some of the more important ones follow. charAt() • This returns the char at the location you specify. String greet = new String(“Hello”); greet.charAt(1); //returns e Remember, you must start counting at 0! concat() • This concatenates one string to another string. • Example: String st1 = “Hello”; String st2 = “ World”; String st3 = st1.concat(st2); //st3 now equals “Hello World” equals() • Returns a boolean value – true or false • Check to see if 2 strings are equal if( st1.equals(st2) ) System.out.println(“Equal”); equals() • The equals() method takes case into consideration. To ignore case, yet still check for equals you should use: equalsIgnoreCase() length() • Returns the length of the String • Example: String st1 = “Hello” int Stlen = st1.length(); //Stlen now equals 5 trim() • Removes all leading and trailing whitespace characters. This does not remove any whitespace characters in the middle, just at either end. Conversions • toLowerCase() • toUpperCase() These convert the String to upper/lower case letters and ignore all the nonalphabetic characters. Main • Recall the following: public static void main( String args[] ) The String args[] that is in the parameters is an array of Strings. This is so the user can enter input to start the program. Main • For instance, if the program was started with: java Project foo bar Then args[0] = foo & args[1] = bar args.length = 2 Objects • Encapsulation of Data along with functions that act upon that data • An object consists of 3 things: 1. Name – which we give it 2. Attributes – set of data fields and their current values 3. Methods – set of methods that define the behavior of the object Class • Blueprint for objects • Describes and defines objects of the same type • Contains data and method declarations • An object is a single instance of a class • You can create many objects from the same class type Creating Objects • Objects are created from a class using the new operator. • They must be attached to a reference variable. Example • Suppose we have a class we built called Square. Inside we have methods for computing area and circumference. • Format: Square MySquare; My Square = new Square(); Or Square MySquare = new Square(); Using the object • Square MySquare = new Square(); • MySquare.side = 10; • The above sets side to 10. Constructors • Special member function of a class. • Purpose is to initialize the members of an object. How to spot a constructor? • It’s very simple since it must meet the following criteria: 1. It has the same name as the class 2. It has no return type. Default Constructor • A constructor without any parameters is the default constructor. • A constructor can have parameters, but no return type. • A constructor is invoked when an object is created with new. MySquare = new Square() //default MySquare = new Square(2) //also valid Visibility • We can declare members of a class to be public or private. • Public can be accessed inside or outside of the class it is in. • Private can only be used by the object itself. • You can hide data this way for security, simpler interface, etc…