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

Slides:



Advertisements
Similar presentations
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Advertisements

Methods Java 5.1 A quick overview of methods
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Written by: Dr. JJ Shepherd
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Fundamental Programming Structures in Java: Strings.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
The Java Programming Language
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 1 Working with strings. Objectives Understand simple programs using character strings and the string library. Get acquainted with declarations,
The java.lang Package chapter 8 Java Certification Study Group February 2, 1998 Seth Ladd.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
Introduction to Exception Handling and Defensive Programming.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
The Math Class Methods Utilizing the Important Math Operations of Java!
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Written by: Dr. JJ Shepherd
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
CSE 110: Programming Language I Afroza Sultana UB 1230.
COP Topics Java Basics - How to write & call your own method - Math methods (static methods) - String methods (instance methods) - Errors Classes.
JAVA MULTIPLE CHOICE QUESTION.
Lecture 14 Throwing Custom Exceptions
Yanal Alahmad Java Workshop Yanal Alahmad
Exceptions, Interfaces & Generics
Why exception handling in C++?
Multiple variables can be created in one declaration
Chapter 5 – Part 2 Methods Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Fundamental Error Handling
Part B – Structured Exception Handling
Object Oriented Programming in java
CMSC 202 Exceptions.
Presentation transcript:

CIS 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…