The return Statement

Size: px
Start display at page:

Download "The return Statement"

Transcription

1 The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return statement, say main()); reaches a return statement; throws an exception (introduced later). As you can see, the return statement is not necessarily at the bottom of the method. 1 Once one defines the return type (except void), the method should guarantee to return a value or an object of that type. 1 Thanks to a lively discussion on November 22, Zheng-Liang Lu Java Programming 195 / 242

2 Bad Exampls static int fun1() { 3 while (true); 4 return 0; //unreachable code 5 } 6 7 static int fun2(int x) { 8 if (x > 0) { 9 return x; 10 } 11 // what if x < 0? 12 } Zheng-Liang Lu Java Programming 196 / 242

3 Method Invocation Note that the input parameters are sort of variables declared within the method as placeholders. When calling the method, one needs to provide arguments, which must match the parameters in order, number, and compatible type, as defined in the method signature. Zheng-Liang Lu Java Programming 197 / 242

4 In Java, method invocation uses pass-by-value. When the callee is invoked, the program control is transferred from the caller to the callee. For each invocation of methods, OS creates an frame which stores necessary information, and the frame is pushed in the call stack. The callee transfers the program control back to the caller once the callee finishes its job. Zheng-Liang Lu Java Programming 198 / 242

5 Zheng-Liang Lu Java Programming 199 / 242

6 Variable Scope The variable scope is the region where the variable can be referenced in the program. Variables can be declared in class level, method level, and loop level. In general, a balanced curly brackets defines a particular scope. One cannot declare the variables with the same name in the same scope. Zheng-Liang Lu Java Programming 200 / 242

7 1 public class ScopeDemo { 2 Example 3 static int i = 1; // class level 4 5 public static void main(string[] args) { 6 System.out.printf("%d\n", i); //output 1 7 int i = 2; // method level; local 8 i++; 9 System.out.printf("%d\n", i); // output 3 10 p(); 11 System.out.printf("%d\n", i); // output? 12 } static void p() { 15 i = i + 1; 16 System.out.printf("%d\n", i); // output? 17 } 18 } What if p(int i) in Line 14? 2 2 Thanks to a lively discussion on January 20, Zheng-Liang Lu Java Programming 201 / 242

8 A Math Toolbox: Math Class The Math class provides basic mathematical functions and 2 global constants Math.PI 3 and Math.E 4. 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! 3 The constant π is a mathematical constant, the ratio of a circle s circumference to its diameter, commonly approximated as The constant e is the base of the natural logarithm. It is approximately equal to Zheng-Liang Lu Java Programming 202 / 242

9 Method Overloading Methods with the same name can coexist and be identified by the method signatures static int max(int x, int y) {... } 3 // different numbers of inputs 4 static int max(int x, int y, int z) {... } 5 // different types 6 static double max(double x, double y) {... } 7... Zheng-Liang Lu Java Programming 203 / 242

10 Recursion 5 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. 5 Recursion is a commom pattern in nature. Zheng-Liang Lu Java Programming 204 / 242

11 Try Fractal. Zheng-Liang Lu Java Programming 205 / 242

12 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! = 24. Can you find the pattern? n! = n (n 1)! In general, f (n) = n f (n 1). Zheng-Liang Lu Java Programming 206 / 242

13 Write a program which determines n! 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? Zheng-Liang Lu Java Programming 207 / 242

14 Zheng-Liang Lu Java Programming 208 / 242

15 Equivalence: Loop Version 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. 6 6 The Church-Turing Thesis proves it if the memory serves. Zheng-Liang Lu Java Programming 209 / 242

16 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. Zheng-Liang Lu Java Programming 210 / 242

17 Memory Layout Zheng-Liang Lu Java Programming 211 / 242

18 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 F n = F n 1 + F n 2, where F 0 = 0, F 1 = 1, and n 2. Zheng-Liang Lu Java Programming 212 / 242

19 static int fib(int n) { 3 if (n > 1) 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?!) Zheng-Liang Lu Java Programming 213 / 242

20 Zheng-Liang Lu Java Programming 214 / 242

21 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 } 10 return y; 11 } else return (n == 1)? y : x; 12 } 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? You may try more examples. 7 7 See Zheng-Liang Lu Java Programming 215 / 242

22 Divide and Conquer For program development, we use the divide-and-conquer strategy 8 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 8 Aka stepwise refinement. Zheng-Liang Lu Java Programming 216 / 242

23 Computational Thinking 9 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. 9 You should read this: Zheng-Liang Lu Java Programming 217 / 242

