Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

Similar documents
The return Statement

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Recursion 1. Recursion is the process of defining something in terms of itself.

Example: Fibonacci Numbers

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244

1 class Lecture6 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

Instance Members and Static Members

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

Exercise: Singleton 1

Example: Count of Points

Example: Count of Points

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Example. Password generator

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Scope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

ITI Introduction to Computing II

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Object-Oriented Programming Concepts

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Lecture 5: Methods CS2301

ITI Introduction to Computing II


Pace University. Fundamental Concepts of CS121 1

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Object Oriented Programming in C#

CS18000: Programming I

Chapter 4 Defining Classes I

Object-Based Programming. Programming with Objects

CS 231 Data Structures and Algorithms, Fall 2016

Java Programming 2. Zheng-Liang Lu. Java2 304 Fall Department of Computer Science & Information Engineering National Taiwan University

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Course Outline. Introduction to java

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

inside: THE MAGAZINE OF USENIX & SAGE August 2003 volume 28 number 4 PROGRAMMING McCluskey: Working with C# Classes

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Chapter 6 Introduction to Defining Classes

Programming Language Pragmatics

Lecture #6-7 Methods

Comments are almost like C++

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Example: Monte Carlo Simulation 1

Java Programming 2. Zheng-Liang Lu. Java2 306 Fall Department of Computer Science & Information Engineering National Taiwan University

CS11 Intro C++ Spring 2018 Lecture 1

Chapter 15: Object Oriented Programming

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

JAVA: A Primer. By: Amrita Rajagopal

BBM 102 Introduction to Programming II Spring 2017

Building custom components IAT351

1.00 Lecture 5. Objects

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

What is Inheritance?

Creating an object Instance variables

Chapter 2: Java OOP I

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Introduction to Programming Using Java (98-388)

Software Design and Analysis for Engineers

Lecture 2 and 3: Fundamental Object-Oriented Concepts Kenneth M. Anderson

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

CSE 8B Programming Assignments Spring Programming: You will have 5 files all should be located in a dir. named PA3:

Programming II (CS300)

Lecture 3. Lecture

C++ Important Questions with Answers

Objects as a programming concept

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

CS110: PROGRAMMING LANGUAGE I

PIC 20A The Basics of Java

Computer Science II (20073) Week 1: Review and Inheritance

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Java Review. Fundamentals of Computer Science

CS-202 Introduction to Object Oriented Programming

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

CLASSES AND OBJECTS IN JAVA

Lecture 6 Introduction to Objects and Classes

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

The Object Oriented Paradigm

IMACS: AP Computer Science A

Programming for Engineers in Python

Advanced Computer Programming

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

G Programming Languages - Fall 2012

Methods: A Deeper Look

CS260 Intro to Java & Android 03.Java Language Basics

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Transcription:

Java Programming U Hou Lok Department of Computer Science and Information Engineering, National Taiwan University Java 272 8 19 Aug., 2016 U Hou Lok Java Programming 1 / 51

A Math Toolbox: Math Class The Math class provides basic mathematical functions and 2 global constants Math.PI 1 and Math.E 2. All methods are public and static. For example, max, min, round, ceil, floor, abs, pow, exp, sqrt, cbrt, log, log10, sin, cos, asin, acos, and random. Full document for Math class can be found here. You are expected to read the document! 1 π is a mathematical constant, the ratio of a circle s circumference to its diameter, commonly approximated as 3.141593. 2 e is the base of the natural logarithm. It is approximately equal to 2.71828. U Hou Lok Java Programming 2 / 51

Method Overloading Overloading methods enables us to define the methods with the same name as long as their signatures are different. This can make programs clearer and more readable. Name conflict is fine. Make sure the signatures differ; the overloaded methods work on different input parameters. Note that you cannot overload methods merely based on different modifiers or return types. U Hou Lok Java Programming 3 / 51

Example (Revisit) Printing stars Rewrite a program which outputs a certain number of lines with some symbol determined by the user. Also, the program repeats itself until the input number is negative. Use * if the input for the symbol is left blank. U Hou Lok Java Programming 4 / 51

1... 2 static void print(int n) { 3 for (int i = 1; i <= n; i++) { 4 for (int j = 1; j <= i; j++) { 5 System.out.printf(" "); 6 } 7 System.out.println(); 8 } 9 } 0 1 static void print(int n, String m) { 2 for (int i = 1; i <= n; i++) { 3 for (int j = 1; j <= i; j++) { 4 System.out.printf("%s", m); 5 } 6 System.out.println(); 7 } 8 } 9... U Hou Lok Java Programming 5 / 51

