3 1 Data Types Using Objects Data Types

3. 1 Data Types: Using Objects

Data Types Data type. Set of values and operations on those values. Primitive types. “Built-in” for a language. Basic “building blocks” Usually single values. Operations directly translate to machine instructions. n n n Data Type Set of Values Operations boolean true, false not, and, or, xor int -231 to 231 - 1 add, subtract, multiply double any of 264 possible reals add, subtract, multiply OK, but we want to write programs that process other types of data. Colors, pictures, strings, input streams, … Complex numbers, vectors, matrices, polynomials, … Points, polygons, charged particles, celestial bodies, … n n n 2

Data Types and Abstraction Remember Abstraction? Hiding details…. One principle of “computational thinking. ” When we use data types, keep these things in mind: We don’t have to understand exactly how bits are stored in the machine. We have an “information model” (or set of values), and… We have operations to use -- even if we don’t know exactly how they’re implemented! n n n Question for you: If operations hide details and are a form of abstraction, can you think of something else we’ve done in Java that is also an example of this “procedural abstraction”? n 3

“Non-primitive” types Reference type. In Java, not a simple, basic data type. Arrays are one kind of reference type. Object types are another. n n n – Examples: String, In n “Class” means data type that’s an object – Class and type. Object and variable. What’s important about reference types? Object types are not part of the “core” language (perhaps part of standard libraries). Arrays are. Object types can be defined by someone or by us. The variable “refers to” or “points to” a separate chunk of memory. We can access things inside what’s pointed to. n n – Example: int[] a = new int[10]; a. length – Problem: int[] b; b. length 4

Objects Object. Holds a value of a particular data-type. A variable name refers to an object. Class. The data type Impact. Enables us to create our own data types; define operations on them; and integrate into our programs. Data Type Set of Values Operations Color 24 bits get red component, brighten Picture 2 D array of colors get/set color of pixel (i, j) String sequence of characters length, substring, compare 5

Example Data Type (Class): Charge A Charge class. Represents a charged particle in a 2 -dim space. Can use this to study “electric potential. ” Data Model. Location in a 2 -dim space, so x and y values The charge at that point Operations. Calculate potential due to this particle as some other (x, y) Convert this to a String for output n n An API defines functions (known as methods) for each class: Charge (double x 0, double y 0, double q 0) // constructor double potential. At( double x, double y) String to. String() n n n 6

Methods for a Class Note! No operators like +, *, etc. Methods / Functions. These are slightly different than previous methods These are “instance methods” Previously we wrote “static” methods n n n Instance methods are called “on” an object (a variable) System. out. println(); // call println on System. out String s = a. Charge. to. String(); // call to. String on a. Charge In file. In = new In(“file. txt”); file. In. read. Int(); n n n Ways to think about this: Send a message to an object. Tell an object to do something. n n 7

Constructors In Java, remember: Variables must be initialized when created. We must have a way to make this happen for “new” types. One special instance method in the API: Charge (double x 0, double y 0, double q 0) // constructor n n This is a method called when you invoke “new” to create a new object! You can pass parameters to control initialization. The class’ author defines the logic for this method to carry out proper initialization. 8

Example: Constructors and Methods To construct a new object: Use keyword new and name of data type. To apply an operation: Use name of object, the dot operator, and the name of the method. 9

String Data Type String data type. Basis for text processing. Set of values. Sequence of Unicode characters. API. … http: //java. sun. com/j 2 se/1. 5. 0/docs/api/java/lang/String. html 10

Typical String Processing Code 11

12

Image Processing

Color Data Type Color. A sensation in the eye from electromagnetic radiation. Set of values. [RGB representation] 2563 possible values, which quantify the amount of red, green, and blue, each on a scale of 0 to 255. R G B 255 0 0 0 255 105 105 Color 14

Color Data Type Color. A sensation in the eye from electromagnetic radiation. Set of values. [RGB representation] 2563 possible values, which quantify the amount of red, green, and blue, each on a scale of 0 to 255. API. Application Programming Interface. http: //java. sun. com/j 2 se/1. 5. 0/docs/api/java/awt/Color. html 15

