Download Objects and Primitive Data

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 2
Objects and Primitive Data
The information we process with a Java program is often represented either as primitive
data or objects.
Primitive data refers to common and basic values such as numbers and characters. An object
usually refers to more complicated or specialized data, such as a bank account, which might
contain a value of balance stored as a primitive
data.
1
Class and methods
A data type defines a set of values and the
operations that can be applied to them. For
example, the type of int refers to a collection
of integer values, together with the well-known
operators such as ‘+’, ‘-’, ‘*’ and ‘/’.
An object is defined as a class, which can be
thought of the data type of that object. The
applicable operations are then defined via methods, which is a group of statements with a
name so that we can call later.
For example, the Message class as we saw defines an object that contains one piece of message, together with a bunch of methods.
2
Encapsulation
Once a class is defined, multiple objects of that
class can be created. For example, once the
bank account class is defined, multiple individual accounts can be created. Each of them
will manage its own balance. This concept is
sometimes referred to as encapsulation, meaning each object protects and manages its own
value(s).
The methods we will define on the account
class allow us to operate on individual bank account objects. For example, we can withdraw
money from individual accounts. We sometimes refer to those methods as services, and
refer to their invocation as sending a message to an object, requesting a service be performed.
Homework: Exercises 2.1.
3
Inheritance
Objects can be created based on existing ones
via inheritance. It is really a form of reuse of
something we have already done. In fact, this
technique will lead to a hierarchy of objects,
e.g., several kinds of bank accounts can be
derived based on the bank account class.
4
Use objects
We once saw the following invocation
System.out.println("Whatever you are, be a good one.");
Here System.out represents an output device,
typically, the monitor. More precisely, it refers
to an out object defined in the System class.
The println refers to a service that object performs. Whenever requested, it prints a string
of characters. Technically, we can say that we
send the println message to the System.out
object to request that a text be printed.
5
The print, println method
System.out provides another service print, which
is different from println, in the sense that
println prints a line that switch to the beginning of the next line; while print does not. For
example, check out the following:
public class Countdown{
public static void main (String[] args){
System.out.print ("Three... ");
System.out.print ("Two... ");
System.out.print ("One... ");
System.out.print ("Zero... ");
System.out.println ("Liftoff!");
System.out.println ("Houston, we have a problem.");
}
}
Question: What should the output look like?
Homework: Exercises 2.2–2.5.
6
Abstraction
An object is referred to as an abstraction, in
the sense that the details contained in its definition is irrelevant to its users. We don’t really
care how the Countdown function works as long
as it does its job.
This feature is really essential due to our own
limit in handling things. For example, we can
only mentally managing about 7 (+/- 2) pieces
of information in our short-term memory. Thus,
if we have too much detail, we will necessarily
lose them.
It is also useful. We really don’t need to know
all the details as how an engine works, as long
as it does, to drive a car. On the other hand,
the level of abstraction must be appropriate
since someone has to know, in detail, how an
engine works. Likewise, some one has to define
those objects, later.
7
String literals
A character string is an object defined in the
String class. Java actually provides the ability
to use a string literal, e.g., “string literal”. We
start our study of the String class with the
concatenation method.
public class Facts{
public static void main (String[] args){
System.out.println("We present the following facts"
+ " for your extracurricular edification:");
System.out.println();
System.out.println("Letters in the Hawaiian alphabet:12");
System.out.println("Dialing code for Antarctica: "+672);
System.out.println("Year in which Leonardo da Vinci"
+ " invented the parachute: " + 1515);
System.out.println("Speed of ketchup: " + 40"
+ " km per year");
}
}
Question: What should the output look like?
8
Another example
Let’s check out the following code.
public class Addition{
public static void main (String[] args){
System.out.println("24 and 45 concatenated: "+24+45);
System.out.println ("24 and 45 added: "+(24+45));
}
}
The important thing is that the concatenation
operation works from left to the right. The
first ‘+’ concatenates a string with 24, then
with 45; while in the second println, an arithmetic addition is done first, resulting 69, which
is then concatenated with the string.
9
Escape sequence
We know what """ means, but the compiler will
get confused, since it will regard the second "
as the ending of the quoted string?
In general, since ‘ “ ’ is used to indicate the
beginning and ending of a string, we must use
a special technique to print the quotation character. Java defines a few escape sequences to
represent these special characters. An escape
sequence begins with a ‘´, which indicates that
the following character should be treated differently. Thus, \" represents the double quotation itself. Check out Figure 2.3 for a complete
list.
10
An example
Let’s check out the following program:
public class Roses{
public static void main (String[] args){
System.out.println("Roses are red,\n\t" +
Violets are blue,\nSugar is sweet,\n\t" +
"But I have \"commitment issues\",\n\t" +
"So I’d rather just be friends\n\t " +
"At this point in our relationship.");
}
}
Question: What should the output look like?
11
Variables
A variable is a name for a location in memory that can be used to hold a data value. A
variable declaration instructs the compiler to
reserve a portion of the memory space large
enough to hold a value of a particular type,
and indicate the name by which we can refer
to that location. For example,
int total;
double num1, num2=4, num3;
char letter=’A’, digit=’7’;
final int MAX=45;
When a variable is referenced, the current value
stored there is used.
Homework: Exercise 2.6.
12
Assignment:Change the values
The following program changes the value of a
variable.
public class Geometry{
public static void main (String[] args){
int sides = 7;
System.out.println("A heptagon has "+sides+" sides.");
sides = 10; // assignment statement
System.out.println("A decagon has "+sides+" sides.");
sides = 12;
System.out.println("A dodecagon has "+sides+" sides.");
}
}
A variable can store only one value at a time.
When a new value is assigned to the variable,
its original value is overwritten.
The types of the value to be assigned and that
of the variable must be compatible, otherwise
a compile-time error will be reported.
13
Constants
When we want to use a data that never changes,
we declare that it is a constant. It often makes
sense to give such a constant a name, such as
MAX OCCUPANCY instead of a number, such as 43.
Constants are special variables in the sense
that their values never change. In Java, if you
precede a variable name with the word final,
you turn it into a constant. For example,
final int MAX_OCCUPANCY=43;
If you later on, decide to change the maximum
occupancy figure, it is easy to do it throughout
the program: you just change its initial value.
14
Integers and floats
A value of int type does not have a fractional
part, and a float type does. There are four integer types (byte, short, int, and long); and
two floating point data types (float and double).
They differ by the amount of space available
to store a value of that type. For example, a
variable of type byte can hold a value between
-128 to 127. Check out Figure 2.4 for the
whole list.
We should be careful to pick up the appropriate
types. For instance, if we know for sure that
the range of a variable is between 1 to 1000,
then we can simply pick the type of short.
On the other hand, although the type float
can keep very large, and very small, values,
it only has 7 significant digits. Thus, if it is
important to accurately maintain a value such
as 50431.2077, we should adopt double.
15
Literals
A literal is an explicit data value used in the
program. Java assumes all the integer literals,
such as 45, are of type int, unless an L or l
is appended to its end to indicate it should be
considered as a literal of type Long.
Similarly, Java assumes all floating pint literals
of type double, unless it is appended with an
F or f to indicate it is really a literal of type
float. For examples,
int answer=42;
byte smallNumber;
long countedStars=86827263927L;
float ratio=0.2363F;
double delta=453.523311903;
Question: What is the difference between a
literal and a constant?
16
Characters
A character literal is expressed in a Java program with single quotes, such as ‘b’ or ‘J’;
while string literals are expressed with double
quotes, such as “Java”.
The common character set we use is called
the ASCII set, which supports 128 different
characters using 7 bits. It includes upper case,
lower case letters, various punctuation, the digits ‘0’ through ‘9’, the space, and some of the
special symbols such as ‘&’, and several control characters, such as the carriage return, null
and end-of-text marks. The extended ASCII
set contains 256 characters, containing many
accented and diacritical symbols not used in
English.
17
The developers of the Java language chose the
Unicode character set, which supports 65,536
unique characters, using 16 bits. For more details, please check out Appendix C. For example,
char topGrade=‘A’;
char symbol1, symbol2;
char terminator=’;’, separator=’ ’;
A variable of type boolean is usually used to
indicate if a condition holds, with only two reserved values: true and false. For example,
boolean flag=true;
boolean tooHigh, tooSmall, tooRough;
boolean done=false;
18
Arithmetic expressions
An expression is a combination of one or more
operators and operands, which usually performs
an calculation. When it is an arithmetic expression, such a calculation leads to a number. The operands can be literals, constants,
variables, or other source of data; while the operators can be ‘+’, ‘-’, ‘*’, ‘/’, or ‘%’, which
is the remainder operator returning the result
of a remainder operation.
If at least one of the two operands is a floating
point value, the result is a floating point value.
This is particularly important for the division
operator (‘/’), when both of its operands are
integers, the fractional part is dropped. For
example, 10/4=2, but 10/4.0=2.5.
Homework Exercise 2.7.
19
Operator precedence
Just like characters can be combined into words
and sentences, operators can be combined to
create long and complex expressions. For example, in the following typical assignment statement:
result=14+8-2;
The RHS, 14+8-2, is evaluated first to come
up to 20, which is then assigned to the variable result. The result gets a value 20, since
the operators ‘+’ and ‘-’ have the same precedence, thus whichever comes first will be applied first.
20
Since ‘*’ has higher precedence than ‘-’, when
evaluating 14+8*2, we would have to perform
the multiplication first, to get 30. If we really
want to apply the addition first, we have to
write (14+8)*2, which leads to 44.
Check out Figure 2.5 for a complete listing of
the precedence among Java operators.
21
An example
In the following program, which converts temperature between two systems, we make sure
that the fractional part of the division will not
get lost.
public class TempConverter{
public static void main (String[] args){
final int BASE=32;
final double CONVERSION_FACTOR=9.0/5.0;
int celsiusTemp=24; // value to convert
double fahrenheitTemp;
fahrenheitTemp=celsiusTemp*CONVERSION_FACTOR+BASE;
System.out.println("Celsius Temperature: "
+celsiusTemp);
System.out.println("Fahrenheit Equivalent: "
+fahrenheitTemp);
}
}
22
Data conversion
Java is a strongly typed language, in the sense
that every value is associated with a type. Thus,
it is sometimes useful to convert one type to
another during data processing. The bottom
line is that we have to make sure that we
won’t lose any important information during
such conversion. For example if we convert a
short variable that holds a value of 1000 to a
byte value, we will end of losing it (?).
A conversion could be either widening or narrowing. Widening goes from one type to another one with equal or greater space, thus is
usually safe. However, when converting from
an int or a long to a float, some of the least
significant digits may be lost, and the resulted
floating point value will be just a rounded version of the original integer.
A narrowing conversion is more likely to lose
information, except converting from a byte or
short to a character.
23
More specifically,...
In Java, data can be converted in one of the
following three ways: assignment conversion,
arithmetic promotion, and casting.
Assignment conversion occurs automatically when
a value of one type is assignment to a variable
of another type. For example, in
int dollar=12;
float money=dollar;
If we print out the value of money, it will be
12.0, since it is not a floating point value.
24
Arithmetic promotion
Arithmetic promotion occurs automatically when
such conversion becomes necessary. For example, in
float sum;
int count;
float result=sum/count;
the variable count is automatically promoted to
float.
25
Casting is the most general form of data conversion. If a conversion can happen at all, it
will happen using a cast. For example,
dollars = (int) money;
int cents = (money-dollar)*100;
Thus, any fractional part of the float type
money will be dropped, then their difference,
multiplied by 100, gives the amount of cents.
Cast is pretty useful to treat a value of one
type temporarily as another type. For example,
when evaluating
result=(float) total/count;
a floating point version of total is returned
first(?), without affecting the value of the int
type variable total, then the type of count is
promoted to float via arithmetic promotion.
Finally, a division between two float type data
is performed.
26
Create objects
A variable can hold either a primitive value,
as we have seen, or can be a reference to an
object. In either case, it has to be declared. An
object is defined via its associated class. For
example, the following line creates a reference
to a String object:
String name;
To initialize a value for name, we use the new
operator, which creates a reference to a newly
created object:
name=new String("Java course");
Of course, the above declaration and instantiation can be combined as follows:
String name=new String("Java course");
27
Method access
Once an object is instantiated, we can use the
‘.’ operator to access its methods. For example, if we want to access the length method to
count the number of characters in the name
object, we can do the following:
count=name.length();
Note: the length method does not take any
parameters, but we still need to keep the ().
Also, in this case, the method does return a
value, that should be the number of characters
in the calling object; while some other methods
do not return any value.
28
The String class
Strings in Java are objects represented by the
String class. Besides the constructor String()
and the counter length(), there are other useful methods, such as char charAt(int index),
which returns the character of the calling object at the specified index; int compareTo(String
str), which returns an integer indicating if
this string is lexically before (a negative value),
or equal to(0), or after (a positive value), the
string str.
Check out Figure 2.8 for a list of some of the
String related methods, and pp. 886 for a complete list.
29
An example
Several of these methods are used in the following code.
public class StringMutation{
public static void main(String[] args){
String phrase=new String("Change is inevitable");
String mut1,mut2,mut3,mut4;
System.out.println("Original: \""+phrase+"\"");
System.out.println("Length: "+phrase.length());
mut1=phrase.concat(", except from vending machines.");
mut2=mut1.toUpperCase();
mut3=mut2.replace (’E’, ’X’);
mut4=mut3.substring (3, 30);
System.out.println("Mut #1: "+mut1);
System.out.println("Mut #2: "+mut2);
System.out.println("Mut #3: "+mut3);
System.out.println("Mut #4: "+mut4);
System.out.println("Mutated length: "+mut4.length());
}
}
Question: What should the output look like?
30
Class libraries and packages
A class library is a set of classes that supports program development. A compiler often comes with such a library. Those classes
often contain methods that are valuable to a
programmer because of the special functionality they provide. Although programmers often
think they are part of the language, they are
not, merely add on.
For example, the String class we just went
through, is not part of the Java language, but
a part of the standard class library, that can be
found in any Java development environment.
31
API
A collection of related library classes that are
available in a programming environment is called
Application Programmer Interfaces. In particularly, those available in the Java environment
is referred to as the Java API. Check out, e.g.,
java.sun.com/j2se/1.5.0/docs/api/ for the details. Appendix M also includes a list of API
and their associated packages for j2se 1.4.
For example, when we want to write database
related applications, we may refer to the Java
Database API, the DatabaseMetaData interface to be exact. Another one is the Swing
API, which collects classes that define special
graphical user interface (GUI).
32
Packages
Classes serving a certain purpose in the standard class library are further grouped into packages. For example, both the String class and
the System class are parts of the java.lang package.
The package organization is more fundamental and language based than the API names.
The names of API might cross packages. We
will pay more attention to the packages in this
course.
Homework: Exercises 2.11.
33
The import declaration
The classes of the package java.lang are automatically available for use when writing a program. To use classes from any other package,
we have to explicitly import them. For example, if you want to use the Random class that is
defined in the java.util package in your program, you have to write down the following:
import java.util.Random;
On the other hand, if you want to make everything defined in java.util available, you simply
say
import java.util.*;
Check out Figure 2.11 for a complete list of
packages available in the Java language.
34
Random numbers
A random number is a number that is picked
up randomly, namely, all of the numbers have
the same chance to be picked up. We often
need to use random numbers when writing interesting programs. For example, in playing
games, we often roll a die or shuffle cards. A
SAT preparation program may use a random
number generator (rng) to pick the next question.
Practically, there is no way to consider all the
numbers, since it would take infinite amount
of time and space. The most we can do is to
implement a pseudorandom number generator,
when all the numbers within a certain range
will have the same chance to be picked up.
35
How to generate ...?
Java provides two methods: nextFloat() and
nextInt(). float nextFloat() returns a random number between 0.0 and 1.0. They come
with the java.util.Random package.
On the other hand, int nextInt() returns a
random that ranges over all possible int values,
i.e., between 0 and a bit over 4 billions; and
int nextInt(int num) returns one in the range
0 to num-1. We will focus on the integers.
Question: How to generate a random number
between 0 and 5?
Answer: nextInt(6)
36
A bit more
Question: How to generate a random number
between 1 and 6?
Answer: We cannot directly generate them.
But, we know that 1) we have to generate 6
random numbers, and 2) They range from 1 to
6. We call nextInt(6) to generate 6 numbers,
0, 1, 2, 3, 4, and 5; then add a 1 to make them
into 1, 2, 3, 4, 5, and 6. Thus, nextInt(6)+1.
Question: How to generate a random number
between 22 and 45?
Answer: Again, we find out that we need
to generate (45-22+1)=24 random numbers,
and call nextInt(24) to generate them: 0, 1,
..., 23; then add a 22 to get the original sequence. Thus, nextInt(24)+22.
37
A general procedure
Question: How to generate a random number
between m1 and m2(> m1)?
Answer: Go through the following two steps:
1. Calculate n = m2 − m1 + 1;
2. Call nextInt(n)+m1.
We will work with random numbers in the lab.
Homework: Exercises 2.12 and 2.13.
38
Invoking class methods
Some of the methods can be invoked directly
through the names of the class in which they
are defined, without having to instantiate an
object of the class first. The Math and Keyboard
classes are two such examples.
import cs1.Keyboard;
public class Quadratic{
public static void main (String[] args){
int a, b, c; // ax^2 + bx + c
System.out.print ("Enter the first value: ");
a=Keyboard.readInt();
System.out.print ("Enter the second value: ");
b=Keyboard.readInt();
System.out.print ("Enter the constant: ");
c=Keyboard.readInt();
double discriminant=Math.pow(b, 2)-(4 * a * c);
double root1=((-1*b)+Math.sqrt(discriminant))/(2 * a);
double root2=((-1*b)-Math.sqrt(discriminant))/(2 * a);
System.out.println ("Root #1: " + root1);
System.out.println ("Root #2: " + root2);
}}
Question: Why is the Math package not imported?
Homework: Exercises 2.8, 2.9, and 2.10.
39
Formatting output
The NumberFormat class and the DecimalFormat
class are used to format information so that
it looks appropriate when printed or displayed.
They are both part of the Java standard class
library and are defined in the java.text package.
The NumberFormat class provides generic formating capabilities for numbers. We don’t
need to instantiate a NumberFormat object using the new operator, instead, we request one
via one of the methods that can be invoked
through the class. A reason is that the format
is fixed, thus need not be specified.
40
An example
Notice that in the following, we get an object,
fmt1, then use it to format the quantity of tax
in the form of currency.
import cs1.Keyboard;
import java.text.NumberFormat;
public class Price{
public static void main (String[] args){
final double TAX_RATE = 0.06; // 6% sales tax
int quantity;
double subtotal, tax, totalCost, unitPrice;
System.out.print ("Enter the quantity: ");
quantity=Keyboard.readInt();
System.out.print("Enter the unit price: ");
unitPrice=Keyboard.readDouble();
subtotal=quantity*unitPrice;
tax=subtotal*TAX_RATE;
totalCost=subtotal + tax;
NumberFormat fmt1=NumberFormat.getCurrencyInstance();
NumberFormat fmt2=NumberFormat.getPercentInstance();
System.out.println("Subtotal: "+fmt1.format(subtotal));
System.out.println("Tax: "+fmt1.format(tax) + " at "
+ fmt2.format(TAX_RATE));
System.out.println ("Total: "
+ fmt1.format(totalCost));
}
}
41
The DecimalFormat class
This is different from the NumberFormat class.
We have to use the new method to define the
needed format.
import java.text.DecimalFormat;
public class CircleStats{
public static void main (String[] args){
int radius;
double area, circumference;
System.out.print ("Enter the circle’s radius: ");
radius = Keyboard.readInt();
area = Math.PI * Math.pow(radius, 2);
circumference = 2 * Math.PI * radius;
// Round the output to three decimal places
DecimalFormat fmt = new DecimalFormat ("0.###");
System.out.println ("The circle’s area: "
+ fmt.format(area));
System.out.println ("The circle’s circumference: "
+ fmt.format(circumference));
}
}
Homework: Exercises 2.14.
42
Introducing Applets
A Java application is a stand-alone program
that can be executed by a Java interpreter.
On the other hand, a Java applet is a Java
program that is intended to be embedded into
an HTML document, transported across a network, and executed using a Web browser. It is
considered just another type of media that can
be exchanged via the Web. When an applet in
the form of bytecode reaches its destination,
an embedded Java interpreter will execute it.
Besides being sent over across, an applet can
be executed via a local browser, or can be executed via other tools, such as the appletviewer
that comes with the JDK.
43
An example
Since the browser that runs an applet is already
running, applets can be thought of as part of
a larger program. Thus, e.g., it does not need
to have the main method. Applet classes have
to be declared as public as well.
import java.applet.Applet;
import java.awt.*;
public class Einstein extends Applet{
public void paint (Graphics page){
page.drawRect (50, 50, 40, 40);
//
page.drawRect (60, 80, 225, 30);
//
page.drawOval (75, 65, 20, 20);
//
page.drawLine (35, 60, 100, 120); //
square
rectangle
circle
line
page.drawString ("Out of clutter, find simplicity.",
110, 70);
page.drawString ("-- Albert Einstein", 130, 100);
}
}
44
How to run an applet?
For an applet to run, it must be referenced in
an HTML document. For example,
<HTML>
<HEAD>
<TITLE>The Einstein Applet</TITLE>
</HEAD>
<BODY>
<center>
<H3>The Einstein Applet</H3>
<applet code="Einstein.class" width=350
height=175>
</applet>
</center>
<p>Above this text you should see a picture of
a some shapes and a quote by Albert Einstein.
This picture is generated by a Java applet.
</BODY>
</HTML>
45
Drawing shapes
The Graphics class is defined in the java.awt
package. It contains various methods that allow us to draw such shapes, including lines,
rectangles, and ovals. All of them depend on
the Java coordinates. Every point is represented by a pair (x, y), where (0, 0) indicates
the upper left corner of a graphical object.
When x gets larger, we are moving to the right,
and when y gets larger, we are moving down.
46
Figure them out
Thus, the method void drawLine(int x1, int
y1, int x2, int y2) draws a line from (x1, y1)
to (x2, y2).
drawArc(int x, int y, int width, int height,
int StartAngle, int arcAngle) is a bit more complicated.
Homework: Check out figures 2.20 to figure
out the mechanism of drawArc. Complete exercises 2.16–2.19.
47
The color class
We can use the color class, part of the java.awt
package, to define and manage colors. For
example, Color.black represents the color of
black. Check out Figure 2.21 for the whole
listing of colors.
Every graphics context has a current foreground
color that is used whenever something is drawn.
This is set by using the setColor method. Every surface that can be drawn has a background color, which is set by using the setBackground
method.
These concepts are best described by going
through an example.
48
The snow man
import java.applet.Applet;
import java.awt.*;
public class Snowman extends Applet{
public void paint (Graphics page){
final int MID = 150;
final int TOP = 50;
setBackground(Color.cyan);
page.setColor(Color.blue);
page.fillRect(0, 175, 300, 50); // ground
page.setColor(Color.yellow);
page.fillOval(-40, -40, 80, 80); // sun
page.setColor(Color.white);
page.fillOval(MID-20, TOP, 40, 40); // head
page.fillOval(MID-35, TOP+35, 70, 50);// upper torso
page.fillOval(MID-50, TOP+80, 100, 60); // lower torso
page.setColor(Color.black);
page.fillOval(MID-10, TOP+10, 5, 5); // left eye
page.fillOval(MID+5, TOP+10, 5, 5); // right eye
page.drawArc(MID-10, TOP+20, 20, 10, 190, 160); //smile
page.drawLine(MID-25, TOP+60, MID-50, TOP+40); //left arm
page.drawLine(MID+25, TOP+60, MID+55, TOP+60); //right arm
page.drawLine(MID-20, TOP+5, MID+20, TOP+5); //hat brim
page.fillRect(MID-15, TOP-20, 30, 25); //top of hat
}
}
49