Objects & Primitive DataObjects & Primitive Data
Clark Savage Turner, J.D., Ph.D.Clark Savage Turner, J.D., Ph.D.
[email protected]@csc.calpoly.edu
756-6133756-6133
Adapted for use with Kaufman and Wolz by Clark S. Turner and Adapted for use with Kaufman and Wolz by Clark S. Turner and
Some lecture slides have been adapted from those developedSome lecture slides have been adapted from those developed by John Lewis and William Loftus to accompany by John Lewis and William Loftus to accompany
Java Software Solutions: Java Software Solutions:
Foundations of Program Design, Second EditionFoundations of Program Design, Second Edition
and and
by Carol Scheftic and Mark Hutchenreuther for CSC-101 at Cal Poly, SLO. by Carol Scheftic and Mark Hutchenreuther for CSC-101 at Cal Poly, SLO.
CSC-101
AbstractionAbstraction
An An abstractionabstraction hides (or ignores) the right details hides (or ignores) the right details at the right time.at the right time.
An object is abstract in that we don't really have to think An object is abstract in that we don't really have to think about its internal details in order to use it.about its internal details in order to use it.
We don't have to know how the We don't have to know how the aa method works method works in order to invoke it.in order to invoke it.
A human being can only manage “seven (plus or minus 2)” A human being can only manage “seven (plus or minus 2)” pieces of information at one time.pieces of information at one time.
But if we group information into chunks (such as objects) But if we group information into chunks (such as objects) we can manage many complicated pieces at once.we can manage many complicated pieces at once.
Therefore, we can write complex software Therefore, we can write complex software by organizing it carefully into classes and objects.by organizing it carefully into classes and objects.
CSC-101
Introduction to ObjectsIntroduction to Objects
Initially, we can think of an Initially, we can think of an objectobject as a collection of services as a collection of services that we can tell it to perform for usthat we can tell it to perform for us
The services are defined by methods in a class that defines The services are defined by methods in a class that defines the objectthe object
In the Lincoln program, we invoked the In the Lincoln program, we invoked the printlnprintln method method of the of the System.outSystem.out object: object:
System.out.println ("Whatever you are, be a good one.");
a method a method of this objectof this object Information provided to the methodInformation provided to the method
(parameters)(parameters)
a class a class of objectsof objects
an object (variable)an object (variable)within this classwithin this class
CSC-101
The println and print MethodsThe println and print Methods
The The System.outSystem.out object provides another service besides object provides another service besides printlnprintln
The The printprint method is similar to the method is similar to the printlnprintln method, method, except that it does not advance to the next lineexcept that it does not advance to the next line
Therefore anything printed after a Therefore anything printed after a printprint statement will statement will appear on the same lineappear on the same line
CSC-101
The String ClassThe String Class
Every character string is an object in Java, defined by the Every character string is an object in Java, defined by the StringString class class
Every string literal, delimited by double quotation marks, Every string literal, delimited by double quotation marks, represents a represents a StringString object object
The The string concatenation operatorstring concatenation operator (+) is used to append one (+) is used to append one string to the end of anotherstring to the end of another
It can also be used to append a number to a stringIt can also be used to append a number to a string A string literal cannot be broken across lines in a programA string literal cannot be broken across lines in a program
Concatenate small strings, which are broken across lines, using + Concatenate small strings, which are broken across lines, using + oror Re-use the print() method to concatenate small strings in print.Re-use the print() method to concatenate small strings in print.
CSC-101
String ConcatenationString Concatenation
The plus operator (+) is also used for arithmetic additionThe plus operator (+) is also used for arithmetic addition The function that the + operator performs depends on the The function that the + operator performs depends on the
type of the information on which it operatestype of the information on which it operates If both operands are strings, or if one is a string and one is If both operands are strings, or if one is a string and one is
a number, it performs string concatenationa number, it performs string concatenation If both operands are numeric, it adds themIf both operands are numeric, it adds them The + operator is evaluated left to rightThe + operator is evaluated left to right Parentheses can be used to force the operation orderParentheses can be used to force the operation order
CSC-101
Escape SequencesEscape Sequences
What if we wanted to print a double quote character?What if we wanted to print a double quote character? The following line would confuse the compiler because it The following line would confuse the compiler because it
would interpret the second quote as the end of the stringwould interpret the second quote as the end of the string
System.out.println ("I said "Hello" to you.");
An An escape sequenceescape sequence is a series of characters that represents is a series of characters that represents a special charactera special character
An escape sequence begins with a backslash character (An escape sequence begins with a backslash character (\\), ), which indicates that the character(s) that follow should be which indicates that the character(s) that follow should be treated in a special waytreated in a special way
System.out.println ("I said \"Hello\" to you.");
CSC-101
Escape SequencesEscape Sequences
Some Java escape sequences:Some Java escape sequences:
Escape Sequence
\b\t\n\r\"\'\\
Meaning
backspacetab
newlinecarriage returndouble quotesingle quotebackslash
CSC-101
VariablesVariables
A A variablevariable is a name for a location in memory is a name for a location in memory A variable must be A variable must be declareddeclared, specifying the variable's name , specifying the variable's name
and the type of information that will be held in itand the type of information that will be held in it
int total;
int count, temp, result;
Multiple variables can be created in one declarationMultiple variables can be created in one declaration
data typedata type variable namevariable name
CSC-101
VariablesVariables
A variable can be given an initial value in the declarationA variable can be given an initial value in the declaration
When a variable is referenced in a program, its current When a variable is referenced in a program, its current value is usedvalue is used
int sum = 0;int base = 32, max = 149;
CSC-101
AssignmentAssignment
An An assignment statementassignment statement changes the value of a variable changes the value of a variable The assignment operator is the The assignment operator is the == sign sign
total = 55;
You can only assign a value to a variable that is You can only assign a value to a variable that is consistent with the variable's declared typeconsistent with the variable's declared type
The expression on the right is evaluated and The expression on the right is evaluated and the result is stored in the variable on the leftthe result is stored in the variable on the left
The value that was in The value that was in totaltotal is overwritten is overwritten
CSC-101
ConstantsConstants
A constant is an identifier that is similar to a variable A constant is an identifier that is similar to a variable except that it holds one value for its entire existenceexcept that it holds one value for its entire existence
The compiler will issue an error if you try to change a The compiler will issue an error if you try to change a constantconstant
In Java, we use the In Java, we use the finalfinal modifier to declare a constant modifier to declare a constant
final int MIN_HEIGHT = 69;
Constants:Constants: give names to otherwise unclear literal valuesgive names to otherwise unclear literal values facilitate changes to the codefacilitate changes to the code prevent inadvertent errorsprevent inadvertent errors
CSC-101
Creating ObjectsCreating Objects
A variable either holds a primitive type, or it holds a A variable either holds a primitive type, or it holds a referencereference to an object to an object
A class name can be used as a type to declare an A class name can be used as a type to declare an object reference variableobject reference variable
String greeting;
No object has been created with this declaration!No object has been created with this declaration!
An An object reference variableobject reference variable holds the holds the addressaddress of an object. of an object. The object itself must be created separately.The object itself must be created separately.
String greeting;greeting = new String(“Howdy!”);
InstantiationInstantiation creates an creates an objectobject that is an instance of a that is an instance of a particular class.particular class.
CSC-101
Creating ObjectsCreating Objects
Use the Use the newnew operator to create an object: operator to create an object:greeting = new String (”Howdy!");
This calls the This calls the StringString constructorconstructor, which is, which isa special method that sets up the objecta special method that sets up the object
Declaration and instantiation can be combined:Declaration and instantiation can be combined:String greeting = new String(“Howdy!”);
An object is an An object is an instanceinstance of a particular class. of a particular class. Can later change the value of a variable (but not its type):Can later change the value of a variable (but not its type):
String greeting = new String(“Howdy!”);. . . greeting = (“Fare thee well.”);
CSC-101
Creating ObjectsCreating Objects
Because strings are so common, we don't have to use the Because strings are so common, we don't have to use the newnew operator to create a operator to create a StringString object object
title = "Java Software Solutions";
This is special syntax that only works for stringsThis is special syntax that only works for strings
Once an object has been instantiated, we can use the Once an object has been instantiated, we can use the dot dot operatoroperator to invoke its methods to invoke its methods
title.length()
CSC-101
String MethodsString Methods
The The StringString class has several methods that are useful for class has several methods that are useful for manipulating strings.manipulating strings.
Many of the methods Many of the methods return a valuereturn a value, such as an integer or a , such as an integer or a new new StringString object. object.
See (and experiment with) the lists of See (and experiment with) the lists of StringString methods in methods in the textbookthe textbook
CSC-101
More on: the dot operator & parenthesesMore on: the dot operator & parentheses
Write some trial pieces of code to experiment with the Write some trial pieces of code to experiment with the dot dot operatoroperator. For example, examine things like:. For example, examine things like: testString.length();testString.length(); testString.toUpperCase();testString.toUpperCase(); testSting.charAt (testString.length()-1)testSting.charAt (testString.length()-1);;
Experiment some more to confirm that Experiment some more to confirm that white spacewhite space before the parentheses is used to improve readability:before the parentheses is used to improve readability: often omitted when no arguments are usedoften omitted when no arguments are used
testString.toLowerCase(); testString.toLowerCase();
usually included when passing parametersusually included when passing parameters testString.replace (i, I);testString.replace (i, I);
CSC-101
Primitive DataPrimitive Data
There are exactly eight primitive data types in JavaThere are exactly eight primitive data types in Java
Four of them represent integer numbers:Four of them represent integer numbers: bytebyte, , shortshort, , intint, , longlong
Two of them represent floating point numbers:Two of them represent floating point numbers: floatfloat, , doubledouble
One of them represents characters:One of them represents characters: charchar
And one of them represents boolean values:And one of them represents boolean values: booleanboolean
Everything else is represented using objects!Everything else is represented using objects!
CSC-101
Numeric Primitive DataNumeric Primitive Data
The difference between the various numeric primitive types The difference between the various numeric primitive types is their size, and therefore the values they can store:is their size, and therefore the values they can store:
Type
byteshortintlong
floatdouble
Storage
8 bits16 bits32 bits64 bits
32 bits64 bits
Min Value
-128-32,768-2,147,483,648< -9 x 1018
+/- 3.4 x 1038 with 7 significant digits+/- 1.7 x 10308 with 15 significant digits
Max Value
12732,7672,147,483,647> 9 x 1018
CSC-101
CharactersCharacters
AA char char variable stores a single character from the variable stores a single character from the Unicode Unicode character setcharacter set
A A character setcharacter set is an ordered list of characters, and each is an ordered list of characters, and each character corresponds to a unique numbercharacter corresponds to a unique number
The Unicode character set uses sixteen bits per character, The Unicode character set uses sixteen bits per character, allowing for 65,536 unique charactersallowing for 65,536 unique characters
It is an international character set, containing symbols and It is an international character set, containing symbols and characters from many world languagescharacters from many world languages
Character literals are delimited by single quotes:Character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' '\n’'a' 'X' '7' '$' ',' '\n’
Remember, though, that strings are objects, not primitive Remember, though, that strings are objects, not primitive data, and they are delimited by double quotes.data, and they are delimited by double quotes.
CSC-101
BooleanBoolean
AA boolean boolean value represents a true or false condition.value represents a true or false condition.
A boolean can also be used to represent any two states, such A boolean can also be used to represent any two states, such as a light bulb being on or off.as a light bulb being on or off.
The reserved wordsThe reserved words true true andand false false are the only valid are the only valid values for a boolean type.values for a boolean type.
boolean done = false;boolean done = false;
CSC-101
Arithmetic ExpressionsArithmetic Expressions
An An expressionexpression is a combination of operators and operands is a combination of operators and operands Arithmetic expressionsArithmetic expressions compute numeric results and make compute numeric results and make
use of the arithmetic operators:use of the arithmetic operators:
Addition +Subtraction -Multiplication *Division /Remainder %
CSC-101
If either or both operands to an arithmetic operator are If either or both operands to an arithmetic operator are floating point, the result is a floating point.floating point, the result is a floating point.
Division and RemainderDivision and Remainder
The remainder operator (%) returns the remainder The remainder operator (%) returns the remainder after dividing the first operand by the second, with the sign after dividing the first operand by the second, with the sign of the first operator (i.e., the numerator).of the first operator (i.e., the numerator).
14 / 3 equals? 4
8 / 12 equals? 0
14 % 3 equals? 2
-8 % 12 equals? -8
12 / 8.0 equals? 1.5
If both operands to the division operator (If both operands to the division operator (//) are integers, ) are integers, the result is an integer (the fractional part is discarded).the result is an integer (the fractional part is discarded).
CSC-101
Operator PrecedenceOperator Precedence
Operators can be combined into complex expressionsOperators can be combined into complex expressions
result = total + count / max - offset;
Operators have a well-defined precedence which Operators have a well-defined precedence which determines the order in which they are evaluated.determines the order in which they are evaluated. Unary operations (+ / -) are done first.Unary operations (+ / -) are done first. Multiplication, division, and remainder are evaluated Multiplication, division, and remainder are evaluated
prior to addition, subtraction, and string concatenation.prior to addition, subtraction, and string concatenation. Arithmetic operators with the same precedence Arithmetic operators with the same precedence
are evaluated from left to right.are evaluated from left to right. Assignment (=) is performed last.Assignment (=) is performed last.
Parentheses can be used to force the evaluation order.Parentheses can be used to force the evaluation order.
CSC-101
Assignment Revisited Assignment Revisited (1)(1)
The assignment operator has a lower precedence The assignment operator has a lower precedence than the arithmetic operators.than the arithmetic operators.
First the expression on the right handFirst the expression on the right handside of the = operator is evaluatedside of the = operator is evaluated
Then the result is stored in theThen the result is stored in thevariable on the left hand sidevariable on the left hand side
answer = sum / 4 + MAX * lowest;
14 3 2
CSC-101
Assignment Revisited Assignment Revisited (2)(2)
The right and left hand sides of an assignment statement The right and left hand sides of an assignment statement can contain the same variablecan contain the same variable
First, one is added to theFirst, one is added to theoriginal value of original value of countcount
Then the result is stored back into Then the result is stored back into countcount(overwriting the original value)(overwriting the original value)
count = count + 1;
CSC-101
Data ConversionsData Conversions
Sometimes it is convenient to convert data Sometimes it is convenient to convert data from one type to another.from one type to another. Example: treat an integer as floating point during a computation.Example: treat an integer as floating point during a computation.
Conversions must be handled carefully to avoid losing Conversions must be handled carefully to avoid losing information!information! Widening conversionsWidening conversions are safest: are safest:
they tend to go from a small data type to a larger one they tend to go from a small data type to a larger one (such as a (such as a shortshort to an to an intint).).
Narrowing conversionsNarrowing conversions can lose information: can lose information: if they go from a large data type to a smaller one if they go from a large data type to a smaller one (such as an (such as an intint to a to a shortshort), or ), or from a number to a char from a number to a char (which incorporates the sign bit and loses numeric hierarchy).(which incorporates the sign bit and loses numeric hierarchy).
CSC-101
Data ConversionsData Conversions
In Java, data conversions can occur in three ways:In Java, data conversions can occur in three ways: assignment conversionassignment conversion arithmetic promotionarithmetic promotion castingcasting
Assignment conversionAssignment conversion occurs when a value of one type is occurs when a value of one type is assigned to a variable of another.assigned to a variable of another. Only widening conversions can happen via assignment.Only widening conversions can happen via assignment.
Arithmetic promotionArithmetic promotion happens automatically happens automatically when operators in expressions convert their operands.when operators in expressions convert their operands.
CastingCasting is the most powerful, and dangerous, technique for is the most powerful, and dangerous, technique for conversion.conversion.
CSC-101
More on CastingMore on Casting
A powerful, and dangerous, technique for conversion:A powerful, and dangerous, technique for conversion: Both widening and narrowing conversions can be Both widening and narrowing conversions can be
accomplished by explicitly casting a valueaccomplished by explicitly casting a value
To cast:To cast: The type is put in parentheses The type is put in parentheses
in front of the value being convertedin front of the value being converted Example:Example:
If both If both totaltotal and and countcount are integers, are integers, resultresult will be integer: will be integer:result = total / count;
If we want a floating point If we want a floating point resultresult from division, we cast from division, we cast totaltotal::
result = (float) total / count;
CSC-101
Class LibrariesClass Libraries
A A class libraryclass library is a collection of related classes that can be is a collection of related classes that can be used in developing programsused in developing programs Java … API: Application Programmer InterfaceJava … API: Application Programmer Interface
The The Java standard class libraryJava standard class library It is not part of the basic Java language, per se.It is not part of the basic Java language, per se. It is part of any Java development environment:It is part of any Java development environment:
e.g., e.g., java.lang is automatically available to all Java programs. is automatically available to all Java programs. We have already seen and used some members of this:We have already seen and used some members of this:
the the System class class the the String class class
Other class libraries can be obtained through third party Other class libraries can be obtained through third party vendors vendors oror you can create them yourself ! you can create them yourself !
CSC-101
PackagesPackages
The classes of the Java standard class library are organized The classes of the Java standard class library are organized into packagesinto packages
Some of the packages in the standard class library are:Some of the packages in the standard class library are:
Package
java.langjava.appletjava.awtjavax.swingjava.netjava.util
Purpose
General supportCreating applets for the webGraphics and graphical user interfacesAdditional graphics capabilities and componentsNetwork communicationUtilities
CSC-101
The import DeclarationThe import Declaration
When you want to use a class from a package, you could When you want to use a class from a package, you could use its use its fully qualified namefully qualified name every time: every time:
java.util.Random
java.util.Random
java.util.Random
Or you can Or you can importimport the class once, and thereafter just use the the class once, and thereafter just use the class name:class name:
import java.util.Random;
… Random();
To import all classes in a particular package, you can use To import all classes in a particular package, you can use the wildcard character ( the wildcard character ( * ) )
import java.util.*;
… Random();
CSC-101
The import DeclarationThe import Declaration
All classes of the All classes of the java.langjava.lang package are package are automatically imported into all programsautomatically imported into all programs Thus, we didn't have to explicitly import the Thus, we didn't have to explicitly import the SystemSystem or or StringString
classes in earlier programs.classes in earlier programs. A A RandomRandom class is part of the class is part of the java.utiljava.util package package
It provides methods that generate pseudo-random numbers.It provides methods that generate pseudo-random numbers. We often have to We often have to scalescale and and shiftshift a number into a number into
an appropriate range for a particular purpose.an appropriate range for a particular purpose.
A A randomrandom method is part of the method is part of the MathMath class in class in java.langjava.lang It can also be used to generate pseudo-random numbers.It can also be used to generate pseudo-random numbers.
It will also require us to It will also require us to scalescale and and shiftshift a number into a number into an appropriate range for our particular purpose.an appropriate range for our particular purpose.
But, we won’t have to explicitly import this either.But, we won’t have to explicitly import this either.
CSC-101
Class MethodsClass Methods
Some methods can be invoked through the class name, Some methods can be invoked through the class name, instead of through an object of the classinstead of through an object of the class
These methods are called These methods are called class methodsclass methods or or static methodsstatic methods
The The MathMath class contains many static methods, providing class contains many static methods, providing various mathematical functions, such as absolute value, various mathematical functions, such as absolute value, trigonometry functions, square root, etc.trigonometry functions, square root, etc.
temp = Math.cos(90) + Math.sqrt(delta);
CSC-101
Static MethodsStatic Methods
In the case of In the case of String, we invoke the methods of the object , we invoke the methods of the object of the class, not the class. of the class, not the class. It makes sense to create an instance It makes sense to create an instance
of the String class with a variable name.of the String class with a variable name. Other classes, like Other classes, like Math, are generally declared , are generally declared staticstatic (like (like
our our main() method). method). It does not make sense to create an instance of these. It does not make sense to create an instance of these. We can invoke them directly.We can invoke them directly.
We will come back to static methods later in the course. We will come back to static methods later in the course. For now, understand that:For now, understand that: static methods can be invoked directly, methods can be invoked directly,
without having to create an object of the class first, butwithout having to create an object of the class first, but other methods, like other methods, like String, ,
do require us to create an object of the class first.do require us to create an object of the class first.
CSC-101
Formatting OutputFormatting Output
The The NumberFormatNumberFormat class has static methods that return a class has static methods that return a formatter objectformatter object
getCurrencyInstance()
getPercentInstance()
Each formatter object has a method called Each formatter object has a method called formatformat that that returns a string with the specified information in the returns a string with the specified information in the appropriate formatappropriate format
Remember to import the appropriate classes first...Remember to import the appropriate classes first... import java.text.NumberFormat;import java.text.NumberFormat; import java.text.DecimalFormat;import java.text.DecimalFormat;
CSC-101
A Note on Localization A Note on Localization (not in textbook)(not in textbook)
A person in the US runs a program called A person in the US runs a program called Price.Price.javajava and it will show and it will show the total price as $20.51.the total price as $20.51.
Q:Q: If a person in Europe runs it, what should it show?If a person in Europe runs it, what should it show? A:A:
20,51 F in France 20,51 F in France 20,51 DM in Germany20,51 DM in Germany etc.etc.
This issue is referred to as This issue is referred to as localizationlocalization, which is the process of making a , which is the process of making a program work appropriately in a particular “Locale” (from java.util).program work appropriately in a particular “Locale” (from java.util).
Workaround:Workaround: import java.util.*; NumberFormat money =
NumberFormat.getCurrencyInstance(Locale.USLocale.US);
CSC-101
Formatting OutputFormatting Output
The The DecimalFormatDecimalFormat class can be used to format a class can be used to format a floating point value in generic waysfloating point value in generic ways
For example, you can specify that the number be printed to For example, you can specify that the number be printed to three decimal placesthree decimal places
The constructor of the The constructor of the DecimalFormatDecimalFormat class takes a class takes a string that represents a pattern for the formatted numberstring that represents a pattern for the formatted number
CSC-101
Displaying Unicode CharactersDisplaying Unicode Characters
Use \udddd Use \udddd
\u indicates Unicode, and \u indicates Unicode, and dddd is the dddd is the hexadecimalhexadecimal notation for the character. notation for the character.
64641010 = 40 = 401616 and 64 and 641010 represents the Unicode character @ represents the Unicode character @
so so System.out.print(“\u0040”); yields yields @@
CSC-101
While We’re On Hex and OctalWhile We’re On Hex and Octal
To represent integers in octal or hexadecimal format:To represent integers in octal or hexadecimal format: 0 preceding a number indicates it is octal.0 preceding a number indicates it is octal. 0x preceding a number indicates it is hexadecimal.0x preceding a number indicates it is hexadecimal.
For example, these three variables are initialized to the For example, these three variables are initialized to the same value:same value: int fee = 255; int fie = 0377; int fum = 0xFF;
soso System.out.print(fee + “\t” + fie + “\t” + fum);
yieldsyields
255 255 255
CSC-101
AppletsApplets
A Java application is a stand-alone program with a A Java application is a stand-alone program with a mainmain method (like the ones we've seen so far)method (like the ones we've seen so far)
An An appletapplet is a Java program that is intended to transported is a Java program that is intended to transported over the web and executed using a web browserover the web and executed using a web browser
An applet can also be executed using the appletviewer tool An applet can also be executed using the appletviewer tool of the Java Software Development Kitof the Java Software Development Kit
An applet does not have a An applet does not have a mainmain method method Instead, there are several special methods that serve Instead, there are several special methods that serve
specific purposesspecific purposes The The paintpaint method, for instance, is automatically executed method, for instance, is automatically executed
and is used to draw the contents of appletsand is used to draw the contents of applets
CSC-101
AppletsApplets
The paint method accepts a parameter that is an object of The paint method accepts a parameter that is an object of the the GraphicsGraphics class class
A A GraphicsGraphics object defines a object defines a graphics contextgraphics context on which we on which we can draw shapes and textcan draw shapes and text
The The GraphicsGraphics class has several methods for drawing class has several methods for drawing shapesshapes
The class that defines the applet The class that defines the applet extendsextends the Applet class the Applet class This makes use of This makes use of inheritanceinheritance, an object-oriented concept , an object-oriented concept
explored in more detail in later chaptersexplored in more detail in later chapters
CSC-101
AppletsApplets
An applet is embedded into an HTML file using a tag that An applet is embedded into an HTML file using a tag that references the bytecode file of the applet classreferences the bytecode file of the applet class
It is actually the bytecode version of the program that is It is actually the bytecode version of the program that is transported across the webtransported across the web
The applet is executed by a Java interpreter that is part of The applet is executed by a Java interpreter that is part of the browserthe browser
CSC-101
Drawing ShapesDrawing Shapes
Let's explore some of the methods of the Let's explore some of the methods of the GraphicsGraphics class class that draw shapes in more detailthat draw shapes in more detail
A shape can be filled or unfilled, depending on which A shape can be filled or unfilled, depending on which method is invokedmethod is invoked
The method parameters specify coordinates and sizesThe method parameters specify coordinates and sizes Recall that the Java coordinate system has the origin in the Recall that the Java coordinate system has the origin in the
upper left cornerupper left corner Many shapes with curves, like an oval, are drawn by Many shapes with curves, like an oval, are drawn by
specifying its specifying its bounding rectanglebounding rectangle An arc can be thought of as a section of an ovalAn arc can be thought of as a section of an oval
CSC-101
Drawing a LineDrawing a Line
X
Y
10
20
150
45
page.drawLine (10, 20, 150, 45);
page.drawLine (150, 45, 10, 20);
oror
CSC-101
Drawing an OvalDrawing an Oval
X
Y
page.drawOval (175, 20, 50, 80);
175
20
50
80
boundingboundingrectanglerectangle
CSC-101
The Color ClassThe Color Class
A color is defined in a Java program using an object A color is defined in a Java program using an object created from the created from the ColorColor class class
The The ColorColor class also contains several static predefined class also contains several static predefined colorscolors
Every graphics context has a current foreground colorEvery graphics context has a current foreground color Every drawing surface has a background colorEvery drawing surface has a background color
Top Related