SlideShare a Scribd company logo
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 2 – Using Objects
Copyright © 2014 by John Wiley & Sons. All rights reserved. 2
Chapter Goals
 What is an “object”?
 Why do we use objects?
 How to we use objects?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 3
Objects and Classes
Each part a home builder uses,
such as a furnace or a water
heater, fulfills a particular
function. Similarly, you build
programs from objects, each of
which has a particular behavior.
In Java, you build programs for objects.
Each object has certain behaviors.
You can manipulate the object to get certain effects.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 4
Using Objects
 Object: an entity in your program that you can manipulate
by calling one or more of its methods.
 Method: consists of a sequence of instructions that can
access the data of an object.
• You do not know what the instructions are
• You do know that the behavior is well defined
 System.out has a println method
• You do not know how it works
• What is important is that it does the work you request of it
Copyright © 2014 by John Wiley & Sons. All rights reserved. 5
Using Objects
Figure 1 Representation of the System.out Object
Copyright © 2014 by John Wiley & Sons. All rights reserved. 6
Using Objects
You can think of a water heater as an
object that can carry out the "get hot
water" method. When you call that
method to enjoy a hot shower, you
don't care whether the water heater
uses gas or solar power.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
Classes
 A class describes a set of objects with the same behavior.
 Some string objects:
"Hello World"
"Goodbye"
"Mississippi"
 You can invoke the same methods on all strings.
 System.out is a member of the PrintStream class that writes
to the console window.
 You can construct other objects of PrintStream class that
write to different destinations.
 All PrintStream objects have methods println and print.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 8
Classes
 Objects of the PrintStream class have a completely different
behavior than the objects of the String class.
 Different classes have different responsibilities
• A string knows about the letters that it contains
• A string doesn't know how to send itself to a console window or file.
 All objects of the Window class share the same behavior.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 9
Self Check 2.1
In Java, objects are grouped into classes according to their
behavior. Would a window object and a water heater object
belong to the same class or to different classes? Why?
Answer: Objects with the same behavior belong to the
same class. A window lets in light while protecting a
room from the outside wind and heat or cold. A water
heater has completely different behavior. It heats water.
They belong to different classes.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 10
Self Check 2.2
Some light bulbs use a glowing filament, others use a
fluorescent gas. If you consider a light bulb a Java object
with an "illuminate" method, would you need to know which
kind of bulb it is?
Answer: When one calls a method, one is not concerned
with how it does its job. As long as a light bulb
illuminates a room, it doesn't matter to the occupant how
the photons are produced.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 11
Variables
 Use a variable to store a value that you want to use later
 To declare a variable named width:
int width = 20;
 Like a variable in a computer program, a parking space has an
identifier and a contents.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 12
Syntax 2.1 Variable Declaration
Copyright © 2014 by John Wiley & Sons. All rights reserved. 13
Variables
 A variable is a storage location
• Has a name and holds a value
 When declaring a variable, you usually specify an initial
value.
 When declaring a variable, you also specify the type of its
values.
 Variable declaration: int width = 20:
• width is the name
• int is the type
• 20 is the initial value
Copyright © 2014 by John Wiley & Sons. All rights reserved. 14
Variables
 Each parking space is suitable for a particular type of vehicle,
just as each variable holds a value of a particular type.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
Variable Declarations
Copyright © 2014 by John Wiley & Sons. All rights reserved. 16
Types
 Use the int type for numbers that cannot have a fractional
part.
int width = 20;
 Use the double type for floating point numbers.
double milesPerGallon = 22.5;
 Numbers can be combined by arithmetic operators such as
+, -, and *
 Another type is String
String greeting = "Hello";
 A type specifies the operations that can be carried out with
its values.
• You can multiply the value width holds by a number
• You can not multiply greetings by a number.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 17
Names
 Pick a name for a variable that describes its purpose.
 Rules for the names of variables, methods, and classes:
• Must start with a letter or the underscore (_) character, and the
remaining characters must be letters, numbers, or underscores.
• Cannot use other symbols such as ? or % or a space
• Use uppercase letters to denote word boundaries, as in milesPerGallon.
(Called camel case)
 Names are case sensitive
 You cannot use reserved words such as double or class
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
Names
 By Java convention:
• variable names start with a lowercase letter.
• class names start with an uppercase letter.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
Variable Names in Java
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
Comments
 Use comments to add explanations for humans who read your
code.
double milesPerGallon = 33.8; // The average fuel efficiency of new U.S. cars in 2011
 The compiler does not process comments
 It ignores everything from a // delimiter to the end of the line.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
Comments
 For longer comment, enclose it between /* and */ delimiters.
• The compiler ignores these delimiters and everything in between.
 Example of longer comments
/* In most countries, fuel efficiency is measured in liters per hundred
kilometer. Perhaps that is more useful—it tells you how much gas you
need to purchase to drive a given distance. Here is the conversion
formula. */
double fuelEfficiency = 235.214583 / milesPerGallon;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
Assignment
 Use the assignment operator (=) to change the value of a
variable.
 You have the following variable declaration
int width = 10;
 To change the value of the variable, assign the new value
width = 20;
Figure 2 Assigning a New Value to a Variable
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
Assignment
 It is an error to use a variable that has never had a value
assigned to it:
int height;
int width = height; // ERROR - uninitialized variable height
• The compiler will complain about an "uninitialized variable"
Figure 3 An Uninitialized Variable
 Remedy: assign a value to the variable before you use it.
int height;
int width = height; // OK
 All variables must be initialized before you access them.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 24
Assignment
 The right-hand side of the = symbol can be a mathematical
expression:
width = height + 10;
• This means
1. compute the value of height + 10
2. store that value in the variable width
width = width + 10
 The assignment operator = does not denote mathematical
equality.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 25
Assignment
Figure 4 Executing the Statement width = width + 10
Copyright © 2014 by John Wiley & Sons. All rights reserved. 26
Syntax 2.2 Assignment
Copyright © 2014 by John Wiley & Sons. All rights reserved. 27
Self Check 2.3
What is wrong with the following variable declaration?
int miles per gallon = 39.4
Answer: There are three errors:
1. You cannot have spaces in variable names.
2. The variable type should be double because it holds a
fractional value.
3. There is a semicolon missing at the end of the statement.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 28
Self Check 2.4
Declare and initialize two variables, unitPrice and quantity,
to contain the unit price of a single item and the number of
items purchased. Use reasonable initial values.
Answer:
double unitPrice = 1.95;
int quantity = 2;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 29
Self Check 2.5
Use the variables declared in Self Check 4 to display the
total purchase price.
Answer:
System.out.print("Total price: ");
System.out.println(unitPrice * quantity);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 30
Self Check 2.6
What are the types of the values 0 and "0"?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 31
Self Check 2.6
What are the types of the values 0 and "0"?
Answer: int and String
Copyright © 2014 by John Wiley & Sons. All rights reserved. 32
Self Check 2.7
Which number type would you use for storing the area of a circle?
Answer: double
Copyright © 2014 by John Wiley & Sons. All rights reserved. 33
Self Check 2.8
Which of the following are legal identifiers?
Greeting1
g
void
101dalmatians
Hello, World
<greeting>
Answer: Only the first two are legal identifiers.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 34
Self Check 2.9
Declare a variable to hold your name. Use camel case in the
variable name.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 35
Self Check 2.9
Declare a variable to hold your name. Use camel case in the
variable name.
Answer:
String myName = "John Q. Public";
Copyright © 2014 by John Wiley & Sons. All rights reserved. 36
Self Check 2.10
Is 12 = 12 a valid expression in the Java language?
Answer: No, the left-hand side of the = operator must be a
variable.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 37
Self Check 2.11
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 declares a new
variable
Copyright © 2014 by John Wiley & Sons. All rights reserved. 38
Self Check 2.12
How would you explain assignment using the parking space
analogy?
Answer: Assignment would occur when one car is replaced
by another in the parking space.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 39
Calling Methods
 You use an object by calling its methods.
 All objects of a given class share a common set of methods.
 The PrintStream class provides methods for its objects such as:
• println
• print
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
Calling Methods
 The String class provides methods that you can apply to all
String objects.
 Example: length
String greeting = “Hello, World!”;
int numberOfCharacters = greeting.length();
 Example: toUpperCase
String river = “Mississippi”;
String bigRiver = river.toUpperCase();
Copyright © 2014 by John Wiley & Sons. All rights reserved. 41
The Public Interface of a Class
The controls of a car form its public
interface. The private implementation
is under the hood.
 The String class declares many other methods besides the
length and toUpperCase methods.
 Collectively, the methods form the public interface of the class.
 The public interface of a class specifies what you can do with
its objects.
 The hidden implementation describes how these actions are
carried out.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 42
A Representation of Two String Objects
 Each String object stores its own data.
 Both objects support the same set of methods.
• Those methods form the public interface
• Public interface is specified by the String class.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
Method Arguments
 Most methods require values that give details about the work
that the method needs to do.
 You must supply the string that should be printed when you call
the println method.
 The technical term for method inputs: arguments.
 The string greeting is an argument of this method call:
System.out.println(greeting);
Figure 6 Passing an Argument to the println Method
Copyright © 2014 by John Wiley & Sons. All rights reserved. 44
Method Arguments
At this tailor shop, the customer's
measurements and the fabric are the
arguments of the sew method. The
return value is the finished garment.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 45
Method Arguments
 Some methods require multiple arguments.
 Other methods don't require any arguments at all.
• Example: the length method of the String class
• All the information that the length method requires to do its job is stored
in the object
Figure 7 Invoking the length Method on a String Object
Copyright © 2014 by John Wiley & Sons. All rights reserved. 46
Return Values
 Some methods carry out an action for you.
• Example: println method
 Other methods compute and return a value.
• Example: the String length method
• returns a value: the number of characters in the string.
• You can store the return value in a variable:
int numberOfCharacters = greeting.length()
 The return value of a method is a result that the method has
computed.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 47
Return Values
 You can also use the return value of one method as an
