Slide #1.

Chapter 2 Data and Expressions Part Two
More slides like this


Slide #2.

Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes 2-2/30
More slides like this


Slide #3.

Expressions • An expression is a combination of one or more operators and operands • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder + * / % • If either or both operands used by an arithmetic operator are floating point, then the result is a floating point 2-3/30
More slides like this


Slide #4.

Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3 equals 4 8 / 12 equals 0 • The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % 3 equals 2 8 % 12 equals 8 2-4/30
More slides like this


Slide #5.

Arithmetic Expressions - continued • If operands are mixed, results are ‘promoted.’  4.5 + 2 = 6.5 (double)  Sometimes called “widened.” 2-5/30
More slides like this


Slide #6.

Operator Precedence • Operators can be combined into complex expressions result = total + count / max - offset; • Operators have a well-defined precedence which determines the order in which they are evaluated • Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order 2-6/30
More slides like this


Slide #7.

Operator Precedence • What is the order of evaluation in the following expressions? a + b + c + d + e 1 2 3 4 a + b * c - d / e 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 2-7/30
More slides like this


Slide #8.

Expression Trees • The evaluation of a particular expression can be shown using an expression tree • The operators lower in the tree have higher precedence for that expression + a + (b – c) / d / a b d c 2-8/30
More slides like this


Slide #9.

Assignment Revisited • The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = 4 sum / 4 + MAX * lowest; 1 3 2 Then the result is stored in the variable on the left hand side Then the result is stored in the variable on the left hand side NOTE: the ‘assignment operator (again) IS an operator – (merely has lower precedence than arithmetic operators….) 2-9/30
More slides like this


Slide #10.

Assignment Revisited • The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value) KNOW THE OPERATOR PRECEDENCE TABLE ON PAGE 78. It will grow significantly! 2-10/30
More slides like this


Slide #11.

Increment and Decrement • The increment and decrement operators use only one operand • The increment operator (++) adds one to its operand • The decrement operator (--) subtracts one from its operand • The statement count++; is functionally equivalent to count = count + 1; 2-11/30
More slides like this


Slide #12.

Increment and Decrement • The increment and decrement operators can be applied in postfix form: count++ • or prefix form: ++count   When used as part of a larger expression, the two forms can have different effects • Because of their subtleties, the increment and decrement operators should be used with care 2-12/30
More slides like this


Slide #13.

Assignment Operators • Often we perform an operation on a variable, and then store the result back into that variable • Java provides assignment operators to simplify that process • For example, the statement num += count; is equivalent to num = num + count; 2-13/30
More slides like this


Slide #14.

Assignment Operators • There are many assignment operators in Java, including the following: Operator += -= *= /= %= Example x x x x x += -= *= /= %= y y y y y Equivalent To x x x x x = = = = = x x x x x + * / % y y y y y 2-14/30
More slides like this


Slide #15.

Assignment Operators   The right hand side of an assignment operator can be a complex expression • The entire right-hand expression is evaluated first, then the result is combined with the original variable • Therefore result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num); 2-15/30
More slides like this


Slide #16.

Assignment Operators • The behavior of some assignment operators depends on the types of the operands • If the operands to the += operator are strings, the assignment operator performs string concatenation • The behavior of an assignment operator (+=) is always consistent with the behavior of the corresponding operator (+) 2-16/30
More slides like this


Slide #17.

Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes 2-17/30
More slides like this


Slide #18.

Data Conversion • Sometimes it is convenient to convert data from one type to another • For example, in a particular situation we may want to treat an integer as a floating point value • These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation 2-18/30
More slides like this


Slide #19.

Data Conversion • Conversions must be handled carefully to avoid losing information • Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) • Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) • In Java, data conversions can occur in three ways:  assignment conversion  promotion  casting 2-19/30
More slides like this


Slide #20.

Assignment Conversion • Assignment conversion occurs when a value of one type is assigned to a variable of another • If money is a float variable and dollars is an int variable, the following assignment converts the value in dollars to a float money = dollars • Only widening conversions can happen via assignment (I do NOT believe this to be true!) • Note that the value or type of dollars did not change 2-20/30
More slides like this


