ࡱ> QSP` (bjbjss .@ ddddxD(f  (!(!(!(!(!(!($*hn,jE( E(Z(''' (' (''' `!WJd$'(p(0(',o'j,','0 ' E(E(' ( @$@ String Class in Java A variable in Java can store one of two things: 1) a primitive value 2) a reference to an object Thus in Java, when you declare an object reference, such as String name; you are NOT creating a String object. (A reference is a similar to a pointer. It refers to a place in memory. But in Java, you don't get explicit control over memory addresses.) In order to actually create a new object, you must instantiate one. In Java, this means calling a constructor using the new operator. We discussed this in the previous lecture with the GiftCard class. A constructor is a method that every class must have. Its job is to create and initialize an object. Many classes (like the GiftCard class) have more than one. Here is an example of a call to the constructor in the String class: String name = new String("Julia Stiles"); All calls to constructors are of the form new (); Often times, constructors are overloaded. This means there are multiple constructors, each of which takes in different parameters. You must choose the constructor appropriate to create the object that you want. In this example, the standard String class constructor takes in a String object. In this example, that object is a String literal. Once you have created an object, you can mutate (change) that specific object by calling methods on that object. All methods that are called on specific objects are instance methods. (In a sentence, the term static means "belongs to the class" and the term instance means "belongs to the object.") Before we move on, one observation about the String class must be made. No methods in the String class actually change/modify an object!!! However, in many other classes, methods do have that ability. In the String class, any method that appears to be changing an object actually creates a new object separate from the original that reflects some particular change compared to the old object. Here is an example of a method call on the object we just created: name.toLowerCase(); What this will do is return a new String object similar to name except that all of its uppercase letters are changed to their lowercase equivalents. For example, if I executed the following line of code String name2 = name.toLowerCase(); Our picture would look like the following: name ----------------( [ Julia Stiles ] name2 -----------------( [ julia stiles ] Also, something else that is "hidden" from the user with Strings is the call of the constructor. The following line of code is perfectly valid: String name3 = "Anne Hathaway"; It is misleading because one MIGHT think that Strings work like primitives and that name3 IS the object itself. But, this code is "automatically changed" to be interpreted as follows: String name3 = new String("Anne Hathaway"); Furthermore, since Strings are references, the following line of code is also deceiving: name3 = name2; Here's what the REAL picture looks like: name ----------------( [ Julia Stiles ] name2 -----------------( [ julia stiles ] (------ name3 [Anne Hathaway] Since no String reference points to the String object storing "Anne Hathaway", this object will get "garbage collected" away. This means the memory for this object will get freed eventually so it can be used for other things. Some Methods in the String Class // Constructor String(String str); // Returns the character stored at index, using a 0 based // indexing system. char charAt(int index); // Returns a negative integer if the current object comes // lexicographically (by ascii value) before str, returns 0 // if the two objects are equal, and returns a positive // integer if the current object comes after str. int compareTo(String str); // Returns the concatenation of the current string and str // in a new String object. String concat(String str); // Returns true if and only if the contents of the current // object and str are identical. boolean equals(String str); // Works the same as equals except differences in the case // of letters is ignored. boolean equalsIgnoreCase(String str); // Returns the length of the current object. int length(); // Returns a new object that is the same as the current // object except with each occurrence of oldChar replaced // with newChar. String replace(char oldChar, char newChar); String Example: concat, replace, substring public class StringTest { public static void main(String[] args) { String test1=new String("Happy Birthday"); String test2, test3, test4; test2 = test1.concat(" Trisha!"); System.out.println("test1 = "+test1); System.out.println("test2 = "+test2); test3 = test1.replace('H', 'M'); test3 = test3.replace('a', 'e'); test3 = test3.replace('p', 'r'); System.out.println("test1 = "+test1); System.out.println("test3 = "+test3); test4 = test2.substring(11, 20); System.out.println("test2 = "+test2); System.out.println("test4 = "+test4); } } Output: test1 = Happy Birthday test2 = Happy Birthday Trisha! test1 = Happy Birthday test3 = Merry Birthdey test2 = Happy Birthday Trisha! test4 = day Trish String Example: length, charAt The following segment of code reads in a string from the user and then prints out all the letters in the string that are lowercase: Scanner stdin = new Scanner(System.in); System.out.println("Enter a word."); String word = stdin.next(); for (int i=0; i= 'a' && temp <= 'z') System.out.print(temp); } There are a couple key things to notice here: 1) length is a method and thus must have parentheses following it. 2) You can NOT use brackets to index into a string, you must make a call to the charAt method. This method does NOT allow you to CHANGE a character in a given string. Thus, it is ILLEGAL to do the following: word.charAt(2) = 'a'; This is because the left-hand side of an assignment statement MUST BE a variable. A method call is NOT a variable. Class Libraries and Packages There are many, prewritten Java classes for you to use, just like the String class. Groups of these classes that are related are put into packages. For example, the String class is included in the java.lang package. Normally, when you use a prewritten java class, you must import the corresponding class. (This is essentially the same as an #include in C.) However, the java.lang package is automatically included to use for every java program. That is why no import statement appears in the code we just looked at. However, let's say for example that you wanted to create a Random object, which will help you generate random numbers. This class appears in the java.util package. In order to use this class you would have to include one of the two following statements in your code: import java.util.*; OR import java.util.Random; The first statement imports the whole java.util package which contains the Random class AND other classes, whereas the second statement JUST imports the Random class itself. The general rule of thumb that I use is if I am only using one class from a package, I will only import that class. Otherwise I will import the package. (I believe your program will be more efficient the less unnecessary stuff you import.) The Random Class Here are some commonly used methods in the Random class: Random(); //constructor float nextFloat(); double nextDouble(); int nextInt(); For most programs you need to generate random numbers, creating a Random object and making calls to the three methods listed above should be sufficient. Generally in most programs you only want to create one instance of a Random object: Random gen = new Random(); Once you have done this, for the rest of your program you can simply call the nextFloat() or nextInt() method on the gen object. Each call will return a random float in between 0 and 1 or a random int in between -231 and 231 - 1. If you need to generate random numbers within some method, you can either create a Random object in that method OR you can simply pass a random number generator in as a parameter to that method. Here's a segment of code which simulates rolling two dice: Random r = new Random(); int roll1 = Math.abs(r.nextInt())%6 + 1; int roll2 = Math.abs(r.nextInt())%6 + 1; System.out.println("You rolled "+roll1+" and "+roll2); u ? Z y % ' X u !JN*?@ij} ܾܾܕhO(5CJ$\aJ$ jh/h/5CJ aJ  jhUh/5CJ aJ h/5CJ aJ hW56CJ \]h?h5CJ \h/5CJ \hW5CJ \hW5CJ$\h/5CJ$\7FG\xyv w @ A & ' Q R & %&$a$$a$(&  )*R}~/0$a$gd/$a$op  &'6JK)a$a$gdO($a$gd/$a$ %&67!~DR0n -nru$$$%\%~%&&&&&&''(((۱ҨҨҚҚh?h5CJ OJQJ\hW5CJ OJQJ\hW5CJ H*OJQJ\hW5CJ$\hO(5CJ OJQJ\^JhO(5CJ$\hF 5CJ \hW5CJ \hO(5CJ \hO(hW5CJ$\aJ$hO(hO(5CJ$\aJ$.!"]~DRS/0JKugdO($a$gdO($a$uv67Z}<dilnow gdO( ,-BC^noq$a$$a$gdO($a$gdO(q!!""""""""##s$t$u$$$$$$$%%%%%$a$$a$%&&''''(((E(n(($a$ ,1h/ =!"#$% @@@ NormalCJ_HaJmH sH tH DA@D Default Paragraph FontVi@V  Table Normal :V 44 la (k@(No List @FG\xyvw@A&'QR&%&  ) * R } ~   / 0   o p       & ' 6 J K )a!"]~DRS/0JKuv67Z}<dilnow ,-BC^noqstu   E n 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@0@000000000000000000000000000000000000000000000000) * R }  n   E j000j00j00 0j00j00j00 @0j00 j00j000j0  h0 h0 0 0 (&u q%((8@0(  B S  ? OLE_LINK1 5 08n s D G   kn~DG=Gmq"(>P%+ !$%&*+,7;<QYZ[bhU^ &/  irx  ( 0 1 : E H Q Y Z c n JK_`9@* . l s  6 =   kn~DG06LR#AOdr )>Q EI`b>Eis    E H n 3333333333333333333333333333333333333333333333333333333333333 Vmz~  F O('fQ?hW/@ Q`  @UnknownGz Times New Roman5Symbol3& z Arial;Wingdings?5 z Courier New3z Times"qhF5FF8;;!24 2QHX)??h2Creating Objectsdmarino Arup GuhaOh+'0   @ L X dpxCreating ObjectsdmarinoNormal Arup Guha7Microsoft Office Word@P@e@Rĸ@\{WJ՜.+,0 hp   University of Central Florida;  Creating Objects Title  "#$%&'(*+,-./0123456789:;<=>?ABCDEFGIJKLMNORRoot Entry F/WJTData !1Table),WordDocument.@SummaryInformation(@DocumentSummaryInformation8HCompObjq  FMicrosoft Office Word Document MSWordDocWord.Document.89q