Review: Local variable: is a variable declared within a method.

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

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

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

AP Computer Science Java Subset

Java Interview Questions and Answers

Moving from CS 61A Scheme to CS 61B Java

Java CPD (I) Frans Coenen Department of Computer Science

CS170 Lab 11 Abstract Data Types & Objects

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Python

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Introduction to Object-Oriented Programming

Chapter 2: Elements of Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

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

The C Programming Language course syllabus associate level

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

Example of a Java program

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Chapter 2 Introduction to Java programming

Inheritance, overloading and overriding

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

CMSC 202H. ArrayList, Multidimensional Arrays

Lecture 2 Notes: Flow of Control

Introduction to Java. CS 3: Computer Programming in Java

LAB4 Making Classes and Objects

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Programming Languages CIS 443

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

Pemrograman Dasar. Basic Elements Of Java

Object Oriented Software Design II

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Class 16: Function Parameters and Polymorphism

Java Basics: Data Types, Variables, and Loops

Object Oriented Software Design

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Object-Oriented Programming Lecture 2: Classes and Objects

Introduction to Java

Object Oriented Software Design

Computer Programming I

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

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

C++ INTERVIEW QUESTIONS

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

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

El Dorado Union High School District Educational Services

CS 106 Introduction to Computer Science I

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

An Incomplete C++ Primer. University of Wyoming MA 5310

Java Programming Fundamentals

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

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

Copyright. Restricted Rights Legend. Trademarks or Service Marks. Copyright 2003 BEA Systems, Inc. All Rights Reserved.

Crash Course in Java

Sample CSE8A midterm Multiple Choice (circle one)

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

Sources: On the Web: Slides will be available on:

Java Classes. GEEN163 Introduction to Computer Programming

java Features Version April 19, 2013 by Thorsten Kracht

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Install Java Development Kit (JDK) 1.8

Java Crash Course Part I

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

Getting Started with the Internet Communications Engine

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

Understanding class definitions

Conditional Statements Summer 2010 Margaret Reid-Miller

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Unit Testing and JUnit

Chapter 13 - Inheritance

e ag u g an L g ter lvin v E ram Neal G g ro va P Ja

C++FA 5.1 PRACTICE MID-TERM EXAM

13 Classes & Objects with Constructors/Destructors

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

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

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

PostgreSQL Functions By Example

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Unit Testing & JUnit

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

More on Objects and Classes

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

COMP 110 Prasun Dewan 1

HybriDroid: Analysis Framework for Android Hybrid Applications

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Lecture 5: Java Fundamentals III

Transcription:

CMSC 131: Chapter 8 (Supplement) More about Methods Methods Revisited Review: Methods are Java s basic computational units. Methods are also called functions or procedures. Information can be passed into a method through its parameters. The calling process provides the actual parameters (sometimes called arguments), and these are copied to the formal parameters (sometimes simply called parameters). Parameters are passed by value. Modifying a formal parameter does not alter the value of the corresponding actual parameter. By default a method (non-static) is associated with a particular class instance. A static method is shared by all instances of a class. A method can return a single value, a primitive type or an object reference. (Omitted See the textbook) Method Syntax Local Variables and Scope Local variable: is a variable declared within a method. a local variable is only accessible within the method in which it is declared. formal parameters are considered to be local variables. if a variable with the same name is defined within another method, it is an entirely different variable. global variables(?): In Java every variable is either local or is an instance variable.

