Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.

Slides:



Advertisements
Similar presentations
Variables and Operators
Advertisements

Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to C Programming
Chapter 2 Using Objects. These slides for CSE 110 Sections are based in part on the textbook-authors ’ slides, which are copyright 2003 by Cay Horstmann.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 2 storing numbers and creating objects Pages in Horstmann.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Datalogi A 2: 15/9. Java Slides based on Horstmann chapter 2&3 Objects and classes Import, methods, references Implementing a class.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
Data types and variables
How Create a C++ Program. #include using namespace std; void main() { cout
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
Chapter 2  Using Objects 1 Chapter 2 Using Objects.
JavaScript, Fourth Edition
Chapter 2: Introduction to C++.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the structure of a C-language program. ❏ To write your first C.
Introduction to C Programming
Chapter 2 types, variables, methods Pages Horstmann.
Basic Elements of C++ Chapter 2.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Slides by Evan Gallagher Fundamental Data Types 09/09/13.
CHAPTER 2 Using Objects. Basic Programming Terminology  Computer program process values.  Numbers (digits)  Words (Strings)  These values are different.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Classes CS 21a: Introduction to Computing I First Semester,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 4 Procedural Methods. Learning Java through Alice © Daly and Wrigley Objectives Identify classes, objects, and methods. Identify the difference.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Chapter 2 Using Objects. Chapter Goals To learn about variables To understand the concepts of classes and objects To be able to call methods To be able.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Jens Dalsgaard Nielsen Jan Dimon Bendtsen Dept. of Electronic Systems Basic Programming INS-basis GF, PDP and HST.
Week 2 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 2 Using Objects. Types A type defines a set of values and the operations that can be carried out on the values Examples: 13 has type int "Hello,
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Jens Dalsgaard Nielsen Jan Dimon Bendtsen Dept. of Electronic Systems Basic Programming INS-basis GF, PDP and HST.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 2 - Using Objects.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Chapter 2 Using Objects. Chapter Goals To learn about variables To understand the concepts of classes and objects To be able to call methods To be able.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Introduction to Programming Python Lab 3: Arithmetic 22 January PythonLab3 lecture slides.ppt Ping Brennan
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
A Sample Program #include using namespace std; int main(void) { cout
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
A Simple Object Oriented Program public class Simple { public static void main (String [] args) { System.out.println(“howdy”); } System.out is an object.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Chapter Topics The Basics of a C++ Program Data Types
Console Output, Variables, Literals, and Introduction to Type
Basic Elements of C++.
Revision Lecture
Basic Elements of C++ Chapter 2.
Chapter 4 Procedural Methods.
IDENTIFIERS CSC 111.
Chapter 2 Using Objects.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 7 Procedural Methods.
Chapter 2: Introduction to C++.
Primitive Types and Expressions
Use a variable to store a value that you want to use at a later time
Each object belongs to a class
Parameter: an input to a method
Presentation transcript:

Chapter 2: Using Objects Part 1

To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about parameters and return values To implement test programs To be able to browse the API documentation To realize the difference between objects and object references To write programs that display simple shapes Chapter Goals

Every value has a type Variable declaration examples (variable name in blue): String greeting = "Hello, World!"; PrintStream printer = System.out; int luckyNumber = 13; Variables Variables store values Can be used in place of the objects they store. For example, instead of this… System.out.println("Hello, World!"); System.out.println(13); …we can use this: printer.println(greeting); printer.println(luckyNumber); Types and Variables

typeName variableName; or typeName variableName = value; Example: String greeting = "Hello, Dave!"; Purpose: To define a new variable of a particular type (declaration) and optionally supply an initial value (initialization). Syntax 2.1 Variable Definition A variable's type must match its value String greeting = 13 // ERROR: Types don't match

Identifier: name of a variable, method, or class Rules for identifiers in Java: Can be made up of letters, digits, and the underscore (_) character Cannot start with a digit Cannot use other symbols such as ? or % Spaces are not permitted inside identifiers You cannot use reserved words They are case sensitive By convention: variable names start with a lowercase letter class names start with an uppercase letter variable and method names start with lowercase, but the first letter of each embedded word is capitalized (known as “camel case”) e.g. luckyNumber, numberOfImages, longTimeNoSee Identifiers

What is the type of the values 0 and "0" ? Answer: int and String. Self Check 2.1

Which of the following are legal identifiers? Greeting1 g void 101dalmatians Hello, World Answer: Only the first two are legal identifiers. Self Check 2.2

Define a variable to hold your name. Use camel case in the variable name. Answer: String myName = “Andrew Vardy"; Self Check 2.3

Assignment operator: = Used to either change the value of a variable or initialize the variable Initialization: Giving a variable its initial value Not used as a statement about equality The Assignment Operator

int luckyNumber = 13; The Assignment Operator

int luckyNumber = 13; luckyNumber = 12; The Assignment Operator

Error: int luckyNumber; System.out.println(luckyNumber); // ERROR – uninitialized variable Uninitialized Variables

variableName = value; Example: luckyNumber = 12; Purpose: To assign a new value to a previously declared variable. Syntax 2.2 Assignment

Animation 2.1

Is 12 = 12 a valid expression in the Java language? Answer: No, the left-hand side of the = operator must be a variable. Self Check 2.4

How do you change the value of the greeting variable to "Hello, Nina!"? Answer: greeting = "Hello, Nina!"; Note that String greeting = "Hello, Nina!"; is not the right answer – that statement defines a new variable. Self Check 2.5

Object: entity that you can manipulate in your programs (by calling methods) Each object belongs to a class: For example, System.out belongs to the class PrintStream "Hello, World!" belongs to the class String Objects and Classes

Method: Sequence of instructions that accesses the data of an object You manipulate objects by calling their methods Class: Set of objects with the same behaviour The class of an object determines which methods are legal for that object String greeting = "Hello"; greeting.println() // Error greeting.length() // OK Public Interface: Specifies the methods (and public variables) that a class offers for your use Methods

A Representation of Two String Objects

length: counts the number of characters in a string String greeting = "Hello, World!"; int n = greeting.length(); // sets n to 13 toUpperCase: creates another String object that contains the characters of the original string, with lowercase letters converted to uppercase String river = "Mississippi"; String bigRiver = river.toUpperCase(); // sets bigRiver to "MISSISSIPPI" When applying a method to an object, make sure the method is defined in the appropriate class (i.e. the method must be part of the class’s public interface)‏ System.out.length(); // This method call is an error String Methods

Assume that river has been defined as follows: String river = “Mississippi!”; How can you compute the length of the string "Mississippi" ? Answer: river.length() or "Mississippi".length() Self Check 2.6

How can you print out the uppercase version of "Hello, World!" ? Assume that greeting has been defined as follows: String greeting = “Hello, World!”; Answer: System.out.println(greeting.toUpperCase()); Self Check 2.7

Assume that river has been defined as follows: String river = “Mississippi!”; Is it legal to call river.println() ? Why or why not? Answer: It is not legal. The variable river has type String. The println method is not a method of the String class. Self Check 2.8

Parameter (explicit parameter): Input to a method. Not all methods have explicit parameters. System.out.println(greeting) greeting.length() // has no explicit parameter Implicit parameter: The object on which a method is invoked System.out.println(greeting) Implicit and Explicit Parameters

Return value: A result that the method has computed for use by the code that called it int n = greeting.length(); // return value stored in n Return Values

You can also use the return value as a parameter of another method: System.out.println(greeting.length()); Not all methods return values. Example: println Passing Return Values

Animation 2.2

This method call has one implicit parameter: the string "Mississippi" two explicit parameters: the strings "issipp" and "our" a return value: the string "Missouri" replace method carries out a search-and-replace operation river.replace(“issipp”, “our”) // constructs a new string (Missouri”)‏ A More Complex Call

Method definition specifies types of explicit parameters and return value Type of implicit parameter = current class; not mentioned in method definition Example: Class String defines public int length() // return type: int // no explicit parameter public String replace(String target, String replacement) // return type: String; // two explicit parameters of type String Method Definitions

If method returns no value, the return type is declared as void public void println(String output) // in class PrintStream A method name is overloaded if a class has more than one method with the same name (but different parameter types) public void println(String output)‏ public void println(int output)‏ Method Definitions

Assume that river has been defined as follows: String river = “Mississippi!”; What are the implicit parameters, explicit parameters, and return values in the method call river.length ()? Answer: The implicit parameter is river. There is no explicit parameter. The return value is 11. Self Check 2.9

What is the result of the call river.replace("p", "s") ? Answer: "Missississi". Self Check 2.10

Assume that greeting has been defined as follows: String greeting = “Hello, World!”; What is the result of the following call: greeting.replace("World", "Dave").length() Answer: 12. Self Check 2.11

How is the toUpperCase method defined in the String class? Answer: As public String toUpperCase(), with no explicit parameter and return type String. Self Check 2.12

Integers: short, int, long 13 Floating point numbers: float, double When a floating-point number is multiplied or divided by 10, only the position of the decimal point changes; it "floats". This representation is related to the "scientific" notation 1.3 × E-4 // 1.3 × written in Java Numbers are not objects; numbers types are primitive types Number Types

Operators: + - * 10 + n n – 1 10 * n // 10 × n As in mathematics, the * operator binds more strongly than the + operator x + y * 2 // means the sum of x and y * 2 (x + y) * 2 // multiplies the sum of x and y with 2 Arithmetic Operations

Which number type would you use for storing the area of a circle? Answer: double. Self Check 2.13

Why is the expression 13.println() an error? Answer: An int is not an object, and you cannot call a method on it. Self Check 2.14

Write an expression to compute the average of the values x and y. Answer: (x + y) * 0.5 Self Check 2.15

Objects of type Rectangle describe rectangular shapes Rectangular Shapes and Rectangle Objects

A Rectangle object isn't a rectangular shape – it is an object that contains a set of numbers that describe the rectangle Rectangular Shapes and Rectangle Objects

new Rectangle(5, 10, 20, 30) Detail: The new operator makes a Rectangle object It uses the parameters (in this case, 5, 10, 20, and 30 ) to initialize the data of the object It returns the object Usually the output of the new operator is stored in a variable Rectangle box = new Rectangle(5, 10, 20, 30); Constructing Objects

The process of creating a new object is called construction The four values 5, 10, 20, and 30 are called the construction parameters Some classes let you construct objects in multiple ways new Rectangle() // constructs a rectangle with its top left corner // at the origin (0, 0), width 0, and height 0 Constructing Objects

new ClassName(parameters) Example: new Rectangle(5, 10, 20, 30) new Rectangle() Purpose: To construct a new object, initialize it with the construction parameters, and return a reference to the constructed object. Syntax 2.3 Object Construction

How do you construct a square with center (100, 100) and side length 20? Answer: new Rectangle(90, 90, 20, 20)‏ Self Check 2.16

What does the following statement print? System.out.println(new Rectangle().getWidth()); Answer: 0 Self Check 2.17

Accessor method: does not change the state of its implicit parameter double width = box.getWidth(); Mutator method: changes the state of its implicit parameter box.translate(15, 25); Accessor and Mutator Methods

Is the toUpperCase method of the String class an accessor or a mutator? Answer: An accessor – it doesn't modify the original string but returns a new string with uppercase letters. Self Check 2.18

Assume the following call has been made: Rectangle box = new Rectangle(5, 10, 20, 30); Which call to translate is needed to move the box rectangle so that its top-left corner is the origin (0, 0)? Answer: box.translate(-5, -10) Self Check 2.19