Albers Squares Josef Albers. Revolutionized the way people think about color. Homage to the Square by Josef Albers (1949 -1975) 16

Albers Squares Josef Albers. Revolutionized the way people think about color. % java Albers. Squares 9 90 166 100 100 17

Using Colors in Java import java. awt. Color; to access Color library public class Albers. Squares { public static void main(String[] args) { int r 1 = Integer. parse. Int(args[0]); int g 1 = Integer. parse. Int(args[1]); int b 1 = Integer. parse. Int(args[2]); Color c 1 = new Color(r 1, g 1, b 1); int r 2 = int g 2 = int b 2 = Color c 2 Integer. parse. Int(args[3]); Integer. parse. Int(args[4]); Integer. parse. Int(args[5]); = new Color(r 2, g 2, b 2); Std. Draw. set. Pen. Color(c 1); Std. Draw. filled. Square(. 25, . 2); Std. Draw. set. Pen. Color(c 2); Std. Draw. filled. Square(. 25, . 1); Std. Draw. set. Pen. Color(c 2); Std. Draw. filled. Square(. 75, . 2); Std. Draw. set. Pen. Color(c 1); Std. Draw. filled. Square(. 75, . 1); first color second color first square second square } } 18

Monochrome Luminance Monochrome luminance. Effective brightness of a color. NTSC formula. Y = 0. 299 r + 0. 587 g + 0. 114 b. import java. awt. Color; public class Luminance { public static double lum(Color c) { int r = c. get. Red(); int g = c. get. Green(); int b = c. get. Blue(); return. 299*r +. 587*g +. 114*b; } } 19

Color Compatibility Q. Which font colors will be most readable with which background colors on computer monitors and cell phone screens? A. Rule of thumb: difference in luminance should be 128. 256 208 105 47 28 14 public static boolean compatible(Color a, Color b) { return Math. abs(lum(a) - lum(b)) >= 128. 0; } 20

Grayscale. When all three R, G, and B values are the same, resulting color is on grayscale from 0 (black) to 255 (white). Convert to grayscale. Use luminance to determine value. public static Color to. Gray(Color c) { int y = (int) Math. round(lum(c)); Color gray = new Color(y, y, y); return gray; } round double to nearest int Bottom line. We are writing programs that manipulate color. 21

Picture Data Type (0, 0) j Raster graphics. Basis for image processing. Set of values. 2 D array of Color objects (pixels). i API. 22

Image Processing: Grayscale Filter Goal. Convert color image to grayscale according to luminance formula. import java. awt. Color; public class Grayscale { public static void main(String[] args) { Picture pic = new Picture(args[0]); for (int i = 0; i < pic. width(); i++) { for (int j = 0; j < pic. height(); j++) { Color color = pic. get(i, j); Color gray = Luminance. to. Gray(color); pic. set(i, j, gray); } } pic. show(); } } 23

Image Processing: Grayscale Filter Goal. Convert color image to grayscale according to luminance formula. mandrill. jpg % java Grayscale mandrill. jpg 24

• Horton got this far before Exam 2 in Spring 2008. • For exam 2, no need to look at slides after this. • Slides after this point will be covered after Exam 2. 25

Image Processing: Scaling Filter Goal. Shrink or enlarge an image to desired size. Downscaling. To shrink, delete half the rows and columns. Upscaling. To enlarge, replace each pixel by 4 copies. 26

Image Processing: Scaling Filter Goal. Shrink or enlarge an image to desired size. Uniform strategy. To convert from ws-by-hs to wt -by-ht : Scale row index by ws / wt. Scale column index by hs / ht. Set color of pixel (i, j) in target image to color of pixel (i ws / wt , j hs / ht ) in source image. n n n j hs / ht j ? i ws / wt source image (ws-by-hs) i target image (wt-by-ht) 27