Slide #21.

Data Conversion • Promotion happens automatically when operators in expressions convert their operands • For example,  if sum is a float and count is an int,  the value of count is converted to a floating point value to perform the following calculation: result = sum / count; • Result is stored in result. • BUT count is still an int. It was promoted in order only to evaluate this expression, but it is still an int. 2-21/30
More slides like this


Slide #22.

Casting • Casting is the most powerful, and dangerous, technique for conversion (but done all the time) • To cast, the type is put in parentheses in front of the value being converted • For example, if total and count are both integers, but we want a floating point result when dividing them, we can cast total: (This makes one of the operands a float; this forces count to be promoted to float for the division to take place. • Remember, both total and count remain ints after. result = (float) total / count; 2-22/30
More slides like this


Slide #23.

Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics 2-23/30
More slides like this


Slide #24.

The Scanner Class • The Scanner class is part of the standard Java class library and makes elementary input/output easier for new Java students. • We will use it for now. • Scanner objects allow us to input data either interactively (from the keyboard) or from a data file. • Scanner methods also allow us to parse a String into its constituent components. • Of course, to use any methods of a class, we must instantiate the class and create an object of that class. 2-24/30
More slides like this


Slide #25.

Scanner Object Methods String next() method returns the next input token as a char string String nextLine() method returns all input remaining on current line as a single character string byte nextByte() double nextDouble() float nextFloat() – int nextInt() – returns the next byte returns the next double returns the next float returns the next int. A number of additional methods are available…. Look and see!  Discuss methods and how they become available from this object! 2-25/30
More slides like this


Slide #26.

Scanner Objects • Create Scanner objects: Scanner scan = new Scanner (System.in); This creates a new object called ‘scan’ and tells the object that the input will be coming from the system standard input stream (defaults to keyboard). The object is created by the ‘new’ operator, which calls a special method called a ‘constructor’ to set up the object. The constructor takes the system.in as an argument and now looks for input to come via the keyboard. 2-26/30
More slides like this


Slide #27.

Scanner Objects • Inputs: Scanner object assumes input ‘tokens’ are separated by a ‘delimiter.’ • Default delimiter is ‘white space’ (blanks or a few special characters – later). • Delimiters can be changed to, say, commas, … • Delimiters are used to separate the inputs from each other. 2-27/30
More slides like this


Slide #28.

Scanner Example import java.util.Scanner; public class GasMileage { // Program computes gas mileage given input miles and gasoline consumed public static void main (String [ ] args) { int miles; double gallonws, mpg; Scanner scan = new Scanner (System.in); System.out.println (“Enter the number of miles: “); miles = scan.nextInt(); System.out.println (“Enter the number of gallons of fuel used: “); gallons = scan.nextDouble(); mpg = miles/gallons; System.out.println (“Miles Per Gallon: “ + mpg); }// end main() }// end class GasMileage 2-28/30
More slides like this


Slide #29.

Sample Outputs: Enter the number of miles: 328 Enter the gallons of fuel used: 11.2 Miles Per Gallon 29.44565345676434 When you compile/run this program on NetBeans, if you have no compilation errors, you will go into execution. If so, your inputs will be requested down the bottom of the window. Enter the requested value and press Enter. There are a lot of assumptions in using the Scanner objects. We will get back to it later. But for now, it is expeditious to use. 2-29/30
More slides like this


Slide #30.

We will stop here • And return if we have time later… 2-30/30
More slides like this


Slide #31.

Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes 2-31/30
More slides like this


Slide #32.

Introduction to Graphics • The last few sections of each chapter of the textbook focus on graphics and graphical user interfaces • A picture or drawing must be digitized for storage on a computer • A picture is made up of pixels (picture elements), and each pixel is stored separately • The number of pixels used to represent a picture is called the picture resolution • The number of pixels that can be displayed by a monitor is called the monitor resolution 2-32/30
More slides like this


Slide #33.

Coordinate Systems • Each pixel can be identified using a twodimensional coordinate system • When referring to a pixel in a Java program, we use a coordinate system with the origin in the topleft corner (0, 0) 40 112 X (112, 40) Y 2-33/30
More slides like this


Slide #34.

Representing Color • A black and white picture could be stored using one bit per pixel (0 = white and 1 = black) • A colored picture requires more information; there are several techniques for representing colors • For example, every color can be represented as a mixture of the three additive primary colors Red, Green, and Blue • Each color is represented by three numbers between 0 and 255 that collectively are called an RGB value 2-34/30
More slides like this


Slide #35.

The Color Class • A color in a Java program is represented as an object created from the Color class • The Color class also contains several predefined colors, including the following: Object RGB Value Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0 2-35/30
More slides like this


Slide #36.

Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes 2-36/30
More slides like this


Slide #37.

Applets • A Java application is a stand-alone program with a main method (like the ones we've seen so far) • A Java applet is a program that is intended to transported over the Web and executed using a web browser • An applet also can be executed using the appletviewer tool of the Java Software Development Kit • An applet doesn't have a main method • Instead, there are several special methods that serve specific purposes 2-37/30
More slides like this


Slide #38.

Applets • The paint method, for instance, is executed automatically and is used to draw the applet’s contents • The paint method accepts a parameter that is an object of the Graphics class • A Graphics object defines a graphics context on which we can draw shapes and text • The Graphics class has several methods for drawing shapes 2-38/30
More slides like this


Slide #39.

Applets • The class that defines an applet extends the Applet class • This makes use of inheritance, which is explored in more detail in Chapter 8 • See Einstein.java (page 97) 2-39/30
More slides like this


Slide #40.

//******************************************************************** // Einstein.java Author: Lewis/Loftus // // Demonstrates a basic applet. //******************************************************************** import javax.swing.JApplet; import java.awt.*; public class Einstein extends JApplet { //----------------------------------------------------------------// Draws a quotation by Albert Einstein among some shapes. //----------------------------------------------------------------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); } } 2-40/30
More slides like this


Slide #41.

• An applet is embedded into an HTML file using a tag that references the bytecode file of the applet • The bytecode version of the program is transported across the web and executed by a Java interpreter that is part of the browser 2-41/30
More slides like this


Slide #42.

The HTML applet Tag The Einstein Applet 2-42/30
More slides like this


Slide #43.

Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes 2-43/30
More slides like this


Slide #44.

Drawing Shapes • Let's explore some of the methods of the Graphics class that draw shapes in more detail • A shape can be filled or unfilled, depending on which method is invoked • The method parameters specify coordinates and sizes • Shapes with curves, like an oval, are usually drawn by specifying the shape’s bounding rectangle • An arc can be thought of as a section of an oval 2-44/30
More slides like this


Slide #45.

Drawing a Line 10 150 X 20 45 Y page.drawLine (10, 20, 150, 45); or page.drawLine (150, 45, 10, 20); 2-45/30
More slides like this


Slide #46.

Drawing a Rectangle 50 X 20 40 100 Y page.drawRect (50, 20, 100, 40); 2-46/30
More slides like this


Slide #47.

Drawing an Oval 175 X 20 80 bounding rectangle Y 50 page.drawOval (175, 20, 50, 80); 2-47/30
More slides like this


Slide #48.

Drawing Shapes • Every drawing surface has a background color • Every graphics context has a current foreground color • Both can be set explicitly • See Snowman.java (page103) 2-48/30
More slides like this


Slide #49.

// Snowman.java Author: Lewis/Loftus // Demonstrates basic drawing methods and the use of color. import javax.swing.JApplet; import java.awt.*; public class Snowman extends JApplet { // Draws a snowman. 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); // brim of hat page.fillRect (MID-15, TOP-20, 30, 25); // top of hat } } 2-49/30
More slides like this


Slide #50.

Summary • Chapter 2.2 focused on:  expressions and operator precedence  brief introduction to objects (out of place – chap 3)  accepting input from the user – using Buffered Reader  Data conversions  Wrapper classes  Java applets  Introduction to graphics 2-50/30
More slides like this