1... 2 while (true) { 3 System.out.println("Enter n =?"); 4 n = input.nextint(); 5 if (n > 0) { 6 System.out.println("Enter a symbol?"); 7 m = input.next(); 8 if (m.equals("")) print(n); 9 else print(n, m); 0 } else { 1 System.out.println("Bye."); 2 break; 3 } 4 } 5... The method next() returns a string from the keyboard. The method equals() is a String method used to compare if the two strings are identical. U Hou Lok Java Programming 6 / 51

Recursion 3 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is repetition without any loop. 3 Recursion is a commom pattern in nature. U Hou Lok Java Programming 7 / 51

Try Fractal. U Hou Lok Java Programming 8 / 51

Example The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than and equal to n. Note that 0! = 1. For example, 4! = 4 3 2 1 = 4 3! = 24. Can you find the pattern? n! = n (n 1)! In general, f (n) = n f (n 1). U Hou Lok Java Programming 9 / 51

Write a program which determines n!. 1... 2 static int factorial(int n) { 3 if (n > 0) { 4 return n factorial(n 1); 5 } else { 6 return 1; // base case 7 } 8 } 9... Note that there must be a base case in recursion. Time complexity: O(n) Can you implement the same method by using a loop? U Hou Lok Java Programming 10 / 51

U Hou Lok Java Programming 11 / 51

Equivalence: Loop Version 1... 2 int s = 1; 3 for (int i = 2; i < = n; i++) { 4 s = i; 5 } 6... Time complexity: O(n) One intriguing question is, Can we always turn a recursive method into a loop version of that? Yes, theoretically. 4 4 The Church-Turing Thesis proves it if the memory serves. U Hou Lok Java Programming 12 / 51

Remarks Recursion bears substantial overhead. So the recursive algorithm may execute a bit more slowly than the iterative equivalent. Additionally, a deeply recursive method depletes the call stack, which is limited, and causes stack overflow soon. U Hou Lok Java Programming 13 / 51

Memory Layout U Hou Lok Java Programming 14 / 51

Example Fibonacci numbers Write a program which determines F n, the (n +1)-th Fibonacci number. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. The sequence of Fibonacci numbers can be defined by the recurrence relation where F 0 = 0, F 1 = 1, and n 2. F n = F n 1 + F n 2, U Hou Lok Java Programming 15 / 51

1... 2 static int fib(int n) { 3 if (n > 0) return fib(n 1) + fib(n 2); 4 else if (n == 1) return 1; 5 else return 0; 6 } 7... This recursive implementation is straightforward. Yet, this algorithm isn t efficient since it requires more time and memory. Time complexity: O(2 n ) (Why?!) You may check Master Theorem. 5 5 See https://math.dartmouth.edu/archive/m19w03/public_html/section5-2.pdf. U Hou Lok Java Programming 16 / 51

U Hou Lok Java Programming 17 / 51

1... 2 static double fibiter(int n) { 3 int x = 0, y = 1; 4 if (n >= 2) { 5 for (int i = 2; i < n; ++i) { 6 int tmp = x + y; 7 x = y; 8 y = tmp; 9 } 0 return y; 1 } else return (n == 1)? y : x; 2 } 3... So it can be done in O(n) time. It implies that the recursive one is not optimal. Could you find a linear recursion for Fibonacci numbers? U Hou Lok Java Programming 18 / 51

Divide and Conquer For program development, we use the divide-and-conquer strategy 6 to decompose the original problem into subproblems, which are more manageable. For example, selection sort. Pros: easier to write, reuse, debug, modify, maintain, and also better facilitating teamwork 6 Aka stepwise refinement. U Hou Lok Java Programming 19 / 51

Program Development: Waterfall Model U Hou Lok Java Programming 20 / 51

Computational Thinking 7 To think about computing, we need to be attuned to three fields: science, technology, and society. Computational thinking shares with mathematical thinking: the way to solve problems engineering thinking: the way to design and evaluating a large, complex system scientific thinking: the way to understand computability, intelligence, the mind and human behavior. 7 You should read this: http://rsta.royalsocietypublishing.org/content/366/1881/3717.full U Hou Lok Java Programming 21 / 51

Computational Thinking Is Everywhere! The essence of computational thinking is abstraction. An algorithm is an abstraction of a step-by-step procedure for taking input and producing some desired output. A programming language is an abstraction of a set of strings each of which when interpreted effects some computation. And more. The abstraction process, which is to decide what details we need to highlight and what details we can ignore, underlies computational thinking. The abstraction process also introduces layers. Well-defined interfaces between layers enable us to build large, complex systems. U Hou Lok Java Programming 22 / 51

Example: Abstraction of Computer System U Hou Lok Java Programming 23 / 51

Example: Methods as Control Abstraction U Hou Lok Java Programming 24 / 51

Abstraction (Concluded) Control abstraction is the abstraction of actions while data abstraction is that of data structures. One can view the notion of an object as a way to combine abstractions of data and code. U Hou Lok Java Programming 25 / 51

1 class Lecture7 { 2 3 // Objects and Classes 4 5 } 6 7 // Reserved words: 8 class, new, this, extends, super, interface, implements, abstract, static, protected, null, default, final 9 // References: Ch.5 6 in Learning Java U Hou Lok Java Programming 26 / 51

Observations for Real Objects Look around. We can easily find many examples for real-world objects. For example, students and an instructor. Real-world objects all have states and behaviors. What possible states can the object be in? What possible behaviors can the object perform? Identifying these states and behaviors for real-world objects is a great way to begin thinking in object-oriented programming. From now, OO is a shorthand for object-oriented. U Hou Lok Java Programming 27 / 51

Software Objects An object stores its states in fields and exposes its behaviors through methods. Plus, internal states are hidden and the interactions to the object are only performed through an object s methods. This is so-call encapsulation, which is one of OO features. Note that the OO features are encapsulation, inheritance, and polymorphism. U Hou Lok Java Programming 28 / 51

Classes We often find many individual objects all of the same kind. For example, each bicycle was built from the same set of blueprints and therefore contains the same components. In OO terms, we say that your bicycle is an instance of the class of objects known as Bicycle. A class is the blueprint to create class instances which are runtime objects. Classes are the building blocks of Java applications. U Hou Lok Java Programming 29 / 51

Example: Points in 2D Coordinate 1 class Point { 2 double x, y; // fields: data member 3 } 1 public class PointDemo { 2 public static void main(string[] args) { 3 // now create a new instance of Point 4 Point p1 = new Point(); 5 p1.x = 1; 6 p1.y = 2; 7 System.out.printf("(%d, %d)\n", p1.x, p1.y); 8 9 // create another instance of Point 0 Point p2 = new Point(); 1 p2.x = 3; 2 p2.y = 4; 3 System.out.printf("(%d, %d)\n", p2.x, p2.y); 4 } 5 } U Hou Lok Java Programming 30 / 51

Class Definition First, give a class name with the first letter capitalized, by convention. The class body, surrounded by balanced braces {}, contains data members (fields) and function members (methods) for objects. We may need an entry point to run the program if the class is used to run the whole program. U Hou Lok Java Programming 31 / 51

Data Members The fields are the states of the object. May have an access modifier, say public and private. public: accessible from all classes private: accessible only within its own class Access modifiers realize encapsulation! In other words, you can decide if these fields are accessible! In OO practice, all the fields should be declared private. U Hou Lok Java Programming 32 / 51

Function Members As said, the fields are hidden by encapsulation. So we may need accessors and mutators if necessary. Accessors: return the state of the object Mutators: set the state of the object For example, getx() and gety() are accessors, and setpoint(double, double) is a mutator in the class Point. U Hou Lok Java Programming 33 / 51

Example: Point (Encapsulated) 1 class Point { 2 private double x; 3 private double y; 4 5 double getx() { return x; } 6 double gety() { return y; } 7 8 void setx(double a) { x = a; } 9 void sety(double a) { y = a; } 0 void setpoint(double a, double b) { 1 x = a; 2 y = b; 3 } 4 } U Hou Lok Java Programming 34 / 51

Example: Class Diagram for Point Modifiers are placed before the fields and the methods: + for public for private U Hou Lok Java Programming 35 / 51

Constructors A constructor is called by the new operator. Constructors are like special methods except that they use the name of the class and have no return type. Note that the constructors are not the part of the instances. Like other methods, the constructors can also be overloaded. If you don t define an explicit constructor, Java assumes a default constructor for your class. Moreover, adding any explicit constructor disables the default constructor. U Hou Lok Java Programming 36 / 51

Parameterized Constructors You can provide specific information to the parameterized constructor as the object is instantiated. For example, 1 class Point { 2... 3 4 Point() {} // restore a default constructor; 5 6 // parameterized constructor 7 Point(double a, double b) { 8 x = a; 9 y = b; 0 } 1... 2 } U Hou Lok Java Programming 37 / 51

Example: Point (Revisited) 1 public class PointDemo { 2 public static void main(string[] args) { 3 Point p1 = new Point(1, 2); 4 System.out.printf("(%f, %f)", p1.getx(), p1.gety()); 5 // output (1, 2) 6 } 7 } U Hou Lok Java Programming 38 / 51

Self-reference You can refer to any (instance) member of the current object within methods and constructors by using this. The most common reason for using the this keyword is because a field is shadowed by method parameters. You can also use this to call another constructor in the same class by invoking this(). U Hou Lok Java Programming 39 / 51

Example: Point (Revisited) 1 class Point { 2... 3 Point(int x, int y) { 4 this.x = x; 5 this.y = y; 6 } 7... 8 } Note that the this operator is referenced to instance members only, but not members declared static. U Hou Lok Java Programming 40 / 51

Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these instance members are available only when the object is created. Those declared w/ static are static members, aka class members. U Hou Lok Java Programming 41 / 51

Static Members Static members mean that there is only one copy of the static members, no matter how many objects of the class are created. The static members belong to the class, and are shared between the instance objects. They are ready once the class is loaded. They can be invoked directly by the class name without creating an instance. For example, Math.random(). U Hou Lok Java Programming 42 / 51

A static method can access other static members. However, static methods cannot access to instance members directly. (Why?) For example, 1... 2 double getdistancefrom(point p) { 3 return Math.sqrt(Math.pow(this.x p.x, 2) + Math.pow(this.y p.y, 2)); 4 } 5 6 static double distancebetween(point p1, Point p2) { 7 return Math.sqrt(Math.pow(p1.x p2.x, 2) + Math.pow(p1.y p2. y, 2)); 8 } 9... U Hou Lok Java Programming 43 / 51

Example: Count of Points 1 class Point { 2... 3 private static int cnt = 0; 4 5 Point() { 6 cnt++; 7 } 8 9 Point(int x, int y) { 0 this(); // calling the constructor with no input argument; should be placed in the first line in the constructor 1 this.x = x; 2 this.y = y; 3 } 4 5... 6 } U Hou Lok Java Programming 44 / 51

Garbage Collection (GC) 8 Java handles deallocation automatically. Automatic garbage collection is the process of looking at the heap memory, identifying whether or not the objects are in use, and deleting the unreferenced objects. An object is said to be unreferenced if the object is no longer referenced by any part of your program. Simply assign null to the reference-type variable to make the object referenced by this variable unreferenced. So the memory used by these objects can be reclaimed. 8 http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/ index.html U Hou Lok Java Programming 45 / 51

finalize() Method The method finalize() conducts a specific task that will be executed as soon as the object is about to be reclaimed by GC. The finalize() method can be only invoked prior to GC. In practice, it must not rely on the finalize() method for normal operations. (Why?) U Hou Lok Java Programming 46 / 51

Example 1 public class finalizedemo { 2 static int numofpointkilled = 0; 3 4 public void finalize() { 5 numofpointkilled++; 6 } 7 8 public static void main(string[] args) { 9 double n = 1e7; 0 for (int i = 1; i <= n; i++) 1 new finalizedemo(); 2 System.out.println(numOfPointKilled); 3 } 4 } You may try different number for instance creation. The number of the objects reclaimed by GC is not deterministic. U Hou Lok Java Programming 47 / 51

HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all objects have their own lifecycle, but there is ownership and child objects do not belong to another parent object. For example, knight sword Composition is a specialized form of aggregation and we can call this as a death relationship. For example, house room U Hou Lok Java Programming 48 / 51

Example: Lines on 2D Cartesian Coordinate +2: Line object contains two Point objects. U Hou Lok Java Programming 49 / 51

More Examples More geometric objects, say Circle, Triangle, and Polygon. Complex number (a + bi) equipped with + and so on. Book with Authors. Lecturer and Students in the classroom. Zoo with many creatures, say Dog, Cat, and Bird. Channels played on TV. U Hou Lok Java Programming 50 / 51

More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to the outside world Packages: grouping related types, providing access protection and name space management U Hou Lok Java Programming 51 / 51