Image Processing: Scaling Filter import java. awt. Color; public class Scale { public static void main(String args[]) { String filename = args[0]; int w = Integer. parse. Int(args[1]); int h = Integer. parse. Int(args[2]); Picture source = new Picture(filename); Picture target = new Picture(w, h); for (int ti = 0; ti < w; ti++) { for (int tj = 0; tj < h; tj++) { int si = ti * source. width() / w; int sj = tj * source. height() / h; Color color = source. get(si, sj); target. set(ti, tj, color); } } source. show(); target. show(); } } 28

Image Processing: Scaling Filter Scaling filter. Creates two Picture objects and two windows. mandrill. jpg % java Scale 400 200 mandrill. jpg 29

More Image Processing Effects (See book and book-site) RGB color separation swirl filter wave filter glass filter Sobel edge detection 30

Objects and Reference Types: Important Issues • See textbook: pp. 352 -357 31

Important Issues about Objects and Reference Types Study textbook: pages 352 -357 References are not objects! Aliases Comparing objects. Don’t use ==. Use. equals() Orphan objects, Memory Management 32

OOP Context for Color Possible memory representation. D 0 D 1 D 2 D 3 D 4 D 5 D 6 D 7 D 8 255 0 0 0 105 105 magenta A 0 B 0 D 6 gray memory address ("pointer") Object reference is analogous to variable name. We can manipulate the value that it holds. We can pass it to (or return it from) a method. n n 33

OOP Context Reference. Variable that stores the name of a thing. Thing Name Web page www. princeton. edu Bank account 45 -234 -23310076 Word of TOY memory 1 C Byte of computer memory 00 FACADE Home 35 Olden Street Some consequences. Assignment statements copy references (not objects). The == operator tests if two references refer to same object. Pass copies of references (not objects) to functions. – efficient since no copying of data – function can change the object n n n 34

References René Magritte. "This is not a pipe. " Java. This is not a color. (Where “this” means c or sienna below. ) Color sienna = new Color(160, 82, Color c = sienna. darker(); 45); OOP. Natural vehicle for studying abstract models of the real world. 35

Reference variables and equality Remember arrays? Can’t use == to see if two have the same content. Objects. Same thing! Never use == if you want to know if they have the same content. Use instance method equals(). All Java classes should provide a working version of equals() that takes a 2 nd object as an argument. String s 1 = new String("hello”); String s 2 = new String("hello”); System. out. println( s 1. equals(s 2) ); true System. out. println( s 1==s 2 ); false System. out. println( s 1==s 1 ); true String s 3 = s 1; System. out. println( s 1==s 3 ); true 36

Some things can’t be changed: Color objects, for example Immutability. Can't change a Color object's value once created. no relevant methods in Color API Consequence. Don't need to worry about aliases. Color a = new Color(160, 82, Color b = a; a = new Color(0, 0, 0); 45); makes a point to a different Color, but does not change b 37

