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

Similar documents
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Introduction to Computer Science Unit 2. Notes

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

What did we talk about last time? Examples switch statements

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

MODULE 02: BASIC COMPUTATION IN JAVA

Methods with Parameters and Return Values

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

Full file at

Introduction to Computer Science Unit 2. Notes

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Variables and Constants

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Downloaded from Chapter 2. Functions

COMP 111 PROGRAMMING I MODULARITY USING FUNCTIONS

DATA TYPES AND EXPRESSIONS

CS 302: Introduction to Programming

CS110: PROGRAMMING LANGUAGE I

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Language Reference Manual

CSCE 120: Learning To Code

CS11 Java. Fall Lecture 1

Pace University. Fundamental Concepts of CS121 1

Object Oriented Methods : Deeper Look Lecture Three

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

Algorithms and Programming I. Lecture#12 Spring 2015

Fundamentals of Programming Session 4

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Chapter 4 Defining Classes I

Lesson 2A Data. Data Types, Variables, Constants, Naming Rules, Limits. A Lesson in Java Programming

Lecture Notes for CS 150 Fall 2009; Version 0.5

CISC 110 Week 3. Expressions, Statements, Programming Style, and Test Review

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

MITOCW watch?v=kz7jjltq9r4

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Formatting Output & Enumerated Types & Wrapper Classes

2. Numbers In, Numbers Out

Methods CSC 121 Fall 2016 Howard Rosenthal

M e t h o d s a n d P a r a m e t e r s

AP CS Unit 3: Control Structures Notes

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Appendix: Common Errors

Outline. Turtles. Creating objects. Turtles. Turtles in Java 1/27/2011 TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

4. Java Project Design, Input Methods

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

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

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Lecture 5: Methods CS2301

Welcome to the Primitives and Expressions Lab!

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

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

Introduction to Java Applications

Lexical Considerations

Chapter 2 Basic Elements of C++

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Programming for Engineers Introduction to C

COMP-202: Foundations of Programming

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

Basics of Java Programming

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

We now start exploring some key elements of the Java programming language and ways of performing I/O

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

CS 231 Data Structures and Algorithms, Fall 2016

A variable is a name for a location in memory A variable must be declared

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Week 2: Data and Output

C++ Reference NYU Digital Electronics Lab Fall 2016

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

The return Statement

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

بسم اهلل الرمحن الرحيم

Building Java Programs

VARIABLES AND TYPES CITS1001

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

Methods CSC 121 Spring 2017 Howard Rosenthal

Skill 1: Multiplying Polynomials

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

M.CS201 Programming language

Function. Mathematical function and C+ + function. Input: arguments. Output: return value

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Chapter 2, Part I Introduction to C Programming

printf( Please enter another number: ); scanf( %d, &num2);

Transcription:

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 for today is posted here. 2

Review Parameters Most methods receive information from the statements that call them Java allows us to do that using parameters A parameter is a special local variable of a method that receives its value from the method call When you write the method header of a method that has parameters... you must specify the number and type of parameters the method uses The parameter declaration appears in the method header... after the name of the method and inside the parentheses 3

Parameters Parameters are different from local variables in another way... they are initialized with values that comes from outside the method They get their values from the arguments... inside the parentheses of a method call The value can be any valid expression That means an argument can be a Literal Variable Constant Calculation using operators 4

The Mechanics of Parameters When Java executes a method call, it Evaluates the expressions inside the parentheses of the method call Creates a new variable of the type specified in the method header Sets the value of this variable to the value given by the method call Let s look at an example 5

The Mechanics of Parameters In the first two lines of the program, the computer sets aside two memory locations and initializes each of them to an integer Now the code calls writespaces writespaces(spaces1 * spaces2 5); The machine Fetches the value of spaces1 (3) Gets the value of spaces2 (5) Multiplies these two values to get 15 Subtracts 5 from this result to get 10 Goes to the block of memory reserved for the method writespaces Creates space in this block of memory for the parameter number Initializes number to 10 After the method call finishes we again have: 6

Common Programming Error: Confusing Arguments and Formal Parameters Students sometimes make a mistake like this writespaces(int spaces1); // this doesn't work the argument of a method call should be like this: writespaces(spaces1); And a parameter is declaration inside a method header public static void writespaces(int number) The data type must be specified when the method is declared... not when a method is called 7

Limitations of Parameters Parameters are used to get values into a method But they cannot be used to get values out of the method When you call a method, the machine sets aside memory... for each of the parameters declared in the method header... and initializes them with the values received from the method call The parameters are variables that are local to the method itself They are in a different scope from the method call Parameters only exist when the method is running... and can't be used to get information... back to the section of code that called them 8

Multiple Parameters Java allows you to define any number of parameters in a method header Here is the format for a method header public static void METHOD_NAME ( DATA_TYPE PARAMETER_NAME,... ) { STATEMENT;... } 9