24 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. Zheng-Liang Lu Java Programming 218 / 242

25 Example: Abstraction of Computer System Zheng-Liang Lu Java Programming 219 / 242

26 Example: Methods as Control Abstraction Zheng-Liang Lu Java Programming 220 / 242

27 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. Zheng-Liang Lu Java Programming 221 / 242

28 1 class Lecture7 { 2 3 // Objects and Classes 4 5 } 6 7 // Key words: 8 class, new, this, static, null, extends, super, abstract, final, interface, implements, protected Zheng-Liang Lu Java Programming 222 / 242

29 Observations for Real Objects Look around. We can easily find many examples for real-world objects. For example, a person and his/her bottle of water. Real-world objects all have states and behaviors. What possible states can the object be in? What possible behaviors can the object perform on the states? 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. Zheng-Liang Lu Java Programming 223 / 242

30 Software Objects An object keeps 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 other OO features are inheritance and polymorphism, which we will see later. Zheng-Liang Lu Java Programming 224 / 242

31 Classes We often find many individual objects all of the same kind. For example, each bicycle was built from the same blueprint so that each 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. Zheng-Liang Lu Java Programming 225 / 242

32 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 10 Point p2 = new Point(); 11 p2.x = 3; 12 p2.y = 4; 13 System.out.printf("(%d, %d)\n", p2.x, p2.y); 14 } 15 } Zheng-Liang Lu Java Programming 226 / 242

33 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. Zheng-Liang Lu Java Programming 227 / 242

34 Data Members The fields are the states of the object. The field may have an access modifier, say public and private. public: accessible from all classes private: accessible only within its own class You can decide if these fields are accessible! In practice, all fields should be declared private. However, this private modifier does not quarantine any security. 10 What private is good for maintainability and modularity Thanks to a lively discussion on January 23, Read are-private-members-really-more-secure-in-java. Zheng-Liang Lu Java Programming 228 / 242

35 Function Members As said, the fields are hidden. 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 one mutator in the class Point. Zheng-Liang Lu Java Programming 229 / 242

36 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; } 10 void setpoint(double a, double b) { 11 x = a; 12 y = b; 13 } 14 } Zheng-Liang Lu Java Programming 230 / 242

37 Unified Modeling Language 12 Unified Modeling Language (UML) is a tool for specifying, visualizing, constructing, and documenting the artifacts of software systems, as well as for business modeling and other non-software systems. Free software: (available for all platforms) 12 See and Zheng-Liang Lu Java Programming 231 / 242

38 Example: Class Diagram for Point Modifiers can be placed before the fields and the methods: + for public for private Zheng-Liang Lu Java Programming 232 / 242

39 Constructors A constructor is called by the new operator. A constructor acts like other methods. However, its names should be identical to the name of the class and it has no return type. A class may have several constructors if needed. Constructors can be overloaded. Note that the constructors are used only during the objection creation. Constructors cannot be invoked by any object. If you don t define any explicit constructor, Java assumes a default constructor for your class. Moreover, adding any explicit constructor disables the default constructor. Zheng-Liang Lu Java Programming 233 / 242