argument of another method:
System.out.println(greeting.length());
• The method call greeting.length() returns a value - the integer 13.
• The return value becomes an argument of the println method.
Figure 8 Passing the Result of a Method Call to Another
Method
Copyright © 2014 by John Wiley & Sons. All rights reserved. 48
Return Values – replace Method
Example: assume String river = "Mississippi";
 Then the statement
river = river.replace("issipp", "our");
• Constructs a new String by
• Replacing all occurrences of "issipp" in "Mississippi" with "our"
• Returns the constructed String object "Missouri"
• And saves the return value in the same variable
 You could pass the return value to another method:
System.out.println(river.replace("issipp", "our"));
Copyright © 2014 by John Wiley & Sons. All rights reserved. 49
Return Values – replace Method - continued
 The method call
river.replace("issipp", "our"))
• Is invoked on a String object: "Mississippi"
• Has two arguments: the strings "issipp" and "our"
• Returns a value: the string "Missouri"
Figure 9 Calling the replace Method
Copyright © 2014 by John Wiley & Sons. All rights reserved. 50
Method Arguments and Return Values
Copyright © 2014 by John Wiley & Sons. All rights reserved. 51
Method Declaration
 To declare a method in a class, specify
• The types of the arguments
• The return value
 Example:
public int length()
• There are no arguments
• The return value has the type int
Copyright © 2014 by John Wiley & Sons. All rights reserved. 52
Method Declaration - continued
 Example:
public String replace(String target, String replacement)
• Has two arguments, target and replacement
• Both arguments have type String
• The returned value is another string
 Example:
public void println(String output)
• Has an argument of type String
• No return value
• Uses the keyword void
Copyright © 2014 by John Wiley & Sons. All rights reserved. 53
Method Declaration - continued
 A class can declare two methods with the same name and
different argument types.
 The PrintStream class declares another println method
public void println(int output)
• Used to print an integer value
 The println name is overloaded because it refers to more than