Overloading Methods Java allows us to have more than one method with the same name.. as long as the number and types of the parameters are different The combination of the method name and the data types of all parameters is called the method signature Allowing Java to have methods with the same name... but different signatures is called method overloading For example: 10

New Materials Outline Methods That Return Values Methods Headers Defining Methods That Return Values The Math Class Using Objects String Objects 11

Methods That Return Values The methods you have seen so far do some work but cannot send a value back to the statement in another method that calls them Many methods perform some sort of calculation... using the values given them through parameters... and return a value to the method that called them When a method gives a value back... it is said to return a value We need to specify the data type of the returned value in the method header 12

Methods That Return Values Let's say we wanted to create a function that computes interest Money is a decimal, so we want to return a value of type double We would need to write the method header this way public static double computeinterest(double value) The return type comes after public static in the method header We can then use the value returned by the method we called in any calculation This means that a method call to a method that returns a value... is also a expression 13

Methods That Return Values Remember, an expression is anything that Java can turn into a value We can use a method call to a method that returns a value... anywhere in our Java code where we can use an expression So we can use it in assignment interest = computeinterest(balance); or in a calculation balance = balance + computeinterest(balance); or as an argument in a method call System.out.print("Here is the interest "); System.out.println(computeInterest(balance)); The value of the variable balance is assigned to the parameter value inside the method computeinterest and the computed interest comes out as the return value 14

Methods That Return Values But what about the methods that don t return a value? That's why they had the return type void void means the method returns no value You must always declare the return type of a method... in the method header 15

New Materials Outline Methods That Return Values Methods Headers Defining Methods That Return Values The Math Class Using Objects String Objects 16

Method Headers A method header is the first line of a method definition If we look at the following method header public static int sumcubes(int limit) it has 5 pieces of information public static int sumcubes int limit Since we are only dealing with static methods in this class all our methods begin with public static. So we only need to think about the 3 pieces of information that follow these two keywords The three things they specify are the Data type of the return value Name of the method The names and data types of the parameters 17

New Materials Outline Methods That Return Values Methods Headers Defining Methods That Return Values The Math Class Using Objects String Objects 18

Defining Methods That Return Values How does the value a method calculates get back to the method call? By using the return statement A return statement has the following format return EXPRESSION; Let's look at an example To calculate the hypotenuse of a right triangle we use the Pythagorean Theorem If we call the hypotenuse and the sides a and b... we can use the formula h * h = a * a + b * b 19

Defining Methods That Return Values This allows us to write the hypotenuse method public static double public hypotenuse(double a, double b){ } return Math.sqrt(a * a + b * b); This method accepts two numbers of type double as arguments and returns a value that is also of type double The return statement does two things It causes the method to stop running It returns a value to the method call You cannot put any statements after the return statement. Otherwise, you will get a compile error. 20

Defining Methods That Return Values Every method that returns a value must have a return statement at the end The only methods that do not have to end with a return statement are void methods. The void keyword in the method header means the method returns no value The value returned by the method must have the data type specified in the method header or you will get a compile error The Math class is a special kind of class called a static class Most classes can be used to create objects but not a static class. A static class cannot create objects. A static class contains only two things Static methods Constants 21

New Materials Outline Methods That Return Values Methods Headers Defining Methods That Return Values The Math Class Using Objects String Objects 22

The Math Class Java comes with many helpful classes that make writing code easier One example is the Math class The Math class contains number of useful methods These methods perform mathematical calculations... like taking the square root of a number The square root method, named sqrt, has the following method header public static double sqrt(double n) 23

The Math Class When you call a method that is not defined in the class... you have to tell Java what class holds the method You do this using dot notation It has the following form CLASS_NAME.ELEMENT_NAME; Where ELEMENT_NAME the name of one of two things A method A constant We need to call the method sqrtfollows Math.sqrt(num); 24

The Math Class Besides methods, the Math class contains some useful constants Constant Description E The base used in natural logarithms (2.71828... ) PI The ratio of circumference of a circle to its diameter (3.14159... ) Notice that these constants follow the Java convention of CAPITALIZING constant names Here is a list of some of the more useful methods contained in the Math class. For a full list look: http://docs.oracle.com/javase/6/docs/api/java/lang/math.html Method Description Example max maximum of two values Math.max(45, 207) returns 207 min minimum of two values Math.min(3.8, 2.75) returns 2.75 sqrt square root Math.sqrt(2) returns 1.4142135623730951 pow power (general exponentiation) Math.pow(3, 4) returns 81.0 25

New Materials Outline Methods That Return Values Methods Headers Defining Methods That Return Values The Math Class Using Objects String Objects 26

Using Objects To bundle variables that contained the data about one type of thing... with the methods that worked upon the data We call these bundles classes We use these classes to create objects in memory when the program runs We sometimes say that an object is an instance of a certain class By that we mean that the object was created... using a specific class as template Remember, there are two broad categories of data types Primitive data types Classes 27

New Materials Outline Methods That Return Values Methods Headers Defining Methods That Return Values The Math Class Using Objects String Objects 28

