Java Programming Language



Similar documents
CS 111 Classes I 1. Software Organization View to this point:

Java Programming Fundamentals

AP Computer Science Java Subset

Fundamentals of Java Programming

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Java Interview Questions and Answers

CS506 Web Design and Development Solved Online Quiz No. 01

Chapter 13 - Inheritance

Lecture J - Exceptions

Android Application Development Course Program

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Java Application Developer Certificate Program Competencies

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

RMI Client Application Programming Interface

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Java EE Web Development Course Program

Programmation 2. Introduction à la programmation Java

D06 PROGRAMMING with JAVA

Description of Class Mutation Mutation Operators for Java

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

CS193j, Stanford Handout #10 OOP 3

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Java CPD (I) Frans Coenen Department of Computer Science

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Software Construction

Java from a C perspective. Plan

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Java SE 8 Programming

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

D06 PROGRAMMING with JAVA

Author: Sascha Wolski Sebastian Hennebrueder Tutorials for Struts, EJB, xdoclet and eclipse.

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Java SE 7 Programming

ECE 122. Engineering Problem Solving with Java

C++ INTERVIEW QUESTIONS

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

Hedging. An Undergraduate Introduction to Financial Mathematics. J. Robert Buchanan. J. Robert Buchanan Hedging

Chapter 1 Fundamentals of Java Programming

Computing Concepts with Java Essentials

15-214: Principles of Software Construction 8 th March 2012

Syllabus for CS 134 Java Programming

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Java (12 Weeks) Introduction to Java Programming Language

Exceptions and their interpretation

Web Development in Java

PLV Goldstein 315, Tuesdays and Thursdays, 6:00PM-7:50PM. Tuesdays and Thursdays, 4:00PM-5:30PM and 7:50PM 9:30PM at PLV G320

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

Specialized Programme on Web Application Development using Open Source Tools

Introduction to Object-Oriented Programming

J a v a Quiz (Unit 3, Test 0 Practice)

ICOM 4015: Advanced Programming

Konzepte objektorientierter Programmierung

Objectif. Participant. Prérequis. Remarque. Programme. C# 3.0 Programming in the.net Framework. 1. Introduction to the.

Glossary of Object Oriented Terms

Getting Started with the Internet Communications Engine

Basic Programming and PC Skills: Basic Programming and PC Skills:

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Programming Languages Featherweight Java David Walker

Abstract Class & Java Interface

Java SE 7 Programming

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Java SE 7 Programming

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Inheritance, overloading and overriding

COMMUNITY COLLEGE OF CITY UNIVERSITY CITY UNIVERSITY OF HONG KONG

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces.

Specialized Programme on Web Application Development using Open Source Tools

Java Classes. GEEN163 Introduction to Computer Programming

Checking Access to Protected Members in the Java Virtual Machine

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science

Install Java Development Kit (JDK) 1.8

JAVA IN A NUTSHELL O'REILLY. David Flanagan. Fifth Edition. Beijing Cambridge Farnham Köln Sebastopol Tokyo

Application Programming Interface

Contents. 9-1 Copyright (c) N. Afshartous

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Part I. Multiple Choice Questions (2 points each):

History OOP languages Year Language 1967 Simula Smalltalk

DIPLOMADO DE JAVA - OCA

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Introducing Variance into the Java Programming Language DRAFT

The Interface Concept

TYLER JUNIOR COLLEGE School of Continuing Studies 1530 SSW Loop 323 Tyler, TX

CS170 Lab 11 Abstract Data Types & Objects

Object-Oriented Programming Lecture 2: Classes and Objects

Transcription:

Lecture 1 Part II Java Programming Language Additional Features and Constructs Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani

