Chapter 2: Using Objects

Similar documents
Chapter 2: Elements of Java

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

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

Introduction to Python

Chapter 1 Java Program Design and Development

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

Introduction to Programming

Variables, Constants, and Data Types

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

Moving from CS 61A Scheme to CS 61B Java

Part 1 Foundations of object orientation

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Introduction to Java. CS 3: Computer Programming in Java

Java Basics: Data Types, Variables, and Loops

MAT 2170: Laboratory 3

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

Chapter 3. Input and output. 3.1 The System class

CS 106 Introduction to Computer Science I

Introduction to programming

Lecture 5: Java Fundamentals III

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

Number Representation

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

Chapter One Introduction to Programming

Chapter 2 Elementary Programming

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Install Java Development Kit (JDK) 1.8

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Chapter 5 Names, Bindings, Type Checking, and Scopes

Reading and Understanding Java s API Documentation

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

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

Pemrograman Dasar. Basic Elements Of Java

LAB 3 Part 1 OBJECTS & CLASSES

AP Computer Science Java Subset

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Computer Programming I

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Java Crash Course Part I

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

CSC 221: Computer Programming I. Fall 2006

Object-Oriented Programming in Java

Introduction to Python

Part I. The Picture class

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

Data Storage. Chapter 3. Objectives. 3-1 Data Types. Data Inside the Computer. After studying this chapter, students should be able to:

Java CPD (I) Frans Coenen Department of Computer Science

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

java Features Version April 19, 2013 by Thorsten Kracht

Java Classes. GEEN163 Introduction to Computer Programming

Object Oriented Software Design

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

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

Programming Languages CIS 443

Appendix K Introduction to Microsoft Visual C++ 6.0

D06 PROGRAMMING with JAVA

Understanding class definitions

Number Sense and Operations

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

Conditionals (with solutions)

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Object Oriented Software Design

AP Computer Science Static Methods, Strings, User Input

Building Java Programs

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

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

Comp 248 Introduction to Programming

Dŵr y Felin Comprehensive School. Perimeter, Area and Volume Methodology Booklet

6.1. Example: A Tip Calculator 6-1

Developing Conceptual Understanding of Number. Set J: Perimeter and Area

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

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

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Chapter 4: Computer Codes

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

Introduction to Data Structures

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Algorithms, Flowcharts & Program Design. ComPro

Introduction to Java

CSE 1020 Introduction to Computer Science I A sample nal exam

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

Florida Department of Education/Office of Assessment January Grade 6 FCAT 2.0 Mathematics Achievement Level Descriptions

Programming and Data Structures with Java and JUnit. Rick Mercer

Event-Driven Programming

6.170 Tutorial 3 - Ruby Basics

A Concrete Introduction. to the Abstract Concepts. of Integers and Algebra using Algebra Tiles

Programmierpraktikum

Some Scanner Class Methods

Chapter 13 - Inheritance

The string of digits in the binary number system represents the quantity

1998. (R. Bird and P. Wadler, Introduction to Functional Programming, Prentice

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

The programming language C. sws1 1

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Cobol. By: Steven Conner. COBOL, COmmon Business Oriented Language, one of the. oldest programming languages, was designed in the last six

CS 170, Section 000, Fall 2009

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

Database Programming with PL/SQL: Learning Objectives

Building Java Programs

Transcription:

Chapter Goals To learn about variables To understand the concepts of classes and objects Chapter 2: Using Objects Part 1 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 Types and Variables 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); Syntax 2.1 Variable Definition 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). A variable's type must match its value String greeting = 13 // ERROR: Types don't match 1

Identifiers 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 ) Self Check 2.1 What is the type of the values 0 and "0"? Answer: int and String. e.g. luckynumber, numberofimages, longtimenosee Self Check 2.2 Which of the following are legal identifiers? Greeting1 g void 101dalmatians Hello, World <greeting> Self Check 2.3 Define a variable to hold your name. Use camel case in the variable name. Answer: String myname = Andrew Vardy"; Answer: Only the first two are legal identifiers. 2

The Assignment Operator 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; Uninitialized Variables Error: int luckynumber; System.out.println(luckyNumber); // ERROR uninitialized variable 3

Syntax 2.2 Assignment Animation 2.1 variablename = value; Example: luckynumber = 12; Purpose: To assign a new value to a previously declared variable. Self Check 2.4 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.5 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. 4

Objects and Classes 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 Methods 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 A Representation of Two String Objects String Methods 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 5

Self Check 2.6 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.7 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.8 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. Implicit and Explicit Parameters 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) 6

Return Values 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 Passing 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 Animation 2.2 A More Complex Call replace method carries out a search-and-replace operation river.replace( issipp, our ) // constructs a new string (Missouri )?Ü This method call has one implicit parameter: the string "Mississippi" two explicit parameters: the strings "issipp" and "our" a return value: the string "Missouri" 7

Method Definitions 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)?ê Self Check 2.9 Assume that river has been defined as follows: String river = Mississippi! ; Self Check 2.10 What is the result of the call river.replace("p", "s")? Answer: "Missississi". 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. 8

Self Check 2.11 Assume that greeting has been defined as follows: String greeting = Hello, World! ; What is the result of the following call: Self Check 2.12 How is the touppercase method defined in the String class? Answer: As public String touppercase(), with no explicit parameter and return type String. greeting.replace("world", "Dave").length() Answer: 12. Number Types Integers: short, int, long 13 Floating point numbers: float, double 1.3 0.00013 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 10-4. 1.3E-4 // 1.3 10-4 written in Java Numbers are not objects; numbers types are primitive types Arithmetic Operations 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 9

Self Check 2.13 Which number type would you use for storing the area of a circle? Answer: double. Self Check 2.14 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.15 Write an expression to compute the average of the values x and y. Rectangular Shapes and Rectangle Objects Objects of type Rectangle describe rectangular shapes Answer: (x + y) * 0.5 10

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 Constructing 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 Syntax 2.3 Object Construction 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. 11

Self Check 2.16 How do you construct a square with center (100, 100) and side length 20? Answer: new Rectangle(90, 90, 20, 20)? Self Check 2.17 What does the following statement print? System.out.println(new Rectangle().getWidth()); Answer: 0 Accessor and Mutator Methods 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); Self Check 2.18 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. 12

Self Check 2.19 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) 13