Objects and Primitive Data

Similar documents
Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods

Applets and the Graphics class

Data Representation and Applets

Chapter. Let's explore some other fundamental programming concepts

Data Representation and Applets

Data Representation and Applets

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

objectives chapter Define the difference between primitive data and objects. Declare and use variables. Perform mathematical computations.

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Using Classes and Objects. Chapter

Chapter 2: Data and Expressions

A variable is a name for a location in memory A variable must be declared

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

Chapter 2: Data and Expressions

2: Basics of Java Programming

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Chapter 2: Data and Expressions

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

2 rd class Department of Programming. OOP with Java Programming

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY

Lecture 3: Variables and assignment

CMPT 125: Lecture 3 Data and Expressions

Chapter 2 Exercise Solutions

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

Data Representation and Applets

We now start exploring some key elements of the Java programming language and ways of performing I/O

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

Full file at

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name:

Chapter 2. Elementary Programming

Example: Tax year 2000

ECE 122 Engineering Problem Solving with Java

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Program Fundamentals

Classes and Objects Part 1

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key

Java Basic Introduction, Classes and Objects SEEM

Using Classes and Objects

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Computational Expression

Zheng-Liang Lu Java Programming 45 / 79


Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Lab5. Wooseok Kim

COMP 202 Java in one week

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Data Representation Classes, and the Java API

Chapter 2 ELEMENTARY PROGRAMMING

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Java Basic Introduction, Classes and Objects SEEM

Getting started with Java

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Types and Expressions. Chapter 3

COMP 202. Java in one week

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Program Elements -- Introduction

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Elementary Programming

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Elementary Programming

Full file at

Introduction to Java (All the Basic Stuff)

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

CIS133J. Working with Numbers in Java

Chapter 3 Using Classes and Objects

CEN 414 Java Programming

What did we talk about last time? Examples switch statements

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Lab5. Wooseok Kim

Lab 3: Work with data (IV)

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Building Java Programs

Programming with Java

Expressions and Casting

B.V. Patel Institute of BMC & IT, UTU 2014

Declaration and Memory

Data Types and the while Statement

Building Java Programs

CS1004: Intro to CS in Java, Spring 2005

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMP-202 Unit 2: Programming Basics. CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

OBJECT ORIENTED PROGRAMMING IN JAVA

Section 2: Introduction to Java. Historical note

CS111: PROGRAMMING LANGUAGE II

Transcription:

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 m 1 and m 2 (>m 1 )? Answer: Go through the following two steps: 1. Calculate n = m 2 m 1 +1; 2. Call nextint(n)+m 1. 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); // square page.drawrect (60, 80, 225, 30); // rectangle page.drawoval (75, 65, 20, 20); // circle page.drawline (35, 60, 100, 120); // 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

import java.applet.applet; import java.awt.*; The snow man 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