Local Variables and Scope Block: is a collection of statements enclosed in curly braces {. Scope: of a variable means the portion of the program where a variable can be accessed. public class LocalTest0 { public static void dumb( int y ) { do { double z = Math.random( ); System.out.println( "z = " + z ); while ( --y > 0 ); // ERROR: z cannot be resolved System.out.println( "In dumb: z = " + z ); Example: Test of Local Variables Duplicate Variables: Java does not allow two local variables to have the same name. public class LocalTest1 { public static void dumber( int y ) { int y; // ERROR: Duplicate variable y double z; do { double z = Math.random( ); // ERROR: Duplicate variable z System.out.println( "z = " + z ); while ( --y > 0 ); System.out.println( "In dumber: z = " + z ); Example: Test of Local Variables public class LocalTest { public static void smarter( int y ) { double z; do { z = Math.random( ); System.out.println( "z = " + z ); while ( --y > 0 ); System.out.println( "In smarter: z = " + z + " y = " + y ); public class LocalTestDriver { public static void main( String[ ] args ) { int z = 5; int y = -6; LocalTest.smarter( 3 ); System.out.println( "Back in main: z = " + z + " y = " + y );

Test Drivers The previous example showed the use of a driver program. public class SomeClass { public static void method1( ) { public static void method2( ) { public class TestDriver { public static void main( String[ ] args ) { SomeClass.method1( ); SomeClass.method2( ); Initialization of Local Variables Initialization of Variables: Instance variables: Java provides default values automatically. boolean variables: false numeric variables (int, float, etc): 0 (zero) object references: null Local variables: are not initialized automatically. You need to give them an initial value before using them or the compiler will not compile your program. Method Overloading Overloading: Java allows methods to have the same name, even within the same class. public void setdate( int m, int d, int y ) { // month given as integer public void setdate( String m, int d, int y ) { // month given as string public void setdate( int m, int y ) { // day defaults to 1 Sample calls: Date duedate = new Date( 10, 5, 2004 ); duedate.setdate( 10, 7, 2004 ); duedate.setdate( Nov, 12, 2004 ); duedate.setdate( 1, 2005 ); // set initial due date // delay the due date // delay it further // delay until next year Question: How does Java know which one to call? Answer: It looks at the number and of types of arguments.

Method Overloading and Signatures Overloading: using the same identifier name for different methods. Signature: of a method consists of the name of the method and the types of the parameters. Example: public float dosomething( int x, double z, double w, String s ) Corresponding Signature: dosomething( int, double, double, String ) Method Overloading and Signatures Note that the return type of a method is not part of the signature. Example: public int tocelsius( double t ) { public double tocelsius( double t ) { System.out.println( tocelsius( 98.6 ) ); Which method should be called? Unfortunately, Java cannot read your mind. Parameter Type Promotion Arithmetic Promotion: We have seen that, in arithmetic expressions, Java promotes numeric types to the higher type: double total = ; int count = ; double average = total / count; Promotion of Parameters: Java automatically promotes each actual parameter to match the type of its formal parameter. int area = 1024; double s = Math.sqrt( area );

Ambiguous Overloading Because of type promotion, there are times when Java cannot figure out which method to call. public void foobar( int x, double y ) { public void foobar( double u, int v ) { foobar( 10, 23.0 ); // okay, use the first foobar( 10.0, 23 ); // okay, use the second foobar( 10, 23 ); //??? Do we promote 23 to 23.0 and call the first, or promote the 10 to 10.0 and call the second? Java issues a compile-time error, since it cannot resolve the ambiguity. Class References as Parameters Pass by Value: Recall that actual parameters (arguments) are passed to a method by copying their values to the formal parameters. public void foo( ) { int x = 23; bar( x ); System.out.println( x ); // this prints 23 public void bar( int x ) { x++; // change the formal parameter This is not as obvious when the actual parameter is an object reference.

Class References as Parameters To see why object references behave differently, let us create a toy class, called RefTest. public class RefTest { private int data; // instance data is a single integer public RefTest( int d ) { data = d; // constructor public String tostring( ) // convert to string [ data ] { return new String( "[" + data + "]" ); public void changeme( ) { data++; // increment data Class References as Parameters public class RefTestDriver { public static void main( String[ ] args ) { int x = 0; RefTest ref = new RefTest( 5 ); System.out.println( "Before: x = " + x + changethem1( x, ref ); System.out.println( "After-1: x = " + x + // (other stuff omitted) public static void changethem1( int x, RefTest ref ) { x = x+1; ref = new RefTest( 2 ); System.out.println( "Inside-1: x = " + x + Output: Before: x = 0 ref = [5] Inside-1: x = 1 ref = [2] After-1: x = 0 ref = [5]

public class RefTestDriver { Class References as Parameters public static void main( String[ ] args ) { int x = 0; RefTest ref = new RefTest( 5 ); System.out.println( "Before: x = " + x + // other stuff omitted changethem2( x, ref ); System.out.println( "After-2: x = " + x + public static void changethem2( int x, RefTest ref ) { ref.changeme( ); System.out.println( "Inside-2: x = " + x + Output: Before: x = 0 ref = [5] Inside-2: x = 0 ref = [6] After-2: x = 0 ref = [6] Returning to return Recall that the return statement returns control from a method. It can appear anywhere in the method, but is best at the end. If the method has type void, then there is no return value given. Example: public void printsecret( String s ) { if ( s == null ) return; System.out.println( The secret of life is + s );

Returning to return Recall that the return statement returns control from a method. If the method has a return value, you must return a value of a compatible type. Numeric promotion is allowed, e.g., returning an int for a double. public int thisbebroken( double x ) { if ( x < 0 ) return x; // ERROR! cannot return double as int // ERROR! if x >= 0, nothing is returned You can return an expression. return w*x 42*y + Math.sqrt( z ); This is about this The keyword this can be used within a class to generate an explicit reference to the current object. Example: Let Date be a class with instance members, month, day, year. public boolean equals( Date d ) { if ( ( year==d.year ) && ( month==d.month ) && ( day==d.day ) ) return true; else return false; We can replace the implicit references to year, month, and day with the explicit references: this.year, this.month, and this.day. public boolean equals( Date d ) { if (( this.year==d.year ) && ( this.month==d.month ) && ( this.day==d.day )) return true; else return false; Are you joking? Why would anyone ever want to do this?

This is about this Better Example: Consider a class Basic that holds a single int data and has a static method that adds two such objects: public class Basic { private int data; public Basic( int d ) { data = d; // instance data // constructor public static int add( Basic t1, Basic t2 ) { return t1.data + t2.data; // static add Your boss asks you to add a non-static method that adds the current object to another Basic object. We can do this by calling the add method, and passing ourselves as the argument. public int addto( Basic t ) { return add( this, t ); // nonstatic add These are called respectively as follows: Basic.add( t1, t2 ); t1.addto( t2 ); Java program: consists of one or more.java files Java File Structure Java file: (e.g., FooBar.java) consists of: (optional) import statements one public class definition (named FooBar). Class definition: consists of: (optional) instance variable declarations (optional) method declarations These elements can appear in any order. Main method: One file in the program should have a main method. This is where execution starts.