40 Parameterized Constructors You can provide specific information to the parameterized constructor during the object creation. For example, 1 class Point { Point() {} // restore a default constructor; 5 6 // parameterized constructor 7 Point(double a, double b) { 8 x = a; 9 y = b; 10 } } Zheng-Liang Lu Java Programming 234 / 242

41 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(). Zheng-Liang Lu Java Programming 235 / 242

42 Example: Point (Revisited) 1 class Point { Point(int x, int y) { 4 this.x = x; 5 this.y = y; 6 } } Note that the this operator cannot be used in static methods. Zheng-Liang Lu Java Programming 236 / 242

43 Instance Members and Static Members You may notice that, until now, all members are declared w/o static. It means that each object has its own values with behaviors. The aforesaid members are called instance members. Note that these instance members are available only after the object is created. Zheng-Liang Lu Java Programming 237 / 242

44 Zheng-Liang Lu Java Programming 238 / 242

45 Static Members The static members belong to the class 13, and are shared between the instance objects. In other word, there is only one copy of the static members, no matter how many objects of the class are created. They are ready once the class is loaded. They can be invoked directly by the class name without using any instance. For example, Math.random(). 13 Aka class members. Zheng-Liang Lu Java Programming 239 / 242

46 A static method can access other static members. (Trivial.) However, static methods cannot access to instance members directly. (Why?) For example, 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 // You cannot access to x and y directly! 8 return Math.sqrt(Math.pow(p1.x p2.x, 2) + Math.pow(p1. y p2.y, 2)); 9 } Zheng-Liang Lu Java Programming 240 / 242

47 Example: Count of Points 1 class Point { private static int numofpoint = 0; 4 5 Point() { 6 numofpoint++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument; should be placed in the first line in the constructor 11 this.x = x; 12 this.y = y; 13 } } Zheng-Liang Lu Java Programming 241 / 242

48 Exercise: Singleton 14 In some situations, you may create the only instance of the class. 1 class Singleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static Singleton instance = new Singleton(); 5 6 // Do now allow to invoke the constructor by other classes. 7 private Singleton() {} 8 9 // Only way to obtain the singleton from the outside world. 10 public static Singleton getsingleton() { 11 return instance; 12 } 13 } 14 See any textbook for design patterns. Zheng-Liang Lu Java Programming 242 / 242

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

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226 Method Invocation Note that the input parameters are sort of variables declared within the method as placeholders. When calling the method, one needs to provide arguments, which must match the parameters

More information

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

Recursion 1. Recursion is the process of defining something in terms of itself. Recursion 1 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

More information

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

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University 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

More information

Example: Fibonacci Numbers

Example: Fibonacci Numbers 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

More information

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

1 class Lecture6 { 2 3 Methods // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244 1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 // keywords: 8 return Zheng-Liang Lu Java Programming 186 / 244 Methods 2 Methods can be used to define reusable code, and organize and simplify code. The idea

More information

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

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Exercise Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Zheng-Liang Lu Java Programming 197 / 227 1... 2 int[] hist = new int[5]; 3 //

More information

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

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;

More information

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

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 1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248 All roads lead to Rome. Anonymous 但如你根本並無招式, 敵人如何來破你的招式? 風清揚,

More information

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

Variable Scope. The variable scope is the range of the program where the variable can be referenced. Variable Scope The variable scope is the range of the program where the variable can be referenced. Variables can be declared in class level, method level, and loop level. In general, a pair of curly brackets

More information

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 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 Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize

More information

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

1 class Lecture4 { 2 3 Loops / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207 1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207 Loops A loop can be used to make a program execute statements repeatedly without having

More information

Instance Members and Static Members

Instance Members and Static Members 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

More information

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.

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. Scope of Variables The variables used in function m-files are known as local variables. Any variable defined within the function exists only for the function to use. The only way a function can communicate

More information

Example. Password generator

Example. Password generator Example Password generator Write a program which generates ten characters as a password. There may be lower-case letters, upper-case letters, and digital characters in the character sequence. Recall that

More information

Lecture 5: Methods CS2301

Lecture 5: Methods CS2301 Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

More information

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

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x

More information

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

1 class Lecture5 { 2 3 Arrays 4. Zheng-Liang Lu Java Programming 136 / 174 1 class Lecture5 { 2 3 "Arrays" 4 5 } Zheng-Liang Lu Java Programming 136 / 174 Arrays An array stores a large collection of data which is of the same type. 2 // assume the size variable exists above 3

More information

How to swap values of two variables without tmp? However, this naive algorithm is biased. 1

How to swap values of two variables without tmp? However, this naive algorithm is biased. 1 Shuffling over array elements 1... 2 for (int i = 0; i < A.length; ++i) { 3 // choose j randomly 4 int j = (int) (Math.random() A.length); 5 // swap 6 int tmp = A[i]; 7 A[i] = A[j]; 8 A[j] = tmp; 9 } 10...

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Exercise: Singleton 1

Exercise: Singleton 1 Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance

More information

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225 1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225 Functions The first thing of the design of algorithms is to divide and conquer. A large and complex problem would be solved by couples

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Lecture #6-7 Methods

Lecture #6-7 Methods Lecture #6-7 s 1. a. group of statements designed to perform a specific function b. may be reused many times i. in a particular program or ii. in multiple programs 2. Examples from the Java Library a.

More information

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

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion Lecture 13 1 What is? A method of programming in which a method refers to itself in order to solve a problem Never necessary In some situations, results in simpler and/or easier-to-write code Can often

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

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

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java. Classes Introduce to classes and objects in Java. Classes and Objects in Java Understand how some of the OO concepts learnt so far are supported in Java. Understand important features in Java classes.

More information

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

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Lecture 3. Lecture

Lecture 3. Lecture True Object-Oriented programming: Dynamic Objects Static Object-Oriented Programming Reference Variables Eckel: 30-31, 41-46, 107-111, 114-115 Riley: 5.1, 5.2 D0010E Object-Oriented Programming and Design

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 7&8: Methods Lecture Contents What is a method? Static methods Declaring and using methods Parameters Scope of declaration Overloading

More information

Methods. CSE 114, Computer Science 1 Stony Brook University

Methods. CSE 114, Computer Science 1 Stony Brook University Methods CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Opening Problem Find multiple sums of integers: - from 1 to 10, - from 20 to 30, - from 35 to 45,... 2

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;

More information

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited Chapter 6 Methods Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from

More information

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise

More information

CS18000: Programming I

CS18000: Programming I CS18000: Programming I Data Abstraction January 25, 2010 Prof. Chris Clifton Announcements Book is available (Draft 2.0) Syllabus updated with readings corresponding to new edition Lab consulting hours

More information

CS110: PROGRAMMING LANGUAGE I

CS110: PROGRAMMING LANGUAGE I CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 8: Methods Lecture Contents: 2 Introduction Program modules in java Defining Methods Calling Methods Scope of local variables Passing Parameters

More information

Object-Based Programming. Programming with Objects

Object-Based Programming. Programming with Objects ITEC1620 Object-Based Programming g Lecture 8 Programming with Objects Review Sequence, Branching, Looping Primitive datatypes Mathematical operations Four-function calculator Scientific calculator Don

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion 2. Recursion Algorithm Two Approaches to Algorithms (1) Iteration It exploits while-loop, for-loop, repeat-until etc. Classical, conventional, and general approach (2) Recursion Self-function call It exploits

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

Nested Loops. A loop can be nested inside another loop.

Nested Loops. A loop can be nested inside another loop. Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.5: Methods A Deeper Look Xianrong (Shawn) Zheng Spring 2017 1 Outline static Methods, static Variables, and Class Math Methods with Multiple

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

CS-201 Introduction to Programming with Java

CS-201 Introduction to Programming with Java CS-201 Introduction to Programming with Java California State University, Los Angeles Computer Science Department Lecture IX: Methods Introduction method: construct for grouping statements together to

More information

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University Opening Problem Chapter 6: Methods Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively CS1: Java Programming Colorado State University Original slides by Daniel Liang

More information

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

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Functions: Program modules in C Function Definitions Function

More information

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

Methods: A Deeper Look

Methods: A Deeper Look 1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number

More information

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi Chapter 4 Loops for while do-while Last Week Chapter 5 Methods Input arguments Output Overloading Code reusability Scope of

More information

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 34. Recursion Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Example: Factorials Example: Fibonacci Numbers Recursion vs. Iteration References Introduction Introduction Recursion

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 26 March 23, 2016 Inheritance and Dynamic Dispatch Chapter 24 Inheritance Example public class { private int x; public () { x = 0; } public void incby(int

More information

Comments are almost like C++

Comments are almost like C++ UMBC CMSC 331 Java Comments are almost like C++ The javadoc program generates HTML API documentation from the javadoc style comments in your code. /* This kind of comment can span multiple lines */ //

More information

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

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

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

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 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

CS11 Introduction to C++ Fall Lecture 2

CS11 Introduction to C++ Fall Lecture 2 CS11 Introduction to C++ Fall 2006-2007 Lecture 2 Instances, Pointers, References Variable-declarations are straightforward int i; double d = 53.217; Pointers are indicated with * in the type int *pint;

More information

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.! True object-oriented programming: Dynamic Objects Reference Variables D0010E Object-Oriented Programming and Design Lecture 3 Static Object-Oriented Programming UML" knows-about Eckel: 30-31, 41-46, 107-111,

More information

Chapter 5 Methods / Functions

Chapter 5 Methods / Functions Chapter 5 Methods / Functions 1 Motivations A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a

More information

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i

More information

Anatomy of a Class Encapsulation Anatomy of a Method

Anatomy of a Class Encapsulation Anatomy of a Method Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions instance data encapsulation and

More information

Programming Language Pragmatics

Programming Language Pragmatics Chapter 10 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken Alan Turing, Alonzo Church, Stephen

More information

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

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal COMSC-051 Java Programming Part 1 Part-Time Instructor: Joenil Mistal Chapter 4 4 Moving Toward Object- Oriented Programming This chapter provides a provides an overview of basic concepts of the object-oriented

More information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, import, new 1 class Lecture2 { 2 3 Data types, Variables, and Operators 4 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44

More information

Object-Oriented Programming Concepts

Object-Oriented Programming Concepts Object-Oriented Programming Concepts Object-oriented programming מונחה עצמים) (תכנות involves programming using objects An object ) represents (עצם an entity in the real world that can be distinctly identified

More information

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides 1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of

More information

Advanced Computer Programming

Advanced Computer Programming Programming in the Large I: Methods (Subroutines) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University

More information

Creating an object Instance variables

Creating an object Instance variables Introduction to Objects: Semantics and Syntax Defining i an object Creating an object Instance variables Instance methods What is OOP? Object-oriented programming (constructing software using objects)

More information

CS11 Intro C++ Spring 2018 Lecture 1

CS11 Intro C++ Spring 2018 Lecture 1 CS11 Intro C++ Spring 2018 Lecture 1 Welcome to CS11 Intro C++! An introduction to the C++ programming language and tools Prerequisites: CS11 C track, or equivalent experience with a curly-brace language,

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #13: Java OO cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Homework due next week Problem #2 revisited Constructors, revisited Remember: a

More information

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 5 Methods rights reserved. 0132130807 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. rights reserved. 0132130807 2 1 Problem int sum =

More information

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming

More information

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

More information

CS115 Principles of Computer Science

CS115 Principles of Computer Science CS115 Principles of Computer Science Chapter 5 Methods Prof. Joe X. Zhou Department of Computer Science CS115 Methods.1 Re: Objectives in Loops Sequence and selection aside, we need repetition (loops)

More information

Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

More information

Exercise (Revisited)

Exercise (Revisited) Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 1... 2 while (true) { 3 System.out.println("Enter price?"); 4 price = input.nextint(); 5 if (price

More information

Making New instances of Classes

Making New instances of Classes Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods CS1150 Principles of Computer Science Methods Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Find the sum of integers from 1 to

More information

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

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems Basics of OO Programming with Java/C# Basic Principles of OO Abstraction Encapsulation Modularity Breaking up something into smaller, more manageable pieces Hierarchy Refining through levels of abstraction

More information

Answers to review questions from Chapter 2

Answers to review questions from Chapter 2 Answers to review questions from Chapter 2 1. Explain in your own words the difference between a method and a program. A method computes a value or performs some operation on behalf of the code for a program.

More information

Object Oriented Methods : Deeper Look Lecture Three

Object Oriented Methods : Deeper Look Lecture Three University of Babylon Collage of Computer Assistant Lecturer : Wadhah R. Baiee Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces,

More information

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() { Scoping, Static Variables, Overloading, Packages In this lecture, we will examine in more detail the notion of scope for variables. We ve already indicated that variables only exist within the block they

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Chapter 6 Methods. Dr. Hikmat Jaber

Chapter 6 Methods. Dr. Hikmat Jaber Chapter 6 Methods Dr. Hikmat Jaber 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i

More information

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i

More information

ECOM 2324 COMPUTER PROGRAMMING II

ECOM 2324 COMPUTER PROGRAMMING II ECOM 2324 COMPUTER PROGRAMMING II Object Oriented Programming with JAVA Instructor: Ruba A. Salamh Islamic University of Gaza 2 CHAPTER 9 OBJECTS AND CLASSES Motivations 3 After learning the preceding

More information

Lecture 10 Declarations and Scope

Lecture 10 Declarations and Scope Lecture 10 Declarations and Scope Declarations and Scope We have seen numerous qualifiers when defining methods and variables public private static final (we'll talk about protected when formally addressing

More information

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

Java Programming 2. Zheng-Liang Lu. Java2 304 Fall Department of Computer Science & Information Engineering National Taiwan University Java Programming 2 Zheng-Liang Lu Department of Computer Science & Information Engineering National Taiwan University Java2 304 Fall 2018 1 class Lecture7 { 2 3 // Object Oriented Programming 4 5 } 6 7

More information

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Java We will be programming in Java in this course. Partly because it is a reasonable language, and partly because you

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, import, new 1 class Lecture2 { 2 3 Data types, Variables, and Operators 4 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44

More information

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

More information

Global Variables. ˆ Unlike local variables, global variables are available to all functions involved.

Global Variables. ˆ Unlike local variables, global variables are available to all functions involved. Global Variables ˆ Unlike local variables, global variables are available to all functions involved. ˆ Use global to declare x as global. ˆ For example, the universal constant, say,. 1 ˆ However, it is

More information

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net COURSE ORGANIZATION 2 Course Elements Lectures: 10 lectures Find schedule and class rooms in online

More information