one method.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
Self Check 2.13
How can you compute the length of the string "Mississippi"?
Answer: river.length() or "Mississippi".length()
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
Self Check 2.14
How can you print out the uppercase version of
"Hello, World!"?
Answer:
System.out.println(greeting.toUpperCase());
or
System.out.println("Hello, World!".toUpperCase());
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
Self Check 2.15
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 57
Self Check 2.16
What are the arguments in the method call
river.replace("p", "s")?
Answer: The arguments are the strings "p" and "s".
Copyright © 2014 by John Wiley & Sons. All rights reserved. 58
Self Check 2.17
What is the result of the call river.replace("p", "s”), where river is
"Mississippi"?
Answer: "Missississi"
Copyright © 2014 by John Wiley & Sons. All rights reserved. 59
Self Check 2.18
What is the result of the call
greeting.replace("World", "Dave").length(),
where greeting is "Hello, World!"?
Answer: 12
Copyright © 2014 by John Wiley & Sons. All rights reserved. 60
Self Check 2.19
How is the toUpperCase method declared in the String class?
Answer: As public String toUpperCase(), with no argument
and return type String.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 61
Constructing Objects
Objects of the Rectangle class describe rectangular shapes.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 62
Copyright © 2014 by John Wiley & Sons. All rights reserved. 63
Constructing Objects
 The Rectangle object is not a rectangular shape.
 It is an object that contains a set of numbers.
• The numbers describe the rectangle
 Each rectangle is described by:
• The x- and y-coordinates of its top-left corner
• Its width
• And its height.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 64
Constructing Objects
 In the computer, a Rectangle object is a block of memory that
holds four numbers.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 65
Constructing Objects
 Use the new operator, followed by a class name and
arguments, to construct new 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
 The process of creating a new object is called construction.
 The four values 5, 10, 20, and 30 are called the construction
arguments.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 66
Constructing Objects
 Usually the output of the new operator is stored in a variable:
Rectangle box = new Rectangle(5, 10, 20, 30);
 Additional constructor:
new Rectangle()
Copyright © 2014 by John Wiley & Sons. All rights reserved. 67
Syntax 2.3 Object Construction
Copyright © 2014 by John Wiley & Sons. All rights reserved. 68
Self Check 2.20
How do you construct a square with center (100, 100) and
side length 20?
Answer:
new Rectangle(90, 90, 20, 20)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 69
Self Check 2.21
Initialize the variables box and box2 with two rectangles that
touch each other.
Answer:
Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 =
new Rectangle(25, 10, 20, 30);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 70
Self Check 2.22
The getWidth method returns the width of a Rectangle object.
What does the following statement print? System.out.println(new
Rectangle().getWidth());
Answer:
0
Copyright © 2014 by John Wiley & Sons. All rights reserved. 71
Self Check 2.23
The PrintStream class has a constructor whose argument is
the name of a file. How do you construct a PrintStream
object with the construction argument "output.txt"?
Answer:
new PrintStream("output.txt”);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 72
Self Check 2.24
Write a statement to save the object that you constructed in
Self Check 23 in a variable.
Answer:
PrintStream out = new PrintStream("output.txt");
Copyright © 2014 by John Wiley & Sons. All rights reserved. 73
Accessor and Mutator Methods
 Accessor method: does not change the internal data of the
object on which it is invoked.
• Returns information about the object
• Example: length method of the String class
• Example: double width = box.getWidth();
 Mutator method: changes the data of the object
box.translate(15, 25);
• The top-left corner is now at (20, 35).
Copyright © 2014 by John Wiley & Sons. All rights reserved. 74
Self Check 2.25
What does this sequence of statements print?
Rectangle box = new Rectangle(5, 10, 20, 30);
System.out.println("Before: " + box.getX());
box.translate(25, 40);
System.out.println("After: " + box.getX());
Answer:
Before: 5
After: 30
Copyright © 2014 by John Wiley & Sons. All rights reserved. 75
Self Check 2.26
What does this sequence of statements print?
Rectangle box = new Rectangle(5, 10, 20, 30);
System.out.println("Before: " + box.getWidth());
box.translate(25, 40);
System.out.println("After: " + box.getWidth());
Answer:
Before: 20
After: 20
Moving the rectangle does not affect its width or height.
You can change the width and height with the setSize
method.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 76
Self Check 2.27
What does this sequence of statements print?
String greeting = "Hello”;
System.out.println(greeting.toUpperCase());
System.out.println(greeting);
Answer:
HELLO
hello
Note that calling toUpperCase doesn't modify the string.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 77
Self Check 2.28
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 78
Self Check 2.29
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), provided the method is
called immediately after storing the new rectangle into
box.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 79
The API Documentation
 API: Application Programming Interface
 API documentation: lists classes and methods of the Java
library
 Application programmer: A programmer who uses the Java
classes to put together a computer program (or application)
 Systems Programmer: A programmer who designs and
implements library classes such as PrintStream and Rectangle
 http://docs.oracle.com/javase/7/docs/api/index.html
Copyright © 2014 by John Wiley & Sons. All rights reserved. 80
Browsing the API Documentation
 Locate Rectangle link in the left pane
 Click on the link
• The right pane shows all the features of the Rectangle class
Figure 13 The API
Documentation of
the Standard Java
Library
Copyright © 2014 by John Wiley & Sons. All rights reserved. 81
Browsing the API Documentation –
Method Summary
 The API documentation for each class has
• A section that describes the purpose of the class
• Summary tables for the constructors and methods
• Clicking on a method's link leads to a detailed description of the method
Figure 14 The Method
Summary for the Rectangle
Class
Copyright © 2014 by John Wiley & Sons. All rights reserved. 82
Browsing the API Documentation
 The detailed description of a method shows:
• The action that the method carries out
• The types and names of the parameter variables that receive the
arguments when the method is called
• The value that it returns (or the reserved word void if the method doesn't
return any value).
Copyright © 2014 by John Wiley & Sons. All rights reserved. 83
Packages
 Java classes are grouped into packages.
 The Rectangle class belongs to the package java.awt.
 To use the Rectangle class you must import the package:
import java.awt.Rectangle;
 Put the line at the top of your program.
 You don't need to import classes in the java.lang package such
as String and System.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 84
Syntax 2.4 Importing a Class from a Package
Copyright © 2014 by John Wiley & Sons. All rights reserved. 85
Self Check 2.30
Look at the API documentation of the String class. Which
method would you use to obtain the string "hello, world!"
from the string "Hello, World!"?
Answer: toLowerCase
Copyright © 2014 by John Wiley & Sons. All rights reserved. 86
Self Check 2.31
In the API documentation of the String class, look at the
description of the trim method. What is the result of applying
trim to the string " Hello, Space ! "? (Note the spaces in the
string.)
Answer: "Hello, Space !" – only the leading and trailing
spaces are trimmed.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 87
Self Check 2.32
Look into the API documentation of the Rectangle class.
What is the difference between the methods
void translate(int x, int y) and
void setLocation(int x, int y)?
Answer: The arguments of the translate method tell how far to
move the rectangle in the x- and y-directions. The arguments
of the setLocation method indicate the new x- and y-values for
the top-left corner. For example,
box.translate(1, 1)
moves the box one pixel down and to the right.
box.setLocation( 1, 1)
moves box to the top-left corner of the screen.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 88
Self Check 2.33
The Random class is declared in the java.util package.
What do you need to do in order to use that class in your
program?
Answer: Add the statement
import java.util.Random;
at the top of your program.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 89
Self Check 2.34
In which package is the BigInteger class located? Look it up
in the API documentation.
Answer: In the java.math package
Copyright © 2014 by John Wiley & Sons. All rights reserved. 90
Implementing a Test Program
 A test program verifies that methods behave as expected.
 Steps in writing a tester class
1. Provide a tester class.
2. Supply a main method.
3. Inside the main method, construct one or more objects.
4. Apply methods to the objects.
5. Display the results of the method calls.
6. Display the values that you expect to get.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 91
Implementing a Test Program
 Code to test the behavior of the translate method
Rectangle box = new Rectangle(5, 10, 20, 30); // Move the rectangle
box.translate(15, 25); // Print information about the moved rectangle
System.out.print("x: ");
System.out.println(box.getX());
System.out.println("Expected: 20");
 Place the code inside the main method of the MoveTester
class.
 Determining the expected result in advance is an important part
of testing.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 92
section_7/MoveTester.java
1 import java.awt.Rectangle;
2
3 public class MoveTester
4 {
5 public static void main(String[] args)
6 {
7 Rectangle box = new Rectangle(5, 10, 20, 30);
8
9 // Move the rectangle
10 box.translate(15, 25);
11
12 // Print information about the moved rectangle
13 System.out.print("x: ");
14 System.out.println(box.getX());
15 System.out.println("Expected: 20");
16
17 System.out.print("y: ");
18 System.out.println(box.getY());
19 System.out.println("Expected: 35");
20 }
21 }
Program Run:
x: 20
Expected: 20
y: 35
Expected: 35
Copyright © 2014 by John Wiley & Sons. All rights reserved. 93
Self Check 2.35
Suppose we had called box.translate(25, 15) instead of
box.translate(15, 25). What are the expected outputs?
Answer:
x: 30, y: 25
Copyright © 2014 by John Wiley & Sons. All rights reserved. 94
Self Check 2.36
Why doesn't the MoveTester program print the width and
height of the rectangle?
Answer: Because the translate method doesn't modify the
shape of the rectangle.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 95
Object References
 An object variable is a variable whose type is a class
• Does not actually hold an object.
• Holds the memory location of an object
Figure 15 An Object Variable Containing an Object Reference
Copyright © 2014 by John Wiley & Sons. All rights reserved. 96
Object References
 Object reference: describes the location of an object
 After this statement:
Rectangle box = new Rectangle(5, 10, 20, 30);
• Variable box refers to the Rectangle object returned by the new operator
• The box variable does not contain the object. It refers to the object.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 97
Object References
 Multiple object variables can refer to the same object:
Rectangle box = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box;
Figure 16 Two Object Variables Referring to the Same Object
Copyright © 2014 by John Wiley & Sons. All rights reserved. 98
Numbers
 Numbers are not objects.
 Number variables actually store numbers.
Figure 17 A Number Variable Stores a Number
Copyright © 2014 by John Wiley & Sons. All rights reserved. 99
Copying Numbers
 When you copy a number
• the original and the copy of the number are independent values.
int luckyNumber = 13;
int luckyNumber2 = luckyNumber;
luckyNumber2 = 12;
Figure 18 Copying Numbers
Copyright © 2014 by John Wiley & Sons. All rights reserved. 100
Copying Object References
 When you copy an object reference
• both the original and the copy are references to the same object
Rectangle box = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box;
box2.translate(15, 25);
Figure 19 Copying Object References
Copyright © 2014 by John Wiley & Sons. All rights reserved. 101
Self Check 2.37
What is the effect of the assignment
greeting2 = greeting?
Answer: Now greeting and greeting2 both refer to the
same String object.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 102
Self Check 2.38
After calling greeting2.toUpperCase(), what are the contents
of greeting and greeting2?
Answer: Both variables still refer to the same string, and
the string has not been modified. Recall that the
toUpperCase method constructs a new string that
contains uppercase characters, leaving the original string
unchanged.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 103
Mainframe Computer
Mainframe Computer
Copyright © 2014 by John Wiley & Sons. All rights reserved. 104
Graphical Applications: Frame Windows
A graphical application shows information inside a frame.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 105
Frame Windows
 To show a frame:
1. Construct an object of the JFrame class:
JFrame frame = new JFrame();
2. Set the size of the frame:
frame.setSize(300, 400);
3. If you'd like, set the title of the frame:
frame.setTitle("An empty Frame");
4. Set the "default close operation”:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
5. Make the frame visible:
frame.setVisible(true);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 106
section_9_1/EmptyFrameViewer.java
1 import javax.swing.JFrame;
2
3 public class EmptyFrameViewer
4 {
5 public static void main(String[] args)
6 {
7 JFrame frame = new JFrame();
8 frame.setSize(300, 400);
9 frame.setTitle("An empty frame");
10 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
11 frame.setVisible(true);
12 }
13 }
Figure 20 A Frame Window
Copyright © 2014 by John Wiley & Sons. All rights reserved. 107
Drawing on a Component
 In order to display a drawing in a frame, define a class that
extends the JComponent class.
 Place drawing instructions inside the paintComponent method.
• That method is called whenever the component needs to be repainted:
public class RectangleComponent extends Jcomponent
{
public void paintComponent(Graphics g)
{
Drawing instructions go here
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 108
Classes Graphics and Graphics2D
 Graphics class stores the graphics state (such as current color).
 Graphics2D class has methods to draw shape objects.
 Use a cast to recover the Graphics2D object from the Graphics parameter:
public class RectangleComponent extends Jcomponent
{
public void paintComponent(Graphics g)
{
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
. . .
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 109
Classes Graphics and Graphics2D
 The draw method of the Graphics2D class draws shapes, such
as rectangles, ellipses, line segments, polygons, and arcs:
public class RectangleComponent extends Jcomponent
{
public void paintComponent(Graphics g)
{
. . .
Rectangle box = new Rectangle(5, 10, 20, 30);
g2.draw(box);
. . .
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 110
Coordinate System of a Component
 The origin (0, 0) is at the upper-left corner of the component.
 The y-coordinate grows downward.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 111
Drawing Rectangles
We want to create an application to display two rectangles.
Figure 21 Drawing Rectangles
Copyright © 2014 by John Wiley & Sons. All rights reserved. 112
section_9_2/RectangleComponent.java
1 import java.awt.Graphics;
2 import java.awt.Graphics2D;
3 import java.awt.Rectangle;
4 import javax.swing.JComponent;
5
6 /*
7 A component that draws two rectangles.
8 */
9 public class RectangleComponent extends JComponent
10 {
11 public void paintComponent(Graphics g)
12 {
13 // Recover Graphics2D
14 Graphics2D g2 = (Graphics2D) g;
15
16 // Construct a rectangle and draw it
17 Rectangle box = new Rectangle(5, 10, 20, 30);
18 g2.draw(box);
19
20 // Move rectangle 15 units to the right and 25 units down
21 box.translate(15, 25);
22
23 // Draw moved rectangle
24 g2.draw(box);
25 }
26 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 113
Displaying a Component in a Frame
 In a graphical application you need:
• A frame to show the application
• A component for the drawing.
 The steps for combining the two:
1. Construct a frame object and configure it.
2. Construct an object of your component class:
RectangleComponent component = new RectangleComponent();
3. Add the component to the frame:
frame.add(component);
4. Make the frame visible.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 114
section_9_3/RectangleViewer.java
1 import javax.swing.JFrame;
2
3 public class RectangleViewer
4 {
5 public static void main(String[] args)
6 {
7 JFrame frame = new JFrame();
8
9 frame.setSize(300, 400);
10 frame.setTitle("Two rectangles");
11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12
13 RectangleComponent component = new RectangleComponent();
14 frame.add(component);
15
16 frame.setVisible(true);
17 }
18 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 115
Self Check 2.39
How do you display a square frame with a title bar that
reads "Hello, World!"?
Answer: Modify the EmptyFrameViewer program as
follows:
frame.setSize(300, 300);
frame.setTitle("Hello, World!");
Copyright © 2014 by John Wiley & Sons. All rights reserved. 116
Self Check 2.40
How can a program display two frames at once?
Answer: Construct two JFrame objects, set each of their
sizes, and call setVisible(true) on each of them.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 117
Self Check 2.41
How do you modify the program to draw two squares?
Answer:
Rectangle box = new Rectangle(5, 10, 20, 20);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 118
Self Check 2.42
How do you modify the program to draw one rectangle and
one square?
Answer: Replace the call to box.translate(15, 25) with
box = new Rectangle(20, 35, 20, 20);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 119
Self Check 2.43
What happens if you call g.draw(box) instead of
g2.draw(box)?
Answer: The compiler complains that g doesn't have a draw
method.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 120
Ellipses
 To construct an ellipse, you specify its bounding box.
Figure 22 An Ellipse and Its Bounding Box
 To construct an ellipse:
Ellipse2D.Double ellipse =
new Ellipse2D.Double(x, y, width, height);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 121
Ellipses
 Ellipse2D.Double is an inner class — doesn't matter to us
except for the import statement:
import java.awt.geom.Ellipse2D; // No .Double
 To draw the shape:
g2.draw(ellipse);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 122
Circles
 To draw a circle, set the width and height to the same values:
Ellipse2D.Double circle =
new Ellipse2D.Double(x, y, diameter, diameter);
g2.draw(circle);
 (x, y) is the top-left corner of the bounding box, not the center of
the circle.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 123
Lines
 To draw a line, specify its end points:
Line2D.Double segment =
new Line2D.Double(x1, y1, x2, y2);
g2.draw(segment);
 Or
Point2D.Double from = new Point2D.Double(x1, y1);
Point2D.Double to = new Point2D.Double(x2, y2);
Line2D.Double segment = new Line2D.Double(from, to);
g2.draw(segment);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 124
Drawing Text
 To draw text, use the drawString method
• Specify the string and the x- and y-coordinates of the basepoint of the
first character
g2.drawString("Message", 50, 100);
Figure 23 Basepoint and Baseline
Copyright © 2014 by John Wiley & Sons. All rights reserved. 125
Colors
 To draw in color, you need to supply a Color object.
 Specify the amount of red, green, blue as values between 0
and 255:
Color magenta = new Color(255, 0, 255);
 The Color class declares a variety of colors:
Color.BLUE, Color.RED, Color.PINK etc.
 To draw a shape in a different color
• First set color in graphics context:
g2.setColor(Color.Red);
g2.draw(circle); // Draws the shape in red
Copyright © 2014 by John Wiley & Sons. All rights reserved. 126
Colors
 To color the inside of the shape, use the fill method:
g2.fill(circle); // Fills with current color
 When you set a new color in the graphics context, it is used for
subsequent drawing operations.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 127
Predefined Colors
Copyright © 2014 by John Wiley & Sons. All rights reserved. 128
Alien Face
The code is on following slides:
Figure 24 An Alien Face
Copyright © 2014 by John Wiley & Sons. All rights reserved. 129
section_10/FaceComponent.java
1 import java.awt.Color;
2 import java.awt.Graphics;
3 import java.awt.Graphics2D;
4 import java.awt.Rectangle;
5 import java.awt.geom.Ellipse2D;
6 import java.awt.geom.Line2D;
7 import javax.swing.JComponent;
8
9 /*
10 A component that draws an alien face
11 */
12 public class FaceComponent extends JComponent
13 {
14 public void paintComponent(Graphics g)
15 {
16 // Recover Graphics2D
17 Graphics2D g2 = (Graphics2D) g;
18
19 // Draw the head
20 Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150);
21 g2.draw(head);
22
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 130
section_10/FaceComponent.java
23 // Draw the eyes
24 g2.setColor(Color.GREEN);
25 Rectangle eye = new Rectangle(25, 70, 15, 15);
26 g2.fill(eye);
27 eye.translate(50, 0);
28 g2.fill(eye);
29
30 // Draw the mouth
31 Line2D.Double mouth = new Line2D.Double(30, 110, 80, 110);
32 g2.setColor(Color.RED);
33 g2.draw(mouth);
34
35 // Draw the greeting
36 g2.setColor(Color.BLUE);
37 g2.drawString("Hello, World!", 5, 175);
38 }
39 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 131
section_10/FaceViewer.java
1 import javax.swing.JFrame;
2
3 public class FaceViewer
4 {
5 public static void main(String[] args)
6 {
7 JFrame frame = new JFrame();
8 frame.setSize(150, 250);
9 frame.setTitle("An Alien Face");
10 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
11
12 FaceComponent component = new FaceComponent();
13 frame.add(component);
14
15 frame.setVisible(true);
16 }
17 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 132
Self Check 2.44
Give instructions to draw a circle with center (100, 100) and
radius 25.
Answer:
g2.draw(new Ellipse2D.Double(75, 75, 50, 50));
Copyright © 2014 by John Wiley & Sons. All rights reserved. 133
Self Check 2.45
Give instructions to draw a letter "V" by drawing two line
segments.
Answer:
Line2D.Double segment1 =
new Line2D.Double(0, 0, 10, 30);
g2.draw(segment1);
Line2D.Double segment2 =
new Line2D.Double(10, 30, 20, 0);
g2.draw(segment2);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 134
Self Check 2.46
Give instructions to draw a string consisting of the letter "V".
Answer:
g2.drawString("V", 0, 30);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 135
Self Check 2.47
What are the RGB color values of Color.BLUE?
Answer: 0, 0, and 255
Copyright © 2014 by John Wiley & Sons. All rights reserved. 136
Self Check 2.48
How do you draw a yellow square on a red background?
Answer: First fill a big red square, then fill a small yellow
square inside:
g2.setColor(Color.RED);
g2.fill(new Rectangle(0, 0, 200, 200));
g2.setColor(Color.YELLOW);
g2.fill(new Rectangle(50, 50, 100, 100));

More Related Content

What's hot

Icom4015 lecture15-f16
Icom4015 lecture15-f16Icom4015 lecture15-f16
Icom4015 lecture15-f16
BienvenidoVelezUPR
 
Icom4015 lecture9-f16
Icom4015 lecture9-f16Icom4015 lecture9-f16
Icom4015 lecture9-f16
BienvenidoVelezUPR
 
Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016
BienvenidoVelezUPR
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
BienvenidoVelezUPR
 
Icom4015 lecture3-f16
Icom4015 lecture3-f16Icom4015 lecture3-f16
Icom4015 lecture3-f16
BienvenidoVelezUPR
 
Icom4015 lecture11-s16
Icom4015 lecture11-s16Icom4015 lecture11-s16
Icom4015 lecture11-s16
BienvenidoVelezUPR
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
BienvenidoVelezUPR
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016
BienvenidoVelezUPR
 
Icom4015 lecture7-f16
Icom4015 lecture7-f16Icom4015 lecture7-f16
Icom4015 lecture7-f16
BienvenidoVelezUPR
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
BienvenidoVelezUPR
 
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 Powerpoint
Gus Sandoval
 
Ch3
Ch3Ch3
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
dplunkett
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
Ilio Catallo
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSVISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
Suraj Kumar
 
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 

What's hot (20)

Icom4015 lecture15-f16
Icom4015 lecture15-f16Icom4015 lecture15-f16
Icom4015 lecture15-f16
 
Icom4015 lecture9-f16
Icom4015 lecture9-f16Icom4015 lecture9-f16
Icom4015 lecture9-f16
 
Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
Icom4015 lecture3-f16
Icom4015 lecture3-f16Icom4015 lecture3-f16
Icom4015 lecture3-f16
 
Icom4015 lecture11-s16
Icom4015 lecture11-s16Icom4015 lecture11-s16
Icom4015 lecture11-s16
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016
 
Icom4015 lecture7-f16
Icom4015 lecture7-f16Icom4015 lecture7-f16
Icom4015 lecture7-f16
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
 
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 Powerpoint
 
Ch3
Ch3Ch3
Ch3
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSVISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
 
Operators in java
Operators in javaOperators in java
Operators in java
 

Similar to CIIC 4010 Chapter 1 f17

Clarity in Documentation
Clarity in DocumentationClarity in Documentation
Clarity in Documentation
Radhika Puthiyetath
 
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGEINTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
RathnaM16
 
classVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptxclassVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptx
MaaReddySanjiv
 
classVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptxclassVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptx
ssusere336f4
 
12.6-12.9.pptx
12.6-12.9.pptx12.6-12.9.pptx
12.6-12.9.pptx
WinterSnow16
 
Variables
VariablesVariables
Variables
Maha Saad
 
Basic Concepts of Programming_withlogo.pdf
Basic Concepts of Programming_withlogo.pdfBasic Concepts of Programming_withlogo.pdf
Basic Concepts of Programming_withlogo.pdf
GandhiSarthak
 
Oops concepts variables and How to handle variable in testing
Oops concepts variables and How to handle variable in testingOops concepts variables and How to handle variable in testing
Oops concepts variables and How to handle variable in testing
NILESH SAWARDEKAR
 
Chap10
Chap10Chap10
JAVA(module1).pptx
JAVA(module1).pptxJAVA(module1).pptx
JAVA(module1).pptx
SRKCREATIONS
 
Programming Style Guidelines for Java Programming The fo.docx
Programming Style Guidelines for Java Programming The fo.docxProgramming Style Guidelines for Java Programming The fo.docx
Programming Style Guidelines for Java Programming The fo.docx
wkyra78
 
Diving into VS 2015 Day3
Diving into VS 2015 Day3Diving into VS 2015 Day3
Diving into VS 2015 Day3
Akhil Mittal
 
OOP Using Java Ch2 all about oop .pptx
OOP Using Java Ch2  all about oop  .pptxOOP Using Java Ch2  all about oop  .pptx
OOP Using Java Ch2 all about oop .pptx
doopagamer
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
Fernando Torres
 
C#/.NET Little Pitfalls
C#/.NET Little PitfallsC#/.NET Little Pitfalls
C#/.NET Little Pitfalls
BlackRabbitCoder
 
Javascript breakdown-workbook
Javascript breakdown-workbookJavascript breakdown-workbook
Javascript breakdown-workbook
HARUN PEHLIVAN
 
Core java
Core javaCore java
Core java
Shivaraj R
 
Core java
Core javaCore java
Core java
Sun Technlogies
 
Week 2
Week 2Week 2
Week 2
EasyStudy3
 
Exam view dynamic recalculation files
Exam view dynamic recalculation filesExam view dynamic recalculation files
Exam view dynamic recalculation files
William McIntosh
 

Similar to CIIC 4010 Chapter 1 f17 (20)

Clarity in Documentation
Clarity in DocumentationClarity in Documentation
Clarity in Documentation
 
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGEINTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
 
classVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptxclassVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptx
 
classVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptxclassVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptx
 
12.6-12.9.pptx
12.6-12.9.pptx12.6-12.9.pptx
12.6-12.9.pptx
 
Variables
VariablesVariables
Variables
 
Basic Concepts of Programming_withlogo.pdf
Basic Concepts of Programming_withlogo.pdfBasic Concepts of Programming_withlogo.pdf
Basic Concepts of Programming_withlogo.pdf
 
Oops concepts variables and How to handle variable in testing
Oops concepts variables and How to handle variable in testingOops concepts variables and How to handle variable in testing
Oops concepts variables and How to handle variable in testing
 
Chap10
Chap10Chap10
Chap10
 
JAVA(module1).pptx
JAVA(module1).pptxJAVA(module1).pptx
JAVA(module1).pptx
 
Programming Style Guidelines for Java Programming The fo.docx
Programming Style Guidelines for Java Programming The fo.docxProgramming Style Guidelines for Java Programming The fo.docx
Programming Style Guidelines for Java Programming The fo.docx
 
Diving into VS 2015 Day3
Diving into VS 2015 Day3Diving into VS 2015 Day3
Diving into VS 2015 Day3
 
OOP Using Java Ch2 all about oop .pptx
OOP Using Java Ch2  all about oop  .pptxOOP Using Java Ch2  all about oop  .pptx
OOP Using Java Ch2 all about oop .pptx
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
 
C#/.NET Little Pitfalls
C#/.NET Little PitfallsC#/.NET Little Pitfalls
C#/.NET Little Pitfalls
 
Javascript breakdown-workbook
Javascript breakdown-workbookJavascript breakdown-workbook
Javascript breakdown-workbook
 
Core java
Core javaCore java
Core java
 
Core java
Core javaCore java
Core java
 
Week 2
Week 2Week 2
Week 2
 
Exam view dynamic recalculation files
Exam view dynamic recalculation filesExam view dynamic recalculation files
Exam view dynamic recalculation files
 

Recently uploaded

ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
NATURAL DEEP EUTECTIC SOLVENTS AS ANTI-FREEZING AGENT
NATURAL DEEP EUTECTIC SOLVENTS AS ANTI-FREEZING AGENTNATURAL DEEP EUTECTIC SOLVENTS AS ANTI-FREEZING AGENT
NATURAL DEEP EUTECTIC SOLVENTS AS ANTI-FREEZING AGENT
Addu25809
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
amsjournal
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
NazakatAliKhoso2
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
gray level transformation unit 3(image processing))
gray level transformation unit 3(image processing))gray level transformation unit 3(image processing))
gray level transformation unit 3(image processing))
shivani5543
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 

Recently uploaded (20)

ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
NATURAL DEEP EUTECTIC SOLVENTS AS ANTI-FREEZING AGENT
NATURAL DEEP EUTECTIC SOLVENTS AS ANTI-FREEZING AGENTNATURAL DEEP EUTECTIC SOLVENTS AS ANTI-FREEZING AGENT
NATURAL DEEP EUTECTIC SOLVENTS AS ANTI-FREEZING AGENT
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
gray level transformation unit 3(image processing))
gray level transformation unit 3(image processing))gray level transformation unit 3(image processing))
gray level transformation unit 3(image processing))
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 

CIIC 4010 Chapter 1 f17

  • 1. Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Chapter 2 – Using Objects
  • 2. Copyright © 2014 by John Wiley & Sons. All rights reserved. 2 Chapter Goals  What is an “object”?  Why do we use objects?  How to we use objects?
  • 3. Copyright © 2014 by John Wiley & Sons. All rights reserved. 3 Objects and Classes Each part a home builder uses, such as a furnace or a water heater, fulfills a particular function. Similarly, you build programs from objects, each of which has a particular behavior. In Java, you build programs for objects. Each object has certain behaviors. You can manipulate the object to get certain effects.
  • 4. Copyright © 2014 by John Wiley & Sons. All rights reserved. 4 Using Objects  Object: an entity in your program that you can manipulate by calling one or more of its methods.  Method: consists of a sequence of instructions that can access the data of an object. • You do not know what the instructions are • You do know that the behavior is well defined  System.out has a println method • You do not know how it works • What is important is that it does the work you request of it
  • 5. Copyright © 2014 by John Wiley & Sons. All rights reserved. 5 Using Objects Figure 1 Representation of the System.out Object
  • 6. Copyright © 2014 by John Wiley & Sons. All rights reserved. 6 Using Objects You can think of a water heater as an object that can carry out the "get hot water" method. When you call that method to enjoy a hot shower, you don't care whether the water heater uses gas or solar power.
  • 7. Copyright © 2014 by John Wiley & Sons. All rights reserved. 7 Classes  A class describes a set of objects with the same behavior.  Some string objects: "Hello World" "Goodbye" "Mississippi"  You can invoke the same methods on all strings.  System.out is a member of the PrintStream class that writes to the console window.  You can construct other objects of PrintStream class that write to different destinations.  All PrintStream objects have methods println and print.
  • 8. Copyright © 2014 by John Wiley & Sons. All rights reserved. 8 Classes  Objects of the PrintStream class have a completely different behavior than the objects of the String class.  Different classes have different responsibilities • A string knows about the letters that it contains • A string doesn't know how to send itself to a console window or file.  All objects of the Window class share the same behavior.
  • 9. Copyright © 2014 by John Wiley & Sons. All rights reserved. 9 Self Check 2.1 In Java, objects are grouped into classes according to their behavior. Would a window object and a water heater object belong to the same class or to different classes? Why? Answer: Objects with the same behavior belong to the same class. A window lets in light while protecting a room from the outside wind and heat or cold. A water heater has completely different behavior. It heats water. They belong to different classes.
  • 10. Copyright © 2014 by John Wiley & Sons. All rights reserved. 10 Self Check 2.2 Some light bulbs use a glowing filament, others use a fluorescent gas. If you consider a light bulb a Java object with an "illuminate" method, would you need to know which kind of bulb it is? Answer: When one calls a method, one is not concerned with how it does its job. As long as a light bulb illuminates a room, it doesn't matter to the occupant how the photons are produced.
  • 11. Copyright © 2014 by John Wiley & Sons. All rights reserved. 11 Variables  Use a variable to store a value that you want to use later  To declare a variable named width: int width = 20;  Like a variable in a computer program, a parking space has an identifier and a contents.
  • 12. Copyright © 2014 by John Wiley & Sons. All rights reserved. 12 Syntax 2.1 Variable Declaration
  • 13. Copyright © 2014 by John Wiley & Sons. All rights reserved. 13 Variables  A variable is a storage location • Has a name and holds a value  When declaring a variable, you usually specify an initial value.  When declaring a variable, you also specify the type of its values.  Variable declaration: int width = 20: • width is the name • int is the type • 20 is the initial value
  • 14. Copyright © 2014 by John Wiley & Sons. All rights reserved. 14 Variables  Each parking space is suitable for a particular type of vehicle, just as each variable holds a value of a particular type.
  • 15. Copyright © 2014 by John Wiley & Sons. All rights reserved. 15 Variable Declarations
  • 16. Copyright © 2014 by John Wiley & Sons. All rights reserved. 16 Types  Use the int type for numbers that cannot have a fractional part. int width = 20;  Use the double type for floating point numbers. double milesPerGallon = 22.5;  Numbers can be combined by arithmetic operators such as +, -, and *  Another type is String String greeting = "Hello";  A type specifies the operations that can be carried out with its values. • You can multiply the value width holds by a number • You can not multiply greetings by a number.
  • 17. Copyright © 2014 by John Wiley & Sons. All rights reserved. 17 Names  Pick a name for a variable that describes its purpose.  Rules for the names of variables, methods, and classes: • Must start with a letter or the underscore (_) character, and the remaining characters must be letters, numbers, or underscores. • Cannot use other symbols such as ? or % or a space • Use uppercase letters to denote word boundaries, as in milesPerGallon. (Called camel case)  Names are case sensitive  You cannot use reserved words such as double or class
  • 18. Copyright © 2014 by John Wiley & Sons. All rights reserved. 18 Names  By Java convention: • variable names start with a lowercase letter. • class names start with an uppercase letter.
  • 19. Copyright © 2014 by John Wiley & Sons. All rights reserved. 19 Variable Names in Java
  • 20. Copyright © 2014 by John Wiley & Sons. All rights reserved. 20 Comments  Use comments to add explanations for humans who read your code. double milesPerGallon = 33.8; // The average fuel efficiency of new U.S. cars in 2011  The compiler does not process comments  It ignores everything from a // delimiter to the end of the line.
  • 21. Copyright © 2014 by John Wiley & Sons. All rights reserved. 21 Comments  For longer comment, enclose it between /* and */ delimiters. • The compiler ignores these delimiters and everything in between.  Example of longer comments /* In most countries, fuel efficiency is measured in liters per hundred kilometer. Perhaps that is more useful—it tells you how much gas you need to purchase to drive a given distance. Here is the conversion formula. */ double fuelEfficiency = 235.214583 / milesPerGallon;
  • 22. Copyright © 2014 by John Wiley & Sons. All rights reserved. 22 Assignment  Use the assignment operator (=) to change the value of a variable.  You have the following variable declaration int width = 10;  To change the value of the variable, assign the new value width = 20; Figure 2 Assigning a New Value to a Variable
  • 23. Copyright © 2014 by John Wiley & Sons. All rights reserved. 23 Assignment  It is an error to use a variable that has never had a value assigned to it: int height; int width = height; // ERROR - uninitialized variable height • The compiler will complain about an "uninitialized variable" Figure 3 An Uninitialized Variable  Remedy: assign a value to the variable before you use it. int height; int width = height; // OK  All variables must be initialized before you access them.
  • 24. Copyright © 2014 by John Wiley & Sons. All rights reserved. 24 Assignment  The right-hand side of the = symbol can be a mathematical expression: width = height + 10; • This means 1. compute the value of height + 10 2. store that value in the variable width width = width + 10  The assignment operator = does not denote mathematical equality.
  • 25. Copyright © 2014 by John Wiley & Sons. All rights reserved. 25 Assignment Figure 4 Executing the Statement width = width + 10
  • 26. Copyright © 2014 by John Wiley & Sons. All rights reserved. 26 Syntax 2.2 Assignment
  • 27. Copyright © 2014 by John Wiley & Sons. All rights reserved. 27 Self Check 2.3 What is wrong with the following variable declaration? int miles per gallon = 39.4 Answer: There are three errors: 1. You cannot have spaces in variable names. 2. The variable type should be double because it holds a fractional value. 3. There is a semicolon missing at the end of the statement.
  • 28. Copyright © 2014 by John Wiley & Sons. All rights reserved. 28 Self Check 2.4 Declare and initialize two variables, unitPrice and quantity, to contain the unit price of a single item and the number of items purchased. Use reasonable initial values. Answer: double unitPrice = 1.95; int quantity = 2;
  • 29. Copyright © 2014 by John Wiley & Sons. All rights reserved. 29 Self Check 2.5 Use the variables declared in Self Check 4 to display the total purchase price. Answer: System.out.print("Total price: "); System.out.println(unitPrice * quantity);
  • 30. Copyright © 2014 by John Wiley & Sons. All rights reserved. 30 Self Check 2.6 What are the types of the values 0 and "0"?
  • 31. Copyright © 2014 by John Wiley & Sons. All rights reserved. 31 Self Check 2.6 What are the types of the values 0 and "0"? Answer: int and String
  • 32. Copyright © 2014 by John Wiley & Sons. All rights reserved. 32 Self Check 2.7 Which number type would you use for storing the area of a circle? Answer: double
  • 33. Copyright © 2014 by John Wiley & Sons. All rights reserved. 33 Self Check 2.8 Which of the following are legal identifiers? Greeting1 g void 101dalmatians Hello, World <greeting> Answer: Only the first two are legal identifiers.
  • 34. Copyright © 2014 by John Wiley & Sons. All rights reserved. 34 Self Check 2.9 Declare a variable to hold your name. Use camel case in the variable name.
  • 35. Copyright © 2014 by John Wiley & Sons. All rights reserved. 35 Self Check 2.9 Declare a variable to hold your name. Use camel case in the variable name. Answer: String myName = "John Q. Public";
  • 36. Copyright © 2014 by John Wiley & Sons. All rights reserved. 36 Self Check 2.10 Is 12 = 12 a valid expression in the Java language? Answer: No, the left-hand side of the = operator must be a variable.
  • 37. Copyright © 2014 by John Wiley & Sons. All rights reserved. 37 Self Check 2.11 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 declares a new variable
  • 38. Copyright © 2014 by John Wiley & Sons. All rights reserved. 38 Self Check 2.12 How would you explain assignment using the parking space analogy? Answer: Assignment would occur when one car is replaced by another in the parking space.
  • 39. Copyright © 2014 by John Wiley & Sons. All rights reserved. 39 Calling Methods  You use an object by calling its methods.  All objects of a given class share a common set of methods.  The PrintStream class provides methods for its objects such as: • println • print
  • 40. Copyright © 2014 by John Wiley & Sons. All rights reserved. 40 Calling Methods  The String class provides methods that you can apply to all String objects.  Example: length String greeting = “Hello, World!”; int numberOfCharacters = greeting.length();  Example: toUpperCase String river = “Mississippi”; String bigRiver = river.toUpperCase();
  • 41. Copyright © 2014 by John Wiley & Sons. All rights reserved. 41 The Public Interface of a Class The controls of a car form its public interface. The private implementation is under the hood.  The String class declares many other methods besides the length and toUpperCase methods.  Collectively, the methods form the public interface of the class.  The public interface of a class specifies what you can do with its objects.  The hidden implementation describes how these actions are carried out.
  • 42. Copyright © 2014 by John Wiley & Sons. All rights reserved. 42 A Representation of Two String Objects  Each String object stores its own data.  Both objects support the same set of methods. • Those methods form the public interface • Public interface is specified by the String class.
  • 43. Copyright © 2014 by John Wiley & Sons. All rights reserved. 43 Method Arguments  Most methods require values that give details about the work that the method needs to do.  You must supply the string that should be printed when you call the println method.  The technical term for method inputs: arguments.  The string greeting is an argument of this method call: System.out.println(greeting); Figure 6 Passing an Argument to the println Method
  • 44. Copyright © 2014 by John Wiley & Sons. All rights reserved. 44 Method Arguments At this tailor shop, the customer's measurements and the fabric are the arguments of the sew method. The return value is the finished garment.
  • 45. Copyright © 2014 by John Wiley & Sons. All rights reserved. 45 Method Arguments  Some methods require multiple arguments.  Other methods don't require any arguments at all. • Example: the length method of the String class • All the information that the length method requires to do its job is stored in the object Figure 7 Invoking the length Method on a String Object
  • 46. Copyright © 2014 by John Wiley & Sons. All rights reserved. 46 Return Values  Some methods carry out an action for you. • Example: println method  Other methods compute and return a value. • Example: the String length method • returns a value: the number of characters in the string. • You can store the return value in a variable: int numberOfCharacters = greeting.length()  The return value of a method is a result that the method has computed.
  • 47. Copyright © 2014 by John Wiley & Sons. All rights reserved. 47 Return Values  You can also use the return value of one method as an argument of another method: System.out.println(greeting.length()); • The method call greeting.length() returns a value - the integer 13. • The return value becomes an argument of the println method. Figure 8 Passing the Result of a Method Call to Another Method
  • 48. Copyright © 2014 by John Wiley & Sons. All rights reserved. 48 Return Values – replace Method Example: assume String river = "Mississippi";  Then the statement river = river.replace("issipp", "our"); • Constructs a new String by • Replacing all occurrences of "issipp" in "Mississippi" with "our" • Returns the constructed String object "Missouri" • And saves the return value in the same variable  You could pass the return value to another method: System.out.println(river.replace("issipp", "our"));
  • 49. Copyright © 2014 by John Wiley & Sons. All rights reserved. 49 Return Values – replace Method - continued  The method call river.replace("issipp", "our")) • Is invoked on a String object: "Mississippi" • Has two arguments: the strings "issipp" and "our" • Returns a value: the string "Missouri" Figure 9 Calling the replace Method
  • 50. Copyright © 2014 by John Wiley & Sons. All rights reserved. 50 Method Arguments and Return Values
  • 51. Copyright © 2014 by John Wiley & Sons. All rights reserved. 51 Method Declaration  To declare a method in a class, specify • The types of the arguments • The return value  Example: public int length() • There are no arguments • The return value has the type int
  • 52. Copyright © 2014 by John Wiley & Sons. All rights reserved. 52 Method Declaration - continued  Example: public String replace(String target, String replacement) • Has two arguments, target and replacement • Both arguments have type String • The returned value is another string  Example: public void println(String output) • Has an argument of type String • No return value • Uses the keyword void
  • 53. Copyright © 2014 by John Wiley & Sons. All rights reserved. 53 Method Declaration - continued  A class can declare two methods with the same name and different argument types.  The PrintStream class declares another println method public void println(int output) • Used to print an integer value  The println name is overloaded because it refers to more than one method.
  • 54. Copyright © 2014 by John Wiley & Sons. All rights reserved. 54 Self Check 2.13 How can you compute the length of the string "Mississippi"? Answer: river.length() or "Mississippi".length()
  • 55. Copyright © 2014 by John Wiley & Sons. All rights reserved. 55 Self Check 2.14 How can you print out the uppercase version of "Hello, World!"? Answer: System.out.println(greeting.toUpperCase()); or System.out.println("Hello, World!".toUpperCase());
  • 56. Copyright © 2014 by John Wiley & Sons. All rights reserved. 56 Self Check 2.15 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.
  • 57. Copyright © 2014 by John Wiley & Sons. All rights reserved. 57 Self Check 2.16 What are the arguments in the method call river.replace("p", "s")? Answer: The arguments are the strings "p" and "s".
  • 58. Copyright © 2014 by John Wiley & Sons. All rights reserved. 58 Self Check 2.17 What is the result of the call river.replace("p", "s”), where river is "Mississippi"? Answer: "Missississi"
  • 59. Copyright © 2014 by John Wiley & Sons. All rights reserved. 59 Self Check 2.18 What is the result of the call greeting.replace("World", "Dave").length(), where greeting is "Hello, World!"? Answer: 12
  • 60. Copyright © 2014 by John Wiley & Sons. All rights reserved. 60 Self Check 2.19 How is the toUpperCase method declared in the String class? Answer: As public String toUpperCase(), with no argument and return type String.
  • 61. Copyright © 2014 by John Wiley & Sons. All rights reserved. 61 Constructing Objects Objects of the Rectangle class describe rectangular shapes.
  • 62. Copyright © 2014 by John Wiley & Sons. All rights reserved. 62
  • 63. Copyright © 2014 by John Wiley & Sons. All rights reserved. 63 Constructing Objects  The Rectangle object is not a rectangular shape.  It is an object that contains a set of numbers. • The numbers describe the rectangle  Each rectangle is described by: • The x- and y-coordinates of its top-left corner • Its width • And its height.
  • 64. Copyright © 2014 by John Wiley & Sons. All rights reserved. 64 Constructing Objects  In the computer, a Rectangle object is a block of memory that holds four numbers.
  • 65. Copyright © 2014 by John Wiley & Sons. All rights reserved. 65 Constructing Objects  Use the new operator, followed by a class name and arguments, to construct new 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  The process of creating a new object is called construction.  The four values 5, 10, 20, and 30 are called the construction arguments.
  • 66. Copyright © 2014 by John Wiley & Sons. All rights reserved. 66 Constructing Objects  Usually the output of the new operator is stored in a variable: Rectangle box = new Rectangle(5, 10, 20, 30);  Additional constructor: new Rectangle()
  • 67. Copyright © 2014 by John Wiley & Sons. All rights reserved. 67 Syntax 2.3 Object Construction
  • 68. Copyright © 2014 by John Wiley & Sons. All rights reserved. 68 Self Check 2.20 How do you construct a square with center (100, 100) and side length 20? Answer: new Rectangle(90, 90, 20, 20)
  • 69. Copyright © 2014 by John Wiley & Sons. All rights reserved. 69 Self Check 2.21 Initialize the variables box and box2 with two rectangles that touch each other. Answer: Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = new Rectangle(25, 10, 20, 30);
  • 70. Copyright © 2014 by John Wiley & Sons. All rights reserved. 70 Self Check 2.22 The getWidth method returns the width of a Rectangle object. What does the following statement print? System.out.println(new Rectangle().getWidth()); Answer: 0
  • 71. Copyright © 2014 by John Wiley & Sons. All rights reserved. 71 Self Check 2.23 The PrintStream class has a constructor whose argument is the name of a file. How do you construct a PrintStream object with the construction argument "output.txt"? Answer: new PrintStream("output.txt”);
  • 72. Copyright © 2014 by John Wiley & Sons. All rights reserved. 72 Self Check 2.24 Write a statement to save the object that you constructed in Self Check 23 in a variable. Answer: PrintStream out = new PrintStream("output.txt");
  • 73. Copyright © 2014 by John Wiley & Sons. All rights reserved. 73 Accessor and Mutator Methods  Accessor method: does not change the internal data of the object on which it is invoked. • Returns information about the object • Example: length method of the String class • Example: double width = box.getWidth();  Mutator method: changes the data of the object box.translate(15, 25); • The top-left corner is now at (20, 35).
  • 74. Copyright © 2014 by John Wiley & Sons. All rights reserved. 74 Self Check 2.25 What does this sequence of statements print? Rectangle box = new Rectangle(5, 10, 20, 30); System.out.println("Before: " + box.getX()); box.translate(25, 40); System.out.println("After: " + box.getX()); Answer: Before: 5 After: 30
  • 75. Copyright © 2014 by John Wiley & Sons. All rights reserved. 75 Self Check 2.26 What does this sequence of statements print? Rectangle box = new Rectangle(5, 10, 20, 30); System.out.println("Before: " + box.getWidth()); box.translate(25, 40); System.out.println("After: " + box.getWidth()); Answer: Before: 20 After: 20 Moving the rectangle does not affect its width or height. You can change the width and height with the setSize method.
  • 76. Copyright © 2014 by John Wiley & Sons. All rights reserved. 76 Self Check 2.27 What does this sequence of statements print? String greeting = "Hello”; System.out.println(greeting.toUpperCase()); System.out.println(greeting); Answer: HELLO hello Note that calling toUpperCase doesn't modify the string.
  • 77. Copyright © 2014 by John Wiley & Sons. All rights reserved. 77 Self Check 2.28 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.
  • 78. Copyright © 2014 by John Wiley & Sons. All rights reserved. 78 Self Check 2.29 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), provided the method is called immediately after storing the new rectangle into box.
  • 79. Copyright © 2014 by John Wiley & Sons. All rights reserved. 79 The API Documentation  API: Application Programming Interface  API documentation: lists classes and methods of the Java library  Application programmer: A programmer who uses the Java classes to put together a computer program (or application)  Systems Programmer: A programmer who designs and implements library classes such as PrintStream and Rectangle  http://docs.oracle.com/javase/7/docs/api/index.html
  • 80. Copyright © 2014 by John Wiley & Sons. All rights reserved. 80 Browsing the API Documentation  Locate Rectangle link in the left pane  Click on the link • The right pane shows all the features of the Rectangle class Figure 13 The API Documentation of the Standard Java Library
  • 81. Copyright © 2014 by John Wiley & Sons. All rights reserved. 81 Browsing the API Documentation – Method Summary  The API documentation for each class has • A section that describes the purpose of the class • Summary tables for the constructors and methods • Clicking on a method's link leads to a detailed description of the method Figure 14 The Method Summary for the Rectangle Class
  • 82. Copyright © 2014 by John Wiley & Sons. All rights reserved. 82 Browsing the API Documentation  The detailed description of a method shows: • The action that the method carries out • The types and names of the parameter variables that receive the arguments when the method is called • The value that it returns (or the reserved word void if the method doesn't return any value).
  • 83. Copyright © 2014 by John Wiley & Sons. All rights reserved. 83 Packages  Java classes are grouped into packages.  The Rectangle class belongs to the package java.awt.  To use the Rectangle class you must import the package: import java.awt.Rectangle;  Put the line at the top of your program.  You don't need to import classes in the java.lang package such as String and System.
  • 84. Copyright © 2014 by John Wiley & Sons. All rights reserved. 84 Syntax 2.4 Importing a Class from a Package
  • 85. Copyright © 2014 by John Wiley & Sons. All rights reserved. 85 Self Check 2.30 Look at the API documentation of the String class. Which method would you use to obtain the string "hello, world!" from the string "Hello, World!"? Answer: toLowerCase
  • 86. Copyright © 2014 by John Wiley & Sons. All rights reserved. 86 Self Check 2.31 In the API documentation of the String class, look at the description of the trim method. What is the result of applying trim to the string " Hello, Space ! "? (Note the spaces in the string.) Answer: "Hello, Space !" – only the leading and trailing spaces are trimmed.
  • 87. Copyright © 2014 by John Wiley & Sons. All rights reserved. 87 Self Check 2.32 Look into the API documentation of the Rectangle class. What is the difference between the methods void translate(int x, int y) and void setLocation(int x, int y)? Answer: The arguments of the translate method tell how far to move the rectangle in the x- and y-directions. The arguments of the setLocation method indicate the new x- and y-values for the top-left corner. For example, box.translate(1, 1) moves the box one pixel down and to the right. box.setLocation( 1, 1) moves box to the top-left corner of the screen.
  • 88. Copyright © 2014 by John Wiley & Sons. All rights reserved. 88 Self Check 2.33 The Random class is declared in the java.util package. What do you need to do in order to use that class in your program? Answer: Add the statement import java.util.Random; at the top of your program.
  • 89. Copyright © 2014 by John Wiley & Sons. All rights reserved. 89 Self Check 2.34 In which package is the BigInteger class located? Look it up in the API documentation. Answer: In the java.math package
  • 90. Copyright © 2014 by John Wiley & Sons. All rights reserved. 90 Implementing a Test Program  A test program verifies that methods behave as expected.  Steps in writing a tester class 1. Provide a tester class. 2. Supply a main method. 3. Inside the main method, construct one or more objects. 4. Apply methods to the objects. 5. Display the results of the method calls. 6. Display the values that you expect to get.
  • 91. Copyright © 2014 by John Wiley & Sons. All rights reserved. 91 Implementing a Test Program  Code to test the behavior of the translate method Rectangle box = new Rectangle(5, 10, 20, 30); // Move the rectangle box.translate(15, 25); // Print information about the moved rectangle System.out.print("x: "); System.out.println(box.getX()); System.out.println("Expected: 20");  Place the code inside the main method of the MoveTester class.  Determining the expected result in advance is an important part of testing.
  • 92. Copyright © 2014 by John Wiley & Sons. All rights reserved. 92 section_7/MoveTester.java 1 import java.awt.Rectangle; 2 3 public class MoveTester 4 { 5 public static void main(String[] args) 6 { 7 Rectangle box = new Rectangle(5, 10, 20, 30); 8 9 // Move the rectangle 10 box.translate(15, 25); 11 12 // Print information about the moved rectangle 13 System.out.print("x: "); 14 System.out.println(box.getX()); 15 System.out.println("Expected: 20"); 16 17 System.out.print("y: "); 18 System.out.println(box.getY()); 19 System.out.println("Expected: 35"); 20 } 21 } Program Run: x: 20 Expected: 20 y: 35 Expected: 35
  • 93. Copyright © 2014 by John Wiley & Sons. All rights reserved. 93 Self Check 2.35 Suppose we had called box.translate(25, 15) instead of box.translate(15, 25). What are the expected outputs? Answer: x: 30, y: 25
  • 94. Copyright © 2014 by John Wiley & Sons. All rights reserved. 94 Self Check 2.36 Why doesn't the MoveTester program print the width and height of the rectangle? Answer: Because the translate method doesn't modify the shape of the rectangle.
  • 95. Copyright © 2014 by John Wiley & Sons. All rights reserved. 95 Object References  An object variable is a variable whose type is a class • Does not actually hold an object. • Holds the memory location of an object Figure 15 An Object Variable Containing an Object Reference
  • 96. Copyright © 2014 by John Wiley & Sons. All rights reserved. 96 Object References  Object reference: describes the location of an object  After this statement: Rectangle box = new Rectangle(5, 10, 20, 30); • Variable box refers to the Rectangle object returned by the new operator • The box variable does not contain the object. It refers to the object.
  • 97. Copyright © 2014 by John Wiley & Sons. All rights reserved. 97 Object References  Multiple object variables can refer to the same object: Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = box; Figure 16 Two Object Variables Referring to the Same Object
  • 98. Copyright © 2014 by John Wiley & Sons. All rights reserved. 98 Numbers  Numbers are not objects.  Number variables actually store numbers. Figure 17 A Number Variable Stores a Number
  • 99. Copyright © 2014 by John Wiley & Sons. All rights reserved. 99 Copying Numbers  When you copy a number • the original and the copy of the number are independent values. int luckyNumber = 13; int luckyNumber2 = luckyNumber; luckyNumber2 = 12; Figure 18 Copying Numbers
  • 100. Copyright © 2014 by John Wiley & Sons. All rights reserved. 100 Copying Object References  When you copy an object reference • both the original and the copy are references to the same object Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = box; box2.translate(15, 25); Figure 19 Copying Object References
  • 101. Copyright © 2014 by John Wiley & Sons. All rights reserved. 101 Self Check 2.37 What is the effect of the assignment greeting2 = greeting? Answer: Now greeting and greeting2 both refer to the same String object.
  • 102. Copyright © 2014 by John Wiley & Sons. All rights reserved. 102 Self Check 2.38 After calling greeting2.toUpperCase(), what are the contents of greeting and greeting2? Answer: Both variables still refer to the same string, and the string has not been modified. Recall that the toUpperCase method constructs a new string that contains uppercase characters, leaving the original string unchanged.
  • 103. Copyright © 2014 by John Wiley & Sons. All rights reserved. 103 Mainframe Computer Mainframe Computer
  • 104. Copyright © 2014 by John Wiley & Sons. All rights reserved. 104 Graphical Applications: Frame Windows A graphical application shows information inside a frame.
  • 105. Copyright © 2014 by John Wiley & Sons. All rights reserved. 105 Frame Windows  To show a frame: 1. Construct an object of the JFrame class: JFrame frame = new JFrame(); 2. Set the size of the frame: frame.setSize(300, 400); 3. If you'd like, set the title of the frame: frame.setTitle("An empty Frame"); 4. Set the "default close operation”: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 5. Make the frame visible: frame.setVisible(true);
  • 106. Copyright © 2014 by John Wiley & Sons. All rights reserved. 106 section_9_1/EmptyFrameViewer.java 1 import javax.swing.JFrame; 2 3 public class EmptyFrameViewer 4 { 5 public static void main(String[] args) 6 { 7 JFrame frame = new JFrame(); 8 frame.setSize(300, 400); 9 frame.setTitle("An empty frame"); 10 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11 frame.setVisible(true); 12 } 13 } Figure 20 A Frame Window
  • 107. Copyright © 2014 by John Wiley & Sons. All rights reserved. 107 Drawing on a Component  In order to display a drawing in a frame, define a class that extends the JComponent class.  Place drawing instructions inside the paintComponent method. • That method is called whenever the component needs to be repainted: public class RectangleComponent extends Jcomponent { public void paintComponent(Graphics g) { Drawing instructions go here } }
  • 108. Copyright © 2014 by John Wiley & Sons. All rights reserved. 108 Classes Graphics and Graphics2D  Graphics class stores the graphics state (such as current color).  Graphics2D class has methods to draw shape objects.  Use a cast to recover the Graphics2D object from the Graphics parameter: public class RectangleComponent extends Jcomponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; . . . } }
  • 109. Copyright © 2014 by John Wiley & Sons. All rights reserved. 109 Classes Graphics and Graphics2D  The draw method of the Graphics2D class draws shapes, such as rectangles, ellipses, line segments, polygons, and arcs: public class RectangleComponent extends Jcomponent { public void paintComponent(Graphics g) { . . . Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); . . . } }
  • 110. Copyright © 2014 by John Wiley & Sons. All rights reserved. 110 Coordinate System of a Component  The origin (0, 0) is at the upper-left corner of the component.  The y-coordinate grows downward.
  • 111. Copyright © 2014 by John Wiley & Sons. All rights reserved. 111 Drawing Rectangles We want to create an application to display two rectangles. Figure 21 Drawing Rectangles
  • 112. Copyright © 2014 by John Wiley & Sons. All rights reserved. 112 section_9_2/RectangleComponent.java 1 import java.awt.Graphics; 2 import java.awt.Graphics2D; 3 import java.awt.Rectangle; 4 import javax.swing.JComponent; 5 6 /* 7 A component that draws two rectangles. 8 */ 9 public class RectangleComponent extends JComponent 10 { 11 public void paintComponent(Graphics g) 12 { 13 // Recover Graphics2D 14 Graphics2D g2 = (Graphics2D) g; 15 16 // Construct a rectangle and draw it 17 Rectangle box = new Rectangle(5, 10, 20, 30); 18 g2.draw(box); 19 20 // Move rectangle 15 units to the right and 25 units down 21 box.translate(15, 25); 22 23 // Draw moved rectangle 24 g2.draw(box); 25 } 26 }
  • 113. Copyright © 2014 by John Wiley & Sons. All rights reserved. 113 Displaying a Component in a Frame  In a graphical application you need: • A frame to show the application • A component for the drawing.  The steps for combining the two: 1. Construct a frame object and configure it. 2. Construct an object of your component class: RectangleComponent component = new RectangleComponent(); 3. Add the component to the frame: frame.add(component); 4. Make the frame visible.
  • 114. Copyright © 2014 by John Wiley & Sons. All rights reserved. 114 section_9_3/RectangleViewer.java 1 import javax.swing.JFrame; 2 3 public class RectangleViewer 4 { 5 public static void main(String[] args) 6 { 7 JFrame frame = new JFrame(); 8 9 frame.setSize(300, 400); 10 frame.setTitle("Two rectangles"); 11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 12 13 RectangleComponent component = new RectangleComponent(); 14 frame.add(component); 15 16 frame.setVisible(true); 17 } 18 }
  • 115. Copyright © 2014 by John Wiley & Sons. All rights reserved. 115 Self Check 2.39 How do you display a square frame with a title bar that reads "Hello, World!"? Answer: Modify the EmptyFrameViewer program as follows: frame.setSize(300, 300); frame.setTitle("Hello, World!");
  • 116. Copyright © 2014 by John Wiley & Sons. All rights reserved. 116 Self Check 2.40 How can a program display two frames at once? Answer: Construct two JFrame objects, set each of their sizes, and call setVisible(true) on each of them.
  • 117. Copyright © 2014 by John Wiley & Sons. All rights reserved. 117 Self Check 2.41 How do you modify the program to draw two squares? Answer: Rectangle box = new Rectangle(5, 10, 20, 20);
  • 118. Copyright © 2014 by John Wiley & Sons. All rights reserved. 118 Self Check 2.42 How do you modify the program to draw one rectangle and one square? Answer: Replace the call to box.translate(15, 25) with box = new Rectangle(20, 35, 20, 20);
  • 119. Copyright © 2014 by John Wiley & Sons. All rights reserved. 119 Self Check 2.43 What happens if you call g.draw(box) instead of g2.draw(box)? Answer: The compiler complains that g doesn't have a draw method.
  • 120. Copyright © 2014 by John Wiley & Sons. All rights reserved. 120 Ellipses  To construct an ellipse, you specify its bounding box. Figure 22 An Ellipse and Its Bounding Box  To construct an ellipse: Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, width, height);
  • 121. Copyright © 2014 by John Wiley & Sons. All rights reserved. 121 Ellipses  Ellipse2D.Double is an inner class — doesn't matter to us except for the import statement: import java.awt.geom.Ellipse2D; // No .Double  To draw the shape: g2.draw(ellipse);
  • 122. Copyright © 2014 by John Wiley & Sons. All rights reserved. 122 Circles  To draw a circle, set the width and height to the same values: Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter); g2.draw(circle);  (x, y) is the top-left corner of the bounding box, not the center of the circle.
  • 123. Copyright © 2014 by John Wiley & Sons. All rights reserved. 123 Lines  To draw a line, specify its end points: Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2); g2.draw(segment);  Or Point2D.Double from = new Point2D.Double(x1, y1); Point2D.Double to = new Point2D.Double(x2, y2); Line2D.Double segment = new Line2D.Double(from, to); g2.draw(segment);
  • 124. Copyright © 2014 by John Wiley & Sons. All rights reserved. 124 Drawing Text  To draw text, use the drawString method • Specify the string and the x- and y-coordinates of the basepoint of the first character g2.drawString("Message", 50, 100); Figure 23 Basepoint and Baseline
  • 125. Copyright © 2014 by John Wiley & Sons. All rights reserved. 125 Colors  To draw in color, you need to supply a Color object.  Specify the amount of red, green, blue as values between 0 and 255: Color magenta = new Color(255, 0, 255);  The Color class declares a variety of colors: Color.BLUE, Color.RED, Color.PINK etc.  To draw a shape in a different color • First set color in graphics context: g2.setColor(Color.Red); g2.draw(circle); // Draws the shape in red
  • 126. Copyright © 2014 by John Wiley & Sons. All rights reserved. 126 Colors  To color the inside of the shape, use the fill method: g2.fill(circle); // Fills with current color  When you set a new color in the graphics context, it is used for subsequent drawing operations.
  • 127. Copyright © 2014 by John Wiley & Sons. All rights reserved. 127 Predefined Colors
  • 128. Copyright © 2014 by John Wiley & Sons. All rights reserved. 128 Alien Face The code is on following slides: Figure 24 An Alien Face
  • 129. Copyright © 2014 by John Wiley & Sons. All rights reserved. 129 section_10/FaceComponent.java 1 import java.awt.Color; 2 import java.awt.Graphics; 3 import java.awt.Graphics2D; 4 import java.awt.Rectangle; 5 import java.awt.geom.Ellipse2D; 6 import java.awt.geom.Line2D; 7 import javax.swing.JComponent; 8 9 /* 10 A component that draws an alien face 11 */ 12 public class FaceComponent extends JComponent 13 { 14 public void paintComponent(Graphics g) 15 { 16 // Recover Graphics2D 17 Graphics2D g2 = (Graphics2D) g; 18 19 // Draw the head 20 Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150); 21 g2.draw(head); 22 Continued
  • 130. Copyright © 2014 by John Wiley & Sons. All rights reserved. 130 section_10/FaceComponent.java 23 // Draw the eyes 24 g2.setColor(Color.GREEN); 25 Rectangle eye = new Rectangle(25, 70, 15, 15); 26 g2.fill(eye); 27 eye.translate(50, 0); 28 g2.fill(eye); 29 30 // Draw the mouth 31 Line2D.Double mouth = new Line2D.Double(30, 110, 80, 110); 32 g2.setColor(Color.RED); 33 g2.draw(mouth); 34 35 // Draw the greeting 36 g2.setColor(Color.BLUE); 37 g2.drawString("Hello, World!", 5, 175); 38 } 39 }
  • 131. Copyright © 2014 by John Wiley & Sons. All rights reserved. 131 section_10/FaceViewer.java 1 import javax.swing.JFrame; 2 3 public class FaceViewer 4 { 5 public static void main(String[] args) 6 { 7 JFrame frame = new JFrame(); 8 frame.setSize(150, 250); 9 frame.setTitle("An Alien Face"); 10 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11 12 FaceComponent component = new FaceComponent(); 13 frame.add(component); 14 15 frame.setVisible(true); 16 } 17 }
  • 132. Copyright © 2014 by John Wiley & Sons. All rights reserved. 132 Self Check 2.44 Give instructions to draw a circle with center (100, 100) and radius 25. Answer: g2.draw(new Ellipse2D.Double(75, 75, 50, 50));
  • 133. Copyright © 2014 by John Wiley & Sons. All rights reserved. 133 Self Check 2.45 Give instructions to draw a letter "V" by drawing two line segments. Answer: Line2D.Double segment1 = new Line2D.Double(0, 0, 10, 30); g2.draw(segment1); Line2D.Double segment2 = new Line2D.Double(10, 30, 20, 0); g2.draw(segment2);
  • 134. Copyright © 2014 by John Wiley & Sons. All rights reserved. 134 Self Check 2.46 Give instructions to draw a string consisting of the letter "V". Answer: g2.drawString("V", 0, 30);
  • 135. Copyright © 2014 by John Wiley & Sons. All rights reserved. 135 Self Check 2.47 What are the RGB color values of Color.BLUE? Answer: 0, 0, and 255
  • 136. Copyright © 2014 by John Wiley & Sons. All rights reserved. 136 Self Check 2.48 How do you draw a yellow square on a red background? Answer: First fill a big red square, then fill a small yellow square inside: g2.setColor(Color.RED); g2.fill(new Rectangle(0, 0, 200, 200)); g2.setColor(Color.YELLOW); g2.fill(new Rectangle(50, 50, 100, 100));