Methods (Deitel chapter 6)
|
|
- Angela Price
- 5 years ago
- Views:
Transcription
1 Methods (Deitel chapter 6) 1
2 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods of Class JApplet Method Overloading Recursion Example Using Recursion: The Fibonacci Series Recursion vs. Iteration
3 3 Introduction Modules Small pieces of a problem e.g., divide and conquer Facilitate design, implementation, operation and maintenance of large programs
4 4 Program Modules in Java Modules in Java Methods Classes Java API provides several modules Programmers can also create modules e.g., programmer-defined methods Methods Invoked by a method call Returns a result to calling method (caller) Similar to a boss (caller) asking a worker (called method) to complete a task The declarations and statements within braces form the method body.
5 5 boss worker1 worker2 worker3 worker4 worker5 Hierarchical boss-method/worker-method relationship.
6 6 Math-Class Methods Class java.lang.math Provides common mathematical calculations Calculate the square root of 900.0: Math.sqrt( ) Method sqrt belongs to class Math Dot (.) allows access to method sqrt The argument is located inside parentheses Math class is part of java.lang (automatically imported by the compiler)
7 7 Method Description Example abs( x ) absolute value of x (this method also has float, int and long versions) abs( 23.7 ) is 23.7 abs( 0.0 ) is 0.0 abs( ) is 23.7 ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x (x is in radians) cos( 0.0 ) is 1.0 exp( x ) exponential method ex exp( 1.0 ) is exp( 2.0 ) is floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0 floor( -9.8 ) is log( x ) natural logarithm of x (base e) log( Math.E ) is 1.0 log( Math.E * Math.E ) is 2.0 max( x, y ) larger value of x and y (this method also has float, int and long versions) max( 2.3, 12.7 ) is 12.7 max( -2.3, ) is -2.3 min( x, y ) smaller value of x and y (this method also has float, int and long versions) min( 2.3, 12.7 ) is 2.3 min( -2.3, ) is pow( x, y ) x raised to the power y (xy) pow( 2.0, 7.0 ) is pow( 9.0, 0.5 ) is 3.0 sin( x ) trigonometric sine of x (x is in radians) sin( 0.0 ) is 0.0 sqrt( x ) square root of x sqrt( ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x (x is in radians) tan( 0.0 ) is 0.0 Fig. 6.2 Math-class methods.
8 8 Methods Declarations Methods Allow programmers to modularize programs Makes program development more manageable (divide-and-conquer) Software reusability (using existing methods as building blocks) Avoid repeating code Local variables Declared in method declaration Parameters Communicates information between methods via method calls
9 Method Declarations (cont.) 9 General format of method declaration: return-value-type method-name( parameter1, parameter2,, parametern ) { declarations and statements } Method can also return values: return expression;
10 25 double max = maximum( number1, number2, number3 ); // method call. 39 Method maximum returns value 40 } // end method init from method max of class Math // maximum method uses Math class method max to help 43 // determine maximum value 44 public double maximum( double x, double y, double z ) 45 { 46 return Math.max( x, Math.max( y, z ) ); } // end method maximum } // end class Maximum Outline Maximum.java 10 Line 25 When maximum method is called a copy of the args is made and program control tranfers to 1st line of method maximum. Method receives a copy of the values in the parameters x,y,z. Line 46 Method maximum returns value from method max of class Math
11 Notes 11 Omitting the return-vale-type in a method definition is a syntax error Forgetting to return a value from a method that is supposed to return a value is a syntax error Returning a value from a method whose return type has been declared void is a syntax error Types are required for each parameter in the method
12 Notes 12 All variables declared in method definitions are local variables Redefining a method parameter as a local variable in the method is a syntax error Methods should be small (half/1 page) Methods can return at most one value
13 Argument Promotion 13 Coercion of arguments Forcing arguments to appropriate type to pass to method e.g., System.out.println( Math.sqrt( 4 ) ); Evaluates Math.sqrt( 4 ) Then evaluates System.out.println() Promotion rules Specify how to convert types without data loss Converting a primitive type to another primitive type may change the value if the new type is not an allowed promotion
14 14 Type Valid promotions double None float double long float or double int long, float or double char int, long, float or double short int, long, float or double byte short, int, long, float or double boolean None (boolean values are not considered to be numbers in Java) Fig. 6.5 Allowed promotions for primitive types.
15 Java API Packages 15 Packages Classes grouped into categories of related classes Promotes software reuse import statements specify classes used in Java programs e.g., import javax.swing.japplet;
16 16 Package java.applet Description The Java Applet Package contains the Applet class and several interfaces that enable applet/browser interaction and the playing of audio clips. In Java 2, class javax.swing.japplet is used to define an applet that uses the Swing GUI components. java.awt The Java Abstract Window Toolkit Package contains the classes and interfaces required to create and manipulate GUIs in Java 1.0 and 1.1. In Java 2, the Swing GUI components of the javax.swing packages are often used instead. java.awt.event The Java Abstract Window Toolkit Event Package contains classes and interfaces that enable event handling for GUI components in both the java.awt and javax.swing packages. java.io The Java Input/Output Package contains classes that enable programs to input and output data (see Chapter 17, Files and Streams). java.lang The Java Language Package contains classes and interfaces (discussed throughout this text) that are required by many Java programs. This package is imported by the compiler into all programs. java.net java.text The Java Networking Package contains classes that enable programs to communicate via networks (see Chapter 18, Networking). The Java Text Package contains classes and interfaces that enable a Java program to manipulate numbers, dates, characters and strings. The package provides many of Java s internationalization capabilities that enable a program to be customized to a specific locale (e.g., an applet may display strings in different languages, based on the user s country). java.util The Java Utilities Package contains utility classes and interfaces, such as date and time manipulations, randomnumber processing capabilities with class Random, storing and processing large amounts of data and breaking strings into smaller pieces called tokens with class StringTokenizer (see Chapter 20; Data Structures, Chapter 21, Java Utilities Package and Bit Manipulation; and Chapter 22, Collections). javax.swing The Java Swing GUI Components Package contains classes and interfaces for Java s Swing GUI components that provide support for portable GUIs. javax.swing.event Fig. 6.6 Java API packages (a subset). The Java Swing Event Package contains classes and interfaces that enable event handling for GUI components in package javax.swing.
17 Random-Number Generation 17 Java random-number generators Math.random() ( int ) ( Math.random() * 6 ) Produces integers from 0-5 Use a seed for different random-number sequences
18 18 Scope of Declarations Scope (of identifiers: var, ref, method) Portion of the program that can reference an entity by its name Basic scope rules Scope of a local-variable declaration Scope of a local-variable declaration that appears in the initialization section of a for statement s header Scope of a method or field of a class
19 1 // Fig. 6.10: Scoping.java 2 // A scoping example. 3 import java.awt.container; 4 5 import javax.swing.*; 6 7 public class Scoping extends JApplet { 8 JTextArea outputarea; 9 10 // field that is accessible to all methods of this class 11 int x = 1; // create applet's GUI 14 public void init() 15 { 16 outputarea = new JTextArea(); 17 Container container = getcontentpane(); 18 container.add( outputarea ); } // end method init // method start called after init completes; start calls 23 // methods uselocal and usefield 24 public void start() 25 { Field x has class scope Local variable x has block scope Method start uses local variable x 26 int x = 5; // local variable in method start that shadows field x outputarea.append( "local x in start is " + x ); 29 Outline Scoping.java Line 11 field x Line 26 Local variable x Line 28 Method start uses local variable x 19
20 30 uselocal(); // uselocal has local x 31 usefield(); // useinstance uses Scoping's field x 32 uselocal(); // uselocal reinitializes local x 33 usefield(); // Scoping's field x retains its value outputarea.append( "\n\nlocal x in start is " + x ); } // end method start // uselocal creates and initializes Re-create local variable variable x x during each call 40 public void uselocal() and initialize it to { 42 int x = 25; // initialized each time uselocal is called outputarea.append( "\n\nlocal x in uselocal is " + x + 45 " after entering uselocal" ); 46 ++x; 47 outputarea.append( "\nlocal x in uselocal is " + x + 48 " before exiting uselocal" ); } // end method uselocal 51 Outline Scoping.java Line 42 Recreate variable x and initialize it to 25 Lines Method uselocal uses local variable x Method uselocal uses local variable x 20
21 52 // usefield modifies Scoping's field x during each call 53 public void usefield() 54 { 55 outputarea.append( "\n\nfield x is " + x + 56 " on entering usefield" ); 57 x *= 10; 58 outputarea.append( "\nfield x is " + x + 59 " on exiting usefield" ); } // end method useinstance } // end class Scoping Outline Scoping.java Lines Method usefield Method usefield uses field x uses field x 21
22 22 Methods of Class JApplet Java API defines several JApplet methods Defining methods of Fig in a JApplet is called overriding those methods.
23 23 Method public void init() When the method is called and its purpose This method is called once by the applet container when an applet is loaded for execution. It performs initialization of an applet. Typical actions performed here are initializing fields, creating GUI components, loading sounds to play, loading images to display (see Chapter 19, Multimedia) and creating threads (see Chapter 16, Multithreading). public void start() This method is called after the init method completes execution. In addition, if the browser user visits another Web site and later returns to the HTML page on which the applet resides, method start is called again. The method performs any tasks that must be completed when the applet is loaded for the first time and that must be performed every time the HTML page on which the applet resides is revisited. Typical actions performed here include starting an animation (see Chapter 19) and starting other threads of execution (see Chapter 16). public void paint( Graphics g ) This drawing method is called after the init method completes execution and the start method has started. It is also called every time the applet needs to be repainted. For example, if the user covers the applet with another open window on the screen and later uncovers the applet, the paint method is called. Typical actions performed here involve drawing with the Graphics object g that is passed to the paint method by the applet container. public void stop() public void destroy() This method is called when the applet should stop executing normally, when the user of the browser leaves the HTML page on which the applet resides. The method performs any tasks that are required to suspend the applet s execution. Typical actions performed here are to stop execution of animations and threads. This method is called when the applet is being removed from memory normally, when the user of the browser exits the browsing session (i.e., closes all browser windows). The method performs any tasks that are required to destroy resources allocated to the applet. Fig JApplet methods that the applet container calls during an applet s execution.
24 24 Method Overloading Method overloading Several methods of the same name Different parameter set for each method Number of parameters Parameter types
25 1 // Fig. 6.12: MethodOverload.java 2 // Using overloaded methods 3 import java.awt.container; 4 5 import javax.swing.*; 6 7 public class MethodOverload extends JApplet { 8 9 // create GUI and call each square method 10 public void init() 11 { 12 JTextArea outputarea = new JTextArea(); 13 Container container = getcontentpane(); 14 container.add( outputarea ); outputarea.settext( "The square of integer 7 is " + square( 7 ) + 17 "\nthe square of double 7.5 is " + square( 7.5 ) ); } // end method init // square method with int argument 22 public int square( int intvalue ) 23 { Method square receives an int as an argument 24 System.out.println( "Called square with int argument: " + 25 intvalue ); return intvalue * intvalue; } // end method square with int argument 30 Outline 25 MethodOverload. java Lines Method square receives an int as an argument
26 31 // square method with double argument 32 public double square( double doublevalue ) 33 { 34 System.out.println( "Called square with double argument: " + 35 doublevalue ); return doublevalue * doublevalue; } // end method square with double argument } // end class MethodOverload Outline 26 MethodOverload. java Lines Overloaded method Overloaded method square square receives a receives a double as an argument double as an argument Called square with int argument: 7 Called square with double argument: 7.5
27 1 // Fig. 6.13: MethodOverload.java 2 // Overloaded methods with identical signatures. 3 import javax.swing.japplet; 4 5 public class MethodOverload extends JApplet { 6 7 // declaration of method square with int argument 8 public int square( int x ) 9 { 10 return x * x; 11 } // second declaration of method square 14 // with int argument causes syntax error 15 public double square( int y ) 16 { 17 return y * y; 18 } } // end class MethodOverload Outline 27 MethodOverload. java Lines 8 and 15 Compiler cannot distinguish between Compiler cannot methods with identical names and distinguish between parameter sets methods with identical names and parameter sets MethodOverload.java:15: square(int) is already defined in MethodOverload public double square( int y ) ^ 1 error Fig Compiler error messages generated from overloaded methods with identical parameter lists and different return types.
28 28 Recursion Recursive method Calls itself (directly or indirectly) through another method Method knows how to solve only a base case Method divides problem Base case Simpler problem Method now divides simpler problem until solvable Recursive call Recursive step
29 29 Final value = 120 5! 5! 5! = 5 * 24 = 120 is returned 5 * 4! 5 * 4! 4! = 4 * 6 = 24 is returned 4 * 3! 4 * 3! 3! = 3 * 2 = 6 is returned 3 * 2! 3 * 2! 2! = 2 * 1 = 2 is returned 2 * 1! 1 2 * 1! 1 1 returned (a) Sequence of recursive calls. (b) Values returned from each recursive call. Recursive evaluation of 5!.
30 1 // Fig. 6.15: FactorialTest.java 2 // Recursive factorial method. 3 import java.awt.*; 4 5 import javax.swing.*; 6 7 public class FactorialTest extends JApplet { 8 JTextArea outputarea; 9 10 // create GUI and calculate factorials of public void init() 12 { 13 outputarea = new JTextArea(); Container container = getcontentpane(); 16 container.add( outputarea ); // calculate the factorials of 0 through for ( long counter = 0; counter <= 10; counter++ ) 20 outputarea.append( counter + "! = " + 21 factorial( counter ) + "\n" ); } // end method init 24 Invoke method factorial Outline 30 FactorialTest.j ava Line 21 Invoke method factorial
31 25 // recursive declaration of method factorial 26 public long factorial( long number ) 27 { 28 // base case 29 if ( number <= 1 ) 30 return 1; // recursive step 33 else 34 return number * factorial( number - 1 ); } // end method factorial } // end class FactorialTest Test for base case (method factorial can solve base case) Outline 31 FactorialTest.j ava Lines Else return simpler Test problem for base that case method factorial (method might solve factorial in next recursive can call solve base case) Line 34 Else return simpler problem that method factorial might solve in next recursive call
32 Example Using Recursion: The Fibonacci Series 32 Fibonacci series Each number in the series is sum of two previous numbers e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21 fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n - 1) + fibonacci( n 1 ) fibonacci(0) and fibonacci(1) are base cases Golden ratio (golden mean)
33 61 // recursive declaration of method fibonacci 62 public long fibonacci( long n ) 63 { 64 // base case 65 if ( n == 0 n == 1 ) 66 return n; // recursive step 69 else 70 return fibonacci( n - 1 ) + fibonacci( n - 2 ); } // end method fibonacci } // end class FibonacciTest Test for base case (method fibonacci can solve base case) Outline 33 FibonacciTest.j ava Else return simpler problem Lines that method fibonaccitest might for solve base case in next recursive (method call fibonacci can solve base case) Lines Else return simpler problem that method fibonacci might solve in next recursive call
34 34 fibonacci( 3 ) return fibonacci( 2 ) + fibonacci( 1 ) return fibonacci( 1 ) + fibonacci( 0 ) return 1 return 1 return 0 Set of recursive calls for fibonacci (3).
35 35 Recursion vs. Iteration Iteration Uses repetition structures (for, while or do while) Repetition through explicitly use of repetition structure Terminates when loop-continuation condition fails Controls repetition by using a counter Recursion Uses selection structures (if, if else or switch) Repetition through repeated method calls Terminates when base case is satisfied Controls repetition by dividing problem into simpler one
36 36 Recursion vs. Iteration (cont.) Recursion More overhead than iteration More memory intensive than iteration Can also be solved iteratively Often can be implemented with only a few lines of code
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 informationChapter 5 - Methods Prentice Hall, Inc. All rights reserved.
1 Chapter 5 - Methods 2003 Prentice Hall, Inc. All rights reserved. 2 Introduction Modules Small pieces of a problem e.g., divide and conquer Facilitate design, implementation, operation and maintenance
More informationPart 8 Methods. scope of declarations method overriding method overloading recursions
Part 8 Methods scope of declarations method overriding method overloading recursions Modules Small pieces of a problem e.g., divide and conquer 6.1 Introduction Facilitate design, implementation, operation
More informationChapter 6 - Methods Prentice Hall. All rights reserved.
Chapter 6 - Methods 1 Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math Class Methods 6.4 Methods 6.5 Method Definitions 6.6 Argument Promotion 6.7 Java API Packages 6.8 Random-Number Generation
More informationMethods: 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 informationChapter 3 - Functions
Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number
More informationDr 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 informationC Functions. 5.2 Program Modules in C
1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking
More informationFunctions. 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 informationCSE123. Program Design and Modular Programming Functions 1-1
CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.
More informationIntroduction to Programming
Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines
More informationFunctions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.
1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare
More informationCT 229 Java Syntax Continued
CT 229 Java Syntax Continued 06/10/2006 CT229 Lab Assignments Due Date for current lab assignment : Oct 8 th Before submission make sure that the name of each.java file matches the name given in the assignment
More informationC++, How to Program. Spring 2016 CISC1600 Yanjun Li 1
Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide
More informationBIL 104E Introduction to Scientific and Engineering Computing. Lecture 4
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions
More information엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED
엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data
More informationMethods: A Deeper Look Pearson Education, Inc. All rights reserved.
1 6 Methods: A Deeper Look 2 The greatest invention of the nineteenth century was the invention of the method of invention. Alfred North Whitehead Call me Ishmael. Herman Melville When you call me that,
More informationChapter 3 - Functions
Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation
More informationObject 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 informationC++ PROGRAMMING SKILLS Part 3 User-Defined Functions
C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions
More informationArrays (Deitel chapter 7)
Arrays (Deitel chapter 7) Plan Arrays Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods Sorting Arrays Searching Arrays: Linear Search and
More informationChapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++
Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8
More informationFunctions and Recursion
Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game
More informationFunction Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design
What is a Function? C Programming Lecture 8-1 : Function (Basic) A small program(subroutine) that performs a particular task Input : parameter / argument Perform what? : function body Output t : return
More informationFall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals
INTERNET PROTOCOLS AND CLIENT-SERVER PROGRAMMING Client SWE344 request Internet response Fall Semester 2008-2009 (081) Server Module 2.1: C# Programming Essentials (Part 1) Dr. El-Sayed El-Alfy Computer
More informationAn applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a
CBOP3203 An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled
More informationFunctions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.
Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5
More informationFunctions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.
Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create
More information6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x
(Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)
More informationFundamentals of Programming Session 13
Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationPace 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 informationCS110: 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 informationJava Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application
Last Time v We created our first Java application v What are the components of a basic Java application? v What GUI component did we use in the examples? v How do we write to the standard output? v An
More informationCS 335 Lecture 02 Java Programming
1 CS 335 Lecture 02 Java Programming Programming in Java Define data Calculate using data Output result Java is object-oriented: Java program must: Merge data and functions into object Invoke functions
More informationCS 335 Java Programming Controls. Fall 2007
CS 335 Java Programming Controls Fall 2007 Java Control Structures Selection: If, If/Else, Switch Repetition (looping): While, For, Do/While Assignment: Expressions, increment/decrement Java Reserved Words
More informationMethods: A Deeper Look
www.thestudycampus.com Methods: A Deeper Look 6.1 Introduction 6.2 Program Modules in Java 6.3 static Methods, static Fields and ClassMath 6.4 Declaring Methods with Multiple Parameters 6.5 Notes on Declaring
More informationQ1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question
Page 1 of 6 Template no.: A Course Name: Computer Programming1 Course ID: Exam Duration: 2 Hours Exam Time: Exam Date: Final Exam 1'st Semester Student no. in the list: Exam pages: Student's Name: Student
More informationC++ Programming Lecture 11 Functions Part I
C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs
More informationC Functions Pearson Education, Inc. All rights reserved.
1 5 C Functions 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare Call me Ishmael. Herman Melville
More informationwww.thestudycampus.com Methods Let s imagine an automobile factory. When an automobile is manufactured, it is not made from basic raw materials; it is put together from previously manufactured parts. Some
More informationINTRODUCTION 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 informationObjectives of CS 230. Java portability. Why ADTs? 8/18/14
http://cs.wellesley.edu/~cs230 Objectives of CS 230 Teach main ideas of programming Data abstraction Modularity Performance analysis Basic abstract data types (ADTs) Make you a more competent programmer
More informationCHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.
More information142
Scope Rules Thus, storage duration does not affect the scope of an identifier. The only identifiers with function-prototype scope are those used in the parameter list of a function prototype. As mentioned
More informationProgramming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.
Programming Fundamentals for Engineers - 0702113 7. Functions Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 Modular programming Your program main() function Calls AnotherFunction1() Returns the results
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More information1001ICT 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 informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationObject-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 informationIntroduction to Computer Science I
Introduction to Computer Science I String and Random Java Classes Janyl Jumadinova 12-13 February, 2018 Divide and Conquer Most programs are complex and involved. The best way to develop and maintain a
More informationJava Methods. Lecture 8 COP 3252 Summer May 23, 2017
Java Methods Lecture 8 COP 3252 Summer 2017 May 23, 2017 Java Methods In Java, the word method refers to the same kind of thing that the word function is used for in other languages. Specifically, a method
More informationRoad Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets
Java Applets Road Map Introduction to Java Applets Review applets that ship with JDK Make our own simple applets Introduce inheritance Introduce the applet environment html needed for applets Reading:
More informationThe Math Class. Using various math class methods. Formatting the values.
The Math Class Using various math class methods. Formatting the values. The Math class is used for mathematical operations; in our case some of its functions will be used. In order to use the Math class,
More informationMethods CSC 121 Fall 2016 Howard Rosenthal
Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods
More informationFunctions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries
More informationCSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU
CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition
More informationMethods CSC 121 Spring 2017 Howard Rosenthal
Methods CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods
More informationTo define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,
1 To define methods, invoke methods, and pass arguments to a method ( 5.2-5.5). To develop reusable code that is modular, easy-toread, easy-to-debug, and easy-to-maintain. ( 5.6). To use method overloading
More informationCS110D: 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 informationArrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type
Array Arrays Introduction Group of contiguous memory locations Each memory location has same name Each memory location has same type Remain same size once created Static entries 1 Name of array (Note that
More informationC Programming for Engineers Functions
C Programming for Engineers Functions ICEN 360 Spring 2017 Prof. Dola Saha 1 Introduction Real world problems are larger, more complex Top down approach Modularize divide and control Easier to track smaller
More informationC Functions. Object created and destroyed within its block auto: default for local variables
1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program
More informationLecture 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 informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
More informationChapter 5 C Functions
Chapter 5 C Functions Objectives of this chapter: To construct programs from small pieces called functions. Common math functions in math.h the C Standard Library. sin( ), cos( ), tan( ), atan( ), sqrt(
More information1 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 informationChapter 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 informationC Programs: Simple Statements and Expressions
.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. C Programs: Simple Statements and Expressions C Program Structure A C program that consists of only one function has the following
More informationJAVA: 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 informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science Department Lecture 3: C# language basics Lecture Contents 2 C# basics Conditions Loops Methods Arrays Dr. Amal Khalifa, Spr 2015 3 Conditions and
More informationVariables. location where in memory is the information stored type what sort of information is stored in that memory
Variables Processing, like many programming languages, uses variables to store information Variables are stored in computer memory with certain attributes location where in memory is the information stored
More informationFunctions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction
Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that
More informationA variable is a name for a location in memory A variable must be declared
Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;
More informationMethods CSC 121 Fall 2014 Howard Rosenthal
Methods CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class Learn the syntax of method construction Learn both void methods and methods that
More informationChapter 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 informationKey Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent
Programming 2 Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent information Input can receive information
More informationPackages. Examples of package names: points java.lang com.sun.security drawing.figures
Packages To make classes easier to find and to use, to avoid naming conflicts, and to control access, programmers bundle groups of related classes and interfaces into packages. A package is a program module
More informationObject-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018
Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative
More information1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B
1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these 2. How many primitive data types are there in Java? A. 5 B. 6 C. 7 D. 8 3. In Java byte, short, int and long
More informationFunctions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa
Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 06 / 10 / 2015 Instructor: Michael Eckmann Today s Topics Questions / comments? Method terminology and Programmer defined methods Michael Eckmann - Skidmore College
More informationWe now start exploring some key elements of the Java programming language and ways of performing I/O
We now start exploring some key elements of the Java programming language and ways of performing I/O This week we focus on: Introduction to objects The String class String concatenation Creating objects
More informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 5 Anatomy of a Class Outline Problem: How do I build and use a class? Need to understand constructors A few more tools to add to our toolbox Formatting
More informationThe return Statement
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
More informationFunctions and Recursion
Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function
More informationC++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.
C++ How to Program, 9/e 1992-2014 by Pearson Education, Inc. Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or components.
More informationJava Classes: Math, Integer A C S L E C T U R E 8
Java Classes: Math, Integer A C S - 1903 L E C T U R E 8 Math class Math class is a utility class You cannot create an instance of Math All references to constants and methods will use the prefix Math.
More informationThe first applet we shall build will ask the user how many times the die is to be tossed. The request is made by utilizing a JoptionPane input form:
Lecture 5 In this lecture we shall discuss the technique of constructing user-defined methods in a class. The discussion will be centered about an experiment of tossing a die a specified number of times.
More informationExercise. 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 information34. 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 informationChapter 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 informationAP CS Unit 3: Control Structures Notes
AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts
More informationReview. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char
Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in
More informationChapter 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 informationDownloaded from Chapter 2. Functions
Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create
More information- HALF YEARLY EXAM ANSWER KEY DEC-2016 COMPUTER SCIENCE ENGLISH MEDIUM
www.padasalai.net - HALF YEARLY EXAM ANSWER KEY DEC-2016 COMPUTER SCIENCE ENGLISH MEDIUM 1 A 26 D 51 C 2 C 27 D 52 D 3 C 28 C 53 B 4 A 29 B 54 D 5 B 30 B 55 B 6 A 31 C 56 A 7 B 32 C 57 D 8 C 33 B 58 C
More informationBuilt-in Types of Data
Built-in Types of Data Types A data type is set of values and a set of operations defined on those values Python supports several built-in data types: int (for integers), float (for floating-point numbers),
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 02 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Comments and/or Questions? Arrays multidimensional Math class methods Programmer defined methods Michael
More informationJAVA Programming Concepts
JAVA Programming Concepts M. G. Abbas Malik Assistant Professor Faculty of Computing and Information Technology University of Jeddah, Jeddah, KSA mgmalik@uj.edu.sa Find the sum of integers from 1 to 10,
More informationUsing Classes and Objects. Chapter
Using Classes and Objects 3 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Using Classes and Objects To create
More information