Objects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal
Lesson Goals Understand objects and classes Understand Encapsulation Learn about additional Java classes The Random class The String class The StringBuilder class The File Class The DecimalFormat class 2
What is an Object? An object has characteristics or attributes. An object also has behaviors The attributes are the data associated with an object The behaviors are the methods used to manipulate the objects We ve already seen and made a bit of use of some objects including: arrays strings Object oriented programming is all about manipulating objects to perform tasks this matches the way we really think about things 3
Some Examples Objects Shoe A remote control A computer mouse or keyboard Non-objects Blue Fast Rough Interesting Return Digest Many of the non-objects are either attributes or methods of the object 4
Some Common Characteristics of Objects An object is made of tangible material (the pen is made of plastic, metal, ink). An object holds together as a single whole (the whole pen, not a fog). An object has properties (the color of the pen, where it is, how thick it writes...). An object can do things and can have things done to it. 5
Identifying Objects An object has identity (each object is a distinct individual). An object has state (it has various properties, which might change). An object has behavior (it can do things and can have things done to it). 6
A Simple Example Is the tube of tennis balls an object? Yes. It has identity (my tube of balls is different than yours), it has states (opened, unopened), properties (brand name, location), and behavior (although not much). Is each tennis ball an object? Yes. It is OK for objects to be part of other objects. Although each ball has nearly the same state and behavior as the others, each has its own identity. Could the top two balls be considered a single object? Not ordinarily. Each has its own identity independent of the other. If they were joined together with a stick you might consider them as one object. Is the color of the balls an object? No. It is a property of each ball. Is your understanding of tennis balls an object? Probably not, although it is unclear what it is. Perhaps it is a property of the object called "your brain." 7
Encapsulation Encapsulation is a computer language feature that packages attributes and behaviors into a single unit. The data and the methods comprise a single entity 8
Object Oriented Programming In object-oriented programming, the programmer uses a programming language (such as Java) to describe various objects. When the program is run (after being compiled) the objects are created (out of main storage) and they start "doing things" by running their methods. The methods must execute in the correct order. For an application, the first method to run is the method named main(). There should be only one method named main() in an application. In a small application, main() might do by itself all the computation that needs to be done. In a larger application, main() will create objects and use their methods. 9
Classes A class is a template, or blueprint from which objects are created A programmer may define a class using Java, or may use predefined classes that come in class libraries. - We ve already done that!!! A class is merely a plan for a possible object. It does not by itself create any objects. When a programmer wants to create an object the new operator is used with the name of the class. Creating an object is called instantiation. 10
An Example The Circle Class Is Instantiated (1) double radius; class Circle double area() { return πr 2 } double circumference() { return 2πr } three Circle objects radius 5.6; double area() double circumference() { radius 19.2; double area() double circumference() { radius 3.4; double area() double circumference() { 11
An Example The Circle Class Is Instantiated (2) Circle ovalguy; ovalguy = new Circle(5.6); or Circle ovalguy = new Circle(5.6); Remember- the new does the instantiation Until then all you ve created is a reference variable 12
Java Libraries and Packages Packages are large files that contain multiple classes Packages are nothing more than logical groupings of classes You can import a single class or an entire package Importing an entire package does not increase the size of the executable code, which only includes those classes actually used We ve done this already for a few months with the Scanner class: import java.packagename.classname import java.packagename.* import java.util.* 13
The Random class(1) The Random class is another class that is imported with the import java.util.* It has a many more methods and is therefore more useful than the Math.random() method (even though that basic Math package did not have to be imported Remember how we achieved the ability to read input from the screen: Scanner keyboard = new Scanner(System.in); Then we had a keyboard reader that could take advantage of all the methods in the class: number = keyboard.nextint(); dnumber = keyboard.nextdouble(); 14
The Random class(2) So let create a new object called randy from the class Random Random randy = new Random(); // note that there are no data attributes, also, that randy is a reference variable that now has a value. Then we can use the methods of Random: number = randy.nextint(n); // returns an integer greater than or equal to zero but less than n (where n is an integer) In general the format is: referencetoobject.method 15
The Random class(3) Method & Description boolean nextboolean() This method returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence. void nextbytes(byte[] bytes) This method generates random bytes and places them into a user-supplied byte array. double nextdouble() This method returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence. float nextfloat() This method returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence. double nextgaussian() This method returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence. int nextint() This method returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. int nextint(int n) This method returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. long nextlong() This method returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence. void setseed(long seed) This method sets the seed of this random number generator using a single long seed. 16
The Random class(4) An example with dice Random die = new Random(); int dice = (die.nextint(6)+1) + (die.nextint(6)+1); Those two lines would give us the sum of the two dice rolled You could create a coin object and then flip it. 17
The java.lang package This package is imported automatically into every application, so you don t need to use an import statement The java.lang package includes many useful classes Math class (discussed previously and not to be confused with the Random class) String class very useful class within java 18
The String Class The String class allows you to create string objects a String object is not a data type a String variable is a reference to a string object An example: String mydog = new String( Fido ); Because String objects are so common there is a shortcut used to initialize or assign an reference value to a String object: String mydog = Fido ; Remember this assigns the address of the string literal Fido to the reference mydog 19
The String Class (2) There are many methods that are available on a String object int length() returns the String length: mydog.length() returns 4 An empty String has no characters and length 0 char charat(int i) returns the character at position i (remember we start counting from 0): mydog.charat(2) = d String next() returns a reference to the next input string i.e. keyboard.next() skips whitespaces and returns the next string of characters 20
String Concatenation Concatenation is the process of joining or linking strings together The operator is + We ve already seen concatenation: System.out.println( A boy who is +age + is a man ); When you concatenate you create a new reference address String s = Sam String t = Thomas String w = s + +t = Sam Thomas w.length = 10 21
Strings and Characters - Review A + B = 131 (integer) A + B = AB (String) A + B = AB (String) + A + B = AB (String) A gets cast to string A + B + = 131 (String) 3 + 4 + = 7 (String) + 3 + 4 = 34 (String) Key is that without parentheses we are reading left to right 22
String Operations String touppercase() converts a string from lower to upper case String s1 = lower String s2 = s1.touppercase(); System.out.println(s1 + +s2); The output is: lower LOWER Note: s1 is not capitalized.; the method returns a new String reference that s2 refers to All java String operations can be found at: http://www.tutorialspoint.com/java/java_strings.htm There is also a new document called Class String Documentation in the Reference material area 23
String Operations substring (1) There are two versions of substring substring( int from ) substring( int from, int to ) Create a new object that contains the characters of the method's string from the index to the end of the string. Create a new object that contains the characters of the method's string from the index to index to-1. 24
String Operations substring (2) Line of code: String line = "buttercup" ; String a = line.substring( 0 ); String b = line.substring( 6 ); String c = line.substring( 9 ); String d = line.substring( line.length() ); String e = line.substring( line.length()+1 ); String f = line.substring( -1 ); New String buttercup buttercup (a new String is created, containing all the characters of the original) cup (an empty string is created) (an empty string is created) EXCEPTION EXCEPTION 25
String Operations substring (3) Line of code: String line = "buttercup" ; New String "buttercup" String a = line.substring( 0, 6 ); "butter" String b = line.substring( 6, 9 ); String c = line.substring( 0, 1 ); "cup" "b" String d = line.substring( 0, 0 ); "" String e = line.substring( 5, 5 ); "" String f = line.substring( 4, line.length()+1 ); EXCEPTION 26
String Operations An example Write a program that encrypts a message using the Caesar Cypher. The program accepts one line of text and a character shift value. Eliminate all non characters (a-z) and print the result as all capitals. See CaesarCipher 27
More on Strings and String Methods (1) String encrypt(string msg, int shift) really is accepting a String reference, not the string itself Strings are immutable You can change the value in the reference pointer, but not the string itself String s = Big ; s = s.tolowercase(); s Big big 28
More on Strings and String Methods (2) Be careful with == and strings. you are comparing references, not strings themselves use boolean equals(str1) to compare 2 strings strx.equals(str1) In the example: String s = new String( ABC ); String t = new String( ABC ); s ==t is not true s.equals(t) is true 29
The Null Value and Strings null is a special value that means "no object." Your program should set a reference variable to null when it is not referring to any object. Programs often set variables to null when they are declared: String a = null; class NullDemo1 { public static void main (String[] arg) { String a = "Random Jottings"; String b = null; String c = ""; if ( a!= null ) System.out.println( a ); if ( b!= null ) System.out.println( b ); if ( c!= null ) System.out.println( c ); } } 30
The nextline() Method (1) nextline() returns the remaining information on the current line, and returns the information that was skipped System.out.print( Enter message on one line: ); String message = keyboard.nextline(); System.out.print( Enter an integer in the range 0-25 ); int shift = keyboard.nextint(); If the inputs are Cato 8 then message points to Cato and shift gets the value 8. 31
The nextline() Method (2) However, if you reverse the process: System.out.print( Enter an integer in the range 0-25 ); int shift = keyboard.nextint(); System.out.print( Enter message on one line: ); String message = keyboard.nextline(); The Results are different: In the second case once you read the 8 the Scanner still hasn t moved to the next line The nextline() then see nothing prior to the line return and returns an empty string 32
The StringBuilder Class (1) StringBuilder is a different class than String, even though they do many of the same things With the StringBuilder Class you do not create a new object with each alteration of the strings The StringBuilder class may improve performance for concatenation and modification The String class is preferable and more efficient for read-only strings While there are some similar methods, remember that the type of object determines which method will be executed and that some overloaded method may execute differently A complete list of StringBuilder Methods can be found at: http://docs.oracle.com/javase/7/docs/api/java/lang/stringbuilder.html Also uploaded into references 33
The StringBuilder Class (2) To create a StringBuilder object: StringBuilder sb = newstringbuilder(); //initial capacity is 16 characters StringBuilder sb = newstringbuilder(50); //initial capacity is 50 characters StringBuilder sb = newstringbuilder( Hello ); //initializes sb to Hello The capacity of a StringBuilder object expands automatically 34
The StringBuilder Class (3) How the equals method works for StringBuilder vs. String String s = new String( Monkey Business ); String t = new String( Monkey Business ); System.out.println(s.equals(t)); In the case above true is printed out StringBuilder s = new StringBuilder( Monkey Business ); StringBuilder t = new StringBuilder( Monkey Business ); System.out.println(s.equals(t)); In the case above false is printed out 35
The Mysterious String [] args String [] args is simply an array of strings It allows you to send inputs to the main method via the command line See the TestMain application 36
Files A File is a collection of data saved under a single name Files can be structured or free text Java creates File objects Once a File is instantiated you can read or write from the file This is very convenient when testing programs, since you can use the same data over and over again 37
Input and Output There are many data sources and destinations that can be used 38
Processing Streams A processing stream operates on the data supplied by another stream. Often a processing stream acts as a buffer for the data coming from another stream. Character streams are intended exclusively for character data. Byte streams are intended for general purpose input and output. A buffer is a block of main memory used as a work area. For example, disks usually deliver data in blocks of 512 bytes, no matter how few bytes a program has asked for. Usually the blocks of data are buffered and delivered from the buffer to the program in the amount the program asked for. 39
Using Files in java Programs (1) You must include the following statement before the class statement import java.io.* You must also include the statement throws IOException after the parentheses of any method that uses File class methods: public static void main (String [] args) throws IOException You must also create a file in the program using the new parameter File inputfile = new File( filename ); If the filename isn t in the same directory as the class file you must use the full path name Finally create a Scanner for the new input file Scanner input = new Scanner(inputFile); Once this is done you can use the same input functions as you have used previously See TestFile1 program 40
Using Files in java Programs (2) Using an output file involves almost the same process File outputfile = new File(filename); PrintWriter output = new PrintWriter(outputFile); Now you can use output to write to the file i.e. output.println((message +intvar + is whatever ); See EncryptFile program to demonstrate all these principles 41
The DecimalFormat Class (1) Allows you to easily format decimal number by pattern pattern looks like: 0.### The # tells you how many places to display Need to create a separate formatter for each pattern Use import java.text.* to use the DecimalFormat class 42
The DecimalFormat Class (2) DecimalFormat myformat = new DecimalFormat( 0o.### ); double x = 123.456789; double y =.9876 System.out.println(myformat.format(x) + + myformat.format (y)); myformat.applypattern( ##.## ); // changes the pattern System.out.println(myformat.format (x) + + myformat.format (y)); output: 123.457 00.988 123.46 0.99 Note: Decimal Format always rounds (up or down) 43
The DecimalFormat Class (3) value of double format pattern output string 123.456 ###.###" "123.456" 123.456 ###.#" "123.5" 123.456 ###" "123" 89.008 000.###" "089.008" 89.008 "0000.0000" "0089.0080" 89.008 "0.00" "89.01" 89.008 "0." "89." -123.456 "000.000" "-123.456" -123.456 "000.0" "-123.5" -89.008 "0.00" "-89.01" -89.008 "0." "-89." -1.1 "0000.0000" -0001.1000" -89.008 " 0.0" "- 89.0" 44
Programming Exercises Class (1) Exercise 2. Uppercase Conversion Write a program that accepts a String and displays another String composed of the characters of the first String but with all lowercase letters capitalized. Any non-alphabetical letters, such as punctuation, should be left unchanged. For example, the string When Homer blew up the nuclear plant, he yelled #!#!#!& DOH &&####!!!! should become WHEN HOMER BLEW UP THE NUCLEAR PLANT, HE YELLED #!#!#!& DOH &&####!!!! 45
Programming Exercises Class (2) Exercise 8. Counting Words Write a method that accepts a string and returns the number of words in the string. For example, the string This sentence has too many words in it. has 8 words. 46
Programming Exercises Lab (1) Exercise 3. Random Strings Write a program that print 25 random strings of length 4 such that each string is composed of uppercase alphabetical characters. 47
Programming Exercises Lab (2) Exercise 12. College Transcript A text file stores the courses you have taken along with the corresponding grade (A,B,C, D, F) that you received in each course. The file might look like: Intro to Sociology Physics Experimental Psych o o o A B C Write a program that uses such a file to calculate a GPA. Print the GPA with two decimal places. 48