Subclasses and Inheritance Central to the object-oriented programming paradigm is the ability to add to the functionality of a class by subclassing or extension. To extend a class the key word extends is used, as in the following example: public class StandardStockOption { public double stockprice; public double strikeprice; // other fields public StandardStockOption() { // default constructor // other constructors including all the parameters // getters and setters etc. public double getprice() { BlackScholes bs = new BlackScholes(stockPrice, strikeprice, ); return bs.getprice(); public class ForwardStartStockOption extends StandardStockOption { public double forwardtime; public ForwardStartStockOption(double forwardtime) { super(); // invokes the super class constructor this.forwardtime = forwardtime; //other constructors, e.g. including all the parameters of StandardStockOption public double getprice() { // overriding the getprice method of the superclass if (forwardtime >= timetoexpiration) return 0; // remaining implementation We refer to ForwardStartStockOption as a subclass of StandardStockOption class, or to StandardStockOption class as the superclass of ForwardStartStockOption class. ForwardStartStockOption class inherits the fields and methods of the StandardStockOption class, as the following code segment shows: ForwardStartStockOption fso = new ForwardStartStockOption(1); fso.stockprice = 100; fso.strikeprice = 95; fso.timetoexpiration = 2; double fsoprice = fso.getprice();

Every subclass is a perfectly valid instance of its superclass, therefore any ForwardStartStockOption object can be assigned without a cast to a StandardStockOption variable: ForwardStartStockOption fso = new ForwardStartStockOption(1); StandardStockOption so = fso; // assigned uo to an StandardStockOption variable However, the reverse assignment will require casting: ForwardStartStockOption fso = new ForwardStartStockOption(1); StandardStockOption so = fso; ForwardStartStockOption fso1 = (ForwardStartStockOption)so; // casting needed here The ability to override the methods of the superclass is another essential feature of the object-oriented paradigm. Every Java class has a superclass. If a class is not a direct extension of another class through the extends keyword, then its superclass is java.lang.object class. The java.lang.object class is the only class that does not have a superclass. It is the root of the Object Hierarchy in Java. Java ensures that the constructor method of a class is invoked when an object of a class or any subclass of the class is initialized. If necessary, Java will inserts a call to super() as the first statement in the constructor methods. This continues all the way up the class hierarchy, including the Object class. All Java classes inherit the methods of the Object class, some of which are shown below: public String tostring(); public boolean equals(object obj); public int hashcode(); It is sometimes convenient to override one or more methods inherited from the Object class, as shown in the following modification to the StandardStockOption and the ForwardStartOption classes: public class StandardStockOption { public String tostring() { StringBuffer sb = new StringBuffer(); sb.append( stockprice: + stockprice); sb.append( strikeprice: + strikeprice); return sb.tostring();

public class ForwardStartStockOption extends StandardStockOption { public String tostring() { // overrides tostring method of superclass StringBuffer sb = new StringBuffer(): sb.append(super.tostring()); // invokes the tostring() method of the superclass sb.append( forwardtime: + forwardtime); return sb.tostring(); The special syntax super.tostring() is used to specifically invoke the superclass s tostring method. Abstract Classes and Methods Suppose we wanted to implement a number of options on the stock, such as standard options, binary options, barrier options etc., each with its own special implementation of getprice() method. To work with this array of claims it would make sense to define a common superclass, StockOption: public abstract class StockOption { public double stockprice; public double dividendyield; public double volatility; public double discountrate; public double strikeprice; public double timetoexpiration; public abstract double getprice(); // an abstract method of abstract StockOption class In Java you can define a method without implementing it by using the abstract keyword. Any class containing an abstract method must also be declared an abstract class. An abstract class can not be instantiated. Any extension of an abstract class that does not implement all the abstract methods it inherits must also be declared abstract. Methods that are static, private and final methods can not be declared abstract since they can not be overridden in a subclass. The following is a possible mock-up of the standard option, binary option and barrier option on a stock: public class StandardStockOption extends StockOption { public static final int CALL = 0; public static final int PUT = 1; public double getprice() {

public class BinaryStockOption extends StockOption { // one-touch digital option public double barrier; public double payoff; public double getprice() { public class BarrierStockOption extends StockOption { // standard single barrier option public static final int UP_OUT_CALL = 0; public static final int UP_IN_CALL = 1; public double barrier; public double rebate; public double getprice() { Interfaces Suppose for all one-touch-type options we wanted to set/get barrier level and obtain expected first passage time to the barrier. We can define an abstract OneTouchOption class and extend it, but since Java does not allow multiple inheritance we can not extend the StockOption class as well. Defining an interface, OneTouch, is Java s solution to this: public interface OneTouch { public void setbarrier(double barrier); public double getbarrier(); public double getexpectedfirstpassagetime(); public class BinaryStockOption extends StockOption implements OneTouch { public void setbarrier(double barrier) { this.barrier = barrier; public double getbarrier() { return barrier; public double getexpectedfirstpassagetime() { public class BarrierStockOption extends StockOption implements OneTouch { // similar implementation for barrier options An interface is similar to an abstract class, and is defined using the keyword interface. It

contains no implementation for its methods, which are implicitly abstract, with the keyword abstract omitted. All interface methods must be instance methods and are implicitly public. In a sense an interface provides a pure public API. An interface can contain fields but they must be declared as static and final (i.e. should be a Constant). Like an abstract class an interface can not be instantiated. A class declares an interface in its implements clause. If a class implementing an interface does not provide an explicit implementation for all the interface methods, it must be declared abstract. Java classes can implement multiple interfaces. For example, we wanted to access payoff along a given path for all path-dependent options. We can define: public interface PathDependent { public double getpayoff(double[] pathtimes, double[] pathprices); Now we can make binary and barrier options implement both interfaces: public class BinaryOption extends StockOption implements OneTouch, PathDependent { // implementations of OneTouch interface public double getpayoff(double[] pathtimes, double[] pathprices) { Another possibility is to allow OneTouch interface to extend PathDependent interface, and let these options implement all the methods of OneTouch interface, as shown below: public interface OneTouch extends PathDependent { Here is an example usage of these constructs involving a portfolio consisting of different types of options and making use of Java s instanceof operator: Option[] opts = new StockOption[10]; opts[0] = new StandardStockOption( ); opts[1] = new BarrierStockOption( ); for (int i = 0; i < 10; i++) { System.out.println( price[ + i + ]: + opts[i].getprice()); if (opts[i] instanceof OneTouch) { OneTouch ot = (OneTouch)opts[i]; System.out.println( first passage time[ + i + ]: + ot.getexpectedfirstpassagetime());

Encapsulation, Inheritance and Polymorphism Encapsulation or Data Hiding refers to hiding of the data within the class and making the data only accessed through trusted methods. It helps the programmer hide the inner workings of the class from users, and to ensure proper working of the class against unintentional disruption by the user. For Java class members this implemented by using the access control modifiers: public, protected, private, and package access. public: member is accessible anywhere the class is accessible. private: member is not accessible anywhere, except within the class. protected: member is accessible to all classes within the package and all subclasses regardless of their package. package access: member is accessible only to all classes in the same package. public class Demo { public int field1; // accessible by everyone protected double field2; // accessible to classes in the same package and all subclasses private long field3; // only accessible in Demo class String field4; // accessible to classes in the same package Java classes can be extended through the process of Inheritance. A subclass inherits all non-private instance fields and methods of its superclass that are accessible to it. In particular, for subclasses in a different package only public and protected members are inherited. Note that private fields and methods, class fields and methods, and constructors are never inherited member visibility Accessibility: public protected package private Defining Class Yes Yes Yes Yes Class / same package Yes Yes Yes No Subclass / different package Yes Yes No No Non-subclass / different package Yes No No No

Polymorphism refers to the availability of multiple methods with the same name but different signature within the same Java class: public class Curve { public double interpolate(double time) { public double[] interpolate(double[] times) { Java Exceptions A Java exception is a signal that an error or an exceptional condition has occurred in the Java program. To throw an exception is to indicate occurrence of an exceptional conditional within the program. To catch an exception is to detect it and do whatever handling necessary to recover from it. Every exception in Java is an object. The type of this object is java.lang.throwable or some subclass of Throwable that more specifically handles a given type of exception that has occurred. You can actively throw an exception from a method using the throw statement, as in the following example: public double getprice() { if ( stockprice < 0 ) { throw new IllegalArgumentException( stock price must be positive! ); There are two basic subclasses of Throwable: java.lang.error and java.lang.exception. The subclasses of java.lang.error generally indicate unrecoverable problems during execution. The subclasses of java.lang.exception are generally recoverable these can be generally caught and handled. Java also distinguishes between checked and unchecked exceptions. Any exception object that is an Error is always unchecked. Any exception object of type Exception is checked, except for subclasses of java.lang.runtimeexception, the occurrence of which may not always be predictable. Examples of runtime exceptions in Java are java.lang.nullpointerexception, and java.lang.illegalargumentexception.

Any method that throws a checked exception, or invokes a method that throws such a checked exception, must explicitly indicate so by use of the throws clause in its signature: public static void read(string filename) throws java.io.ioexception { // must throw FileReader reader = new FileReader(filename); The Throwable class has a String field containing the error message, which can be read by invoking the getmessage method once the exception is caught using the try/catch/finally statement: try { read(filename); catch(ioexception e) { System.out.println( error: + e.getmessage()); finally { // do any necessary clean-up

Homework Assignment 1: 1. If you have a laptop and do not already have a Java IDE installed, begin by installing a JBuilder Foundation from www.borland.com: Downloads -> JBuilder -> Select Foundation (Windows, 02/12/05, 51.2-96.5 Mb) 2. Create a new project in JBuilder: Name: course, Directory: z:\ 3. Create the Gaussian class in this project, as discussed in the lecture: Name: Gaussian, Package: edu.columbia.ieor.course.util Write the implementation for pdf() and cdf() methods of the Gaussian class based on the lecture and using the handouts, and Exercise 1: Calculate pdf(x) for values of x in the range [-5,5] in intervals of size 0.2. Exercise 2: Calculate cdf(x) for the same range of x values as above. 4. Create and fully implement StandardStockOption class as discussed in lecture (in edu.columbia.ieor.course.analytic package). Exercise 3: Assume S = 100, K =100, T = 3, r = 0.05, δ = 0.03, σ = 0. 2. Compute the price, delta, gamma, theta, vega, and rho (use numerical calculation for computing all sensitivities) for both standard European call and put options with the following ranges of parameters (in each case keeping other parameters unchanged as given above): Strike price K in the range [80, 120] in steps of 2 Maturity T in the range [0.2, 5] in steps of 0.2 Interest rate r in the range [0, 0.20] in steps of 0.01 Volatility σ in the range [0.02, 0.5] in steps of 0.02 Extra Credit: Create and implement a BarrierStockOption class in the same package and provide implementation for pricing UP_OUT_CALL and DOWN_IN_CALL options, using the pricing formulas provided in the handouts, and using numerical calculations for all sensitivities (delta, gamma, theta, vega, and rho). Assume S = 100, r = 4%, δ = 2%, σ = 15%. Compute the price and sensitivities for: Type Strike Barrier Payoff Expiration Up-Out-Call 100 110 5 2 Down-In-Call 95 90 0 3