1 / 50

Java Method Overloading and Math Class Basics

Learn about method overloading in Java, using the Math class for various calculations, and exception handling. Get hands-on experience with examples and explore the capabilities of the Math class.

galli
Télécharger la présentation

Java Method Overloading and Math Class Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CIS3931 - Intro to JAVA Lecture Notes Set 5 26-May-05

  2. 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.

  3. 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.

  4. Is this correct? • int MyMethod(int x) • double MyMethod(int a) • Are these two methods allowed together?

  5. 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

  6. 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

  7. Rounding in Math Class • ceil – round up to nearest integer • floor – round down to nearest integer

  8. 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

  9. 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.

  10. 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.

  11. 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

  12. 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)

  13. 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.

  14. 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

  15. 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

  16. 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; } }

  17. Exceptions : Throw / Catch • Result : Exception in thread “main” java.lang.ArithmeticException: / by zero at DivideByZero.main(DivideByZero.java:14)

  18. 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

  19. 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 }

  20. 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.

  21. 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

  22. Exception handling … • Example program … • “Finally” statements • Users can create user defined exceptions … • … will go over this next class.

  23. Scanner • Good news, Scanner can now be used on program since 1.5 was added. This can be used instead of Buffered Readers.

  24. 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;

  25. 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);

  26. 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();

  27. 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();

  28. 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.

  29. 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.

  30. Scanner & Strings • To grab a String using Scanner, just use the following: Scanner input = new Scanner(System.in); String name = input.nextLine();

  31. 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.

  32. 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.

  33. 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!

  34. 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”

  35. equals() • Returns a boolean value – true or false • Check to see if 2 strings are equal if( st1.equals(st2) ) System.out.println(“Equal”);

  36. equals() • The equals() method takes case into consideration. To ignore case, yet still check for equals you should use: equalsIgnoreCase()

  37. length() • Returns the length of the String • Example: String st1 = “Hello” int Stlen = st1.length(); //Stlen now equals 5

  38. trim() • Removes all leading and trailing whitespace characters. This does not remove any whitespace characters in the middle, just at either end.

  39. Conversions • toLowerCase() • toUpperCase() These convert the String to upper/lower case letters and ignore all the nonalphabetic characters.

  40. 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.

  41. Main • For instance, if the program was started with: java Project foo bar Then args[0] = foo & args[1] = bar args.length = 2

  42. 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

  43. 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

  44. Creating Objects • Objects are created from a class using the new operator. • They must be attached to a reference variable.

  45. 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();

  46. Using the object • Square MySquare = new Square(); • MySquare.side = 10; • The above sets side to 10.

  47. Constructors • Special member function of a class. • Purpose is to initialize the members of an object.

  48. 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.

  49. 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

  50. 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…

More Related