String Objects We'll begin our study of objects by talking about strings A string is just a collection of characters You may have noticed that while Java has a char primitive data type... it has no string primitive data type This was a design decision made early in the history of Java Instead of a string primitive type, Java has the String class So individual strings are objects of type String There is one way that the String object is different from other objects: the string literal No other object has a literal A string literal is a group of characters enclosed in double quotes, " " 29

String Objects We can declare and initialize String variables String s = "Hello world!"; You can't add, subtract, multiply or divide a String variable But you can concatenate them String s1 = "Hello ; String s2 = "world"; String greeting = s1 + " " + s2; 30

String Objects: Get the length If we want to get the length of a string variable we use int len = s1.length(); To use a method of a class that in not static... you must first create an object that is an instance of that class... before we can use the methods it contains It's as if we were asking the String object to tell us it's length You can then use the instance name to get to the method using dot notation The syntax for calling a method on an object is OBJECT_NAME.METHOD_NAME(EXPRESSION,...) 31

String Objects: Get the Character of a String Another thing we might want to do with a string is get the character at a specific position in the string The most commonly used method is charat This method returns the character at a specific location in the string The position of the character in the string is called the index An index is an integer that specifies the location of a value in a list of values Indexes in Java start with 0 This is called zero- based indexing Just remember, in a string the numberingalways starts with 0 32

String Objects: Get the Character of a String Here are the indices for a string we've already encountered Notice that even the space and the exclamation mark,!, have a position in the string Let's write some code to print the characters in a string 33

String Objects: Substring Another useful String method is substring This method returns a smaller string within the larger string When we call substringwe need to give it two arguments The first is the index of the first character in the substring... and the second argument is a number which is one more the index of the last character We would use the following method call Notice that there is no character with an index of 12. 34

String Objects: Substring When you use substringyou must be careful with the second argument It must be one more than the index of the last character you want, But it can't be larger than the length of the string. This is a runtime error which Java handles with an exception... which we'll discuss in a future class 35

Class 9 Quiz 1. What is the scope of a parameter? the method in which it is defined 2. Where does a parameter get its value? from the argument in the method call 3. Where in a method header do you declare a parameter? inside the parentheses after the method name 4. Does a parameter keep its value after the method has finished? no. the parameter only lives while the method runs 5. Can a parameter be used to give a value back to the statement that calls the method? no 36

Class 9 Quiz 6. Write the method header for a method named printaverage that takes a single integer parameter called num public static void printaverage(intnum) 7. Write a statement that calls printaverage with the argument 10. printaverage(10); 8. Write the method header for a method named printmultiply that takes two integer parameters, a and b.? public static void printmultiply(int a, int b); 9. Write a statement that calls printmultiply with the arguments 4 and 5. printmultiply(4, 5); 10. What is a method signature? the name of the method together with the name and type of each of the parameters 37

Class 10 Quiz 1. What is the data type of return value of the following method? public static int fibonacci (int number) integer (int) 2. Write a statement that uses the fibonacci method above to print a value when fibonacci is called with an argument of 5 System.out.println(fibonacci(5)); 3. What is wrong with the following code? public static double interest(int percent, double value) { } return percent/100 * value; System.out.println("Returned a value"); there is a statement after the return statement 38

Class 10 Quiz 4. Write a statement that prints the square root of 5 using the sqrt method of the Math class. System.out.println(Math.sqrt(5)); 5. What is a class used to create? an object 6. Can a static class create an object? no 7. What is a string? a collection of characters 8. Is a string a primitive data type in Java? No, it is a class 39

Class 10 Quiz 9. What is the index of the first character in a string? 0 10. Write a statement that declares the string variable s and assigns it the value "Hello world!". String s = "Hello world!"; 40

Weekly Quiz1 1. What must the name of the source code file for the Java class CountToTenbe? CountToTen.java 2. If you want to run a Java program from the command line, what must the source code file contain inside the class definition? a main method 3. What is the first line of a method called? method header 4. What is a method? a group of statements that performs a specific task 41

Weekly Quiz1 5. Write the Java statement that prints "Hello world!"? System.out.println("Hello world!"); 6. In the previous statement, what does Java call "Hello world!"? a string literal 7. Write the escape sequence for the Tab character? \t 8. Can you use a Java keyword as an identifier? no 42

Weekly Quiz1 9. Is 1st_try a valid Java identifier? no 10. Write a one line comment that contains the text "This is a one line comment" // This is a one line comment 43

Common Programming Error: Ignoring the Returned Value When you call a method that returns a value, you should do something with that value If you don't, the compiler won't object but you have just wasted computer time calculating something you didn't use When you call a method with a return value, you should do something with the result Store it Print it Use it in another expression If your code does nothing, maybe you forgot to use a returned value 44

Common Programming Error: Statement after Return It is illegal to place statements in a Java method after a return statement Any code following the return statement will never be reached and the compiler will object When debugging code, it is common to add print statements to see what is going on But you must put the print statement before the return statement The following code will produce a syntax error 45