Java objects: Some are Immutable, Some are Not Immutability. Can't change a Color object's value once created. no relevant methods in Color API We can create a new color from an old one. We can change the Color object the reference points to. The String class is immutable too. Mutability. Can change a Picture object's value. Color red = new Color(255, 0, pic. set(0, 3, red); 0); D 0 D 4 D 8 Java has class String. Buffer that is like String but mutable. It has an append() method, for example. DC 38
![Code Example public static void main (String[] args) { String s 1 = "Defined Code Example public static void main (String[] args) { String s 1 = "Defined](http://slidetodoc.com/presentation_image_h/2a5486b86659ab2b1577d93829d74d73/image-39.jpg)
Code Example public static void main (String[] args) { String s 1 = "Defined in main. "; change. String(s 1); System. out. println("String obj is now: " + s 1); // see? reference still points to original object String. Buffer sb 1 = new String. Buffer("Defined in main. "); change. String. Buffer(sb 1); System. out. println("String. Buffer obj is now: " + sb 1); // see? object pointed to has be changed! } public static void change. String(String s) { s = "Changed in method"; // change is only local } public static void change. String. Buffer(String. Buffer sb) { sb. append(" -- Changed in method"); } 39

Conclusion from Example Arguments that are object-references: §Code inside a method can change an argument passed to it. Only if that argument allows itself to be changed (i. e. is mutable). §Cannot make the object-reference point to a new object. In other words, inside the method: The thing “pointed to” can be changed. The “pointer” cannot be changed. This rule is same as for arrays! 40

OOP Summary Object. Holds a data type value; variable name refers to object. In Java, programs manipulate references to objects. Exception: primitive types, e. g. , boolean, int, double. Reference types: String, Picture, Color, arrays, everything else. n n Bottom line. We wrote programs that manipulate colors, pictures, and strings. Next. We'll write programs that manipulate our own abstractions. 41

Extra Slides
![Spectrum import java. awt. Color; public class Spectrum { public static void main(String[] args) Spectrum import java. awt. Color; public class Spectrum { public static void main(String[] args)](http://slidetodoc.com/presentation_image_h/2a5486b86659ab2b1577d93829d74d73/image-43.jpg)
Spectrum import java. awt. Color; public class Spectrum { public static void main(String[] args) { int N = Integer. parse. Int(args[0]); Picture pic = new Picture(N, N); for (int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { int r = (i * 256) / N; int g = 128; int b = (j * 256) / N; Color c = new Color(r, g, b); pic. set(i, j, c); } } pic. show(); pic. save("spectrum. png"); } } 43

Java Function Involving Colors We can write Java functions that manipulate colors. Ex: return convex combination of two colors. n import java. awt. Color; public class Color. Combiner { public static Color combine(Color c 1, Color c 2, int r = (int) (beta*c 1. get. Red() + (1 -beta) int g = (int) (beta*c 1. get. Green() + (1 -beta) int b = (int) (beta*c 1. get. Blue() + (1 -beta) return new Color(r, g, b); } public static void main(String args[]) { Color c 1 = new Color(127, 255); Color c 2 = new Color( 0, 127); Color c 3 = combine(c 1, c 2, 0. 15); System. out. println("c 3 = " + c 3); } } % java Color. Combiner double beta) { * c 2. get. Red()); * c 2. get. Green()); * c 2. get. Blue()); c 3 = java. awt. Color[r=19, g=146, b=146] 44

Color Separation import java. awt. Color; public class Color. Separation { public static void main(String args[]) { Picture pic = new Picture(args[0]); int width = pic. width(); int height = pic. height(); Picture R = new Picture(width, height); Picture G = new Picture(width, height); Picture B = new Picture(width, height); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { Color c = pic. get(i, j); int r = c. get. Red(); int g = c. get. Green(); int b = c. get. Blue(); R. set(i, j, new Color(r, 0, 0)); G. set(i, j, new Color(0, g, 0)); B. set(i, j, new Color(0, 0, b)); } } R. show(); G. show(); B. show(); } } 45

Color Separation Color. Separation. java. Creates three Picture objects and windows. 46

Image Processing: Swirl Filter Swirl. java. Creates two Picture objects and windows. 47

Image Processing: Swirl Filter Goal. Create swirl special effect by setting color of output pixel (i, j) to color of some other input pixel (ii, jj). double i 0 = 0. 5 * width; double j 0 = 0. 5 * height; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { double di = i - i 0; double dj = j - j 0; double r = Math. sqrt(di*di +dj*dj); double a = Math. PI / 256 * r; int ii = (int)(-di*Math. cos(a) + dj*Math. sin(a) + i 0); int jj = (int)( di*Math. sin(a) + dj*Math. cos(a) + j 0); if (ii >= 0 && ii < width && jj >= 0 && jj < height) pic 2. set(i, j, pic 1. get(ii, jj)); } } 48

Memory Management Value types. Allocate memory when variable is declared. Can reclaim memory when variable goes out of scope. n n Reference types. Allocate memory when object is created with new. Can reclaim memory when last reference goes out of scope. Significantly more challenging if several references to same object. n n n Garbage collector. System automatically reclaims memory; programmer relieved of tedious and error-prone activity. 49
- Slides: 49