Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance

Slides:



Advertisements
Similar presentations
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Advertisements

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Wrappers: Java’s Wrapper Classes for the Primitives Types Steve Bossie.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming Strings Chapter 7.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
Fundamental Programming Structures in Java: Strings.
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
String Class in Java java.lang Class String java.lang.Object java.lang.String java.lang.Object We do not have to import the String class since it comes.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
The java.lang Package chapter 8 Java Certification Study Group February 2, 1998 Seth Ladd.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Strings Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts.
Working with string In java Four classes are provided to work with String:1) String 2)String Buffer 3)String Tokenizer 4)String Builder Note: An object.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 1 Sun Certified Java 1.4 Programmer Chapter 3 Notes Gary Lance
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Chapter 7: Characters, Strings, and the StringBuilder.
CHAPTER 9 Text Processing and More about Wrapper Classes Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
Geoff Holmes Date Math Weighted Distr Strings String methods Tokenizers System Examples Utility Classes (Chapter 17) import java.util.*;
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Strings Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
CONTENTS Wrapper Class Enumeration Garbage Collection Import static.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
Strings and ArrayLists April 23, 2012 ASFA AP CS.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
17-Feb-16 String and StringBuilder Part I: String.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
Lecture 5: java.lang.Math, java.lang.String and Characters Michael Hsu CSULA.
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 4 Mathematical Functions, Characters, and Strings 1.
String and StringBuffer classes
Chapter 4 Mathematical Functions, Characters, and Strings
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
EKT 472: Object Oriented Programming
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
The Language Package.
More About Objects and Methods
CS2011 Introduction to Programming I Strings
Outline Creating Objects The String Class The Random and Math Classes
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
Chapter 2: Java Fundamentals cont’d
In Java, strings are objects that belong to class java.lang.String .
Ch 5 : Mathematical Functions, Characters, and Strings
Presentation transcript:

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 2 Strings are Immutable What is all the fuss about? So what if String objects are immutable. Well, everytime an anonymous String object is created, is it using up memory that must wait for garbage collection to reclaim it. When you concatenate a String with another String, the old String object may be abandoned. Let’s consider a few examples

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 3 String Concatenation Example What is printed out, and how many String objects have been created in memory? How many String objects have no references to them? Create a class Practice, and put this code in main(). String m = “M”; m.concat(“i”); m.concat(“c”); m.concat(“r”); m += “o”; System.out.println(m);

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 4 String Concatenation Example Five String objects were created, and the location of only one is accessible by String variable “m”. String m = “M”;// Creates memory to hold “M”, stores ref in m m.concat(“i”);// Creates anonymous String object “mi” m.concat(“c”);// Creates anonymous String object “mic” m.concat(“r”);// Creates anonymous String object “micr” m += “o”;// Creates String object “Mo”, stores ref in m System.out.println(m);// Prints “mo”

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 5 String method concat concat public String concat(String str) –Concatenates the specified string to the end of this string. If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string. SO, if str refers to a String object that has at least one character, a new String object is created by this method. But we MUST assign this to a String variable if we want to access it. In the last example, we did not do this. New String objects were created, but the references to those Strings was never assigned to a variable. m.concat(“i”) does NOT change m, because String objects are immutable.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 6 String toUpperCase() toUpperCase public String toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale. Returns: the String, converted to uppercase. What is printed? How many Strings have been created, and how many are unreachable? String str = “abc” str.toUpperCase(); “abc”.toUpperCase(); System.out.println(str);

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 7 String toLowerCase() toUpperCase public String toUpperCase() Converts all of the characters in this String to lower case using the rules of the default locale. Returns: the String, converted to uppercase. What is printed? How many Strings have been created, and how many are unreachable? String str = “abc” str.toLowerCase(); “abc”.toLowerCase(); System.out.println(str);

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 8

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 9 String equals() equals public boolean equals(Object anObject) Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. Overrides: equals in class Object Parameters: anObject - the object to compare this String against. Returns: true if the String are equal; false otherwise.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 10 new String(“abc”) This is interesting. Note that an anonymous String “abc” is created, and that is used to instantiate another String. But what if a String identical to one being created already has a reference to it? Then a new String may be created, according to the text. I am not sure this is correct. Why? Because of the existence of the String method intern(). All String objects end up in the “String constant pool”. The constant pool may be searched to find a String object with the exact character sequence as the new String being created. But it will definitely be searched if the new String is created NOT by an constructor, but by the method intern().

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 11 String constant pool – not on exam interned Strings Interned strings avoid duplicate strings. There is only one copy of each String that has been interned, no matter how many references point to it. Since Strings are immutable, if two different methods "incidentally" use the same String, (even if they concocted the same String by totally independent means, e.g. one might use the string "sin" in the context of Moses and another in the context of trigonometry.) they can share a copy of the same string. The process of converting duplicated strings to shared ones is called interning. String.intern() gives you the address of the canonical master String. You can compare interned Strings with simple == (which compares pointers) instead of.equals which compares the characters of the String one by one. Because Strings are immutable, the intern process is free to further save space, for example, by not creating a separate string literal for "pot" when it exists as a substring of some other literal such as "hippopotamus" There there are two reasons for interning Strings: To save space, by removing String literal duplicates. To speed up String equality compares.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 12 Not on exam – but it is interesting. The only way to guarantee that two String objects refer to the same object in the String constant pool is to use the intern() method in String to create the duplicate. Clearly, this implies that there is no guarantee that two String objects that satisfy (s1.equals(s2) = = true) are really referring to the same String object in memory. I don’t believe this! See example, page 19.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 13 String length() length public int length() Returns the length of this string. Returns: the length of the sequence of characters represented by this object.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 14 Think of Strings as arrays, as arrays and Strings are zero-based. String str = “abcdefgh”; System.out.println(str.charAt(1));// returns ‘b’

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 15 Compare two Strings, but ignore case. String str = “abcdefgh”; String str2 = “AbCdEfG”; System.out.println( str2.equalsIgnoreCase(str) );

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 16

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 17

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 18

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 19 public class Practice { public static void main(String[] args){ String str = "Now is the time"; String str1 = str; String str2 = str.substring(4, 6);// "is" String str3 = str.substring(3,7);// " is " String str4 = str2.intern();// NOT ON EXAM System.out.println("str == str1 is " + (str == str1)); System.out.println("str.equals(str1) is " + str.equals(str1)); System.out.println("str2 == str3 is " + (str2 == str3)); System.out.println("str2.equals(str3) is " + str2.equals(str3)); str3 = str3.trim(); System.out.println("str2 == str3 is " + (str2 == str3)); System.out.println("str2.equals(str3) is " + str2.equals(str3)); System.out.println("str2 == str4 is " + (str2 == str4)); System.out.println("str2.equals(str4) is " + str2.equals(str4)); } Know the difference between == and equals. You will be tested on it. Also, make sure you know how both overloaded substring methods work!

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 20 java.lang.StringBuffer class A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code: x = "a" "c" is compiled to the equivalent of: x = new StringBuffer().append("a").append(4).append("c").toString() which creates a new string buffer (initially empty), appends the string representation of each operand to the string buffer in turn, and then converts the contents of the string buffer to a string. Overall, this avoids creating many temporary strings.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 21 StringBuffer There is one thing to keep in mind. There IS a difference between: String x = “a” + “b” + “c”; and String x = “a”; x += “b”; x += “c”; The first does not create temporary String objects. But the second one does.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 22 Overloading of insert() in StringBuffer class

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 23 Overloaded StringBuffer Constructors Note that you can create a StringBuffer object from a String. This means that you can use the methods of StringBuffer on Strings. The toString() method of StringBuffer can then convert the StringBuffer object back to a String.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 24 StringBuffer reverse() Reverses the characters in the StringBuffer object. TASK: Create a String, and then make another String with the characters reversed. How would you do this, using the StringBuffer class?

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 25 StringBuffer insert() StringBuffer sb = new StringBuffer("aefg"); sb.insert(1,"bcd"); System.out.println(sb); System.out.println( sb.reverse() );

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 26 Chained Methods Recall the append() example for String concatenation: x = new StringBuffer().append("a").append(4).append("c").toString() This is an example of chained methods. You are always to start from the left, and handle this one message at a time.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 27 java.lang.Math constants E and PI

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 28 Math.abs(): Absolute Value static double abs(double a) Returns the absolute value of a double value. static float abs(float a) Returns the absolute value of a float value. static int abs(int a) Returns the absolute value of an int value. static long abs(long a) Returns the absolute value of a long value.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 29 Math.floor() public static double floor(double a) Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer. Special cases: If the argument value is already equal to a mathematical integer, then the result is the same as the argument. If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. Parameters: a - a value. Returns: the largest (closest to positive infinity) floating-point value that is not greater than the argument and is equal to a mathematical integer <= x < 5.0

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 30 Math.ceil() public static double ceil(double a) Returns the smallest (closest to negative infinity) double value that is not less than the argument and is equal to a mathematical integer. Special cases: If the argument value is already equal to a mathematical integer, then the result is the same as the argument. If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. If the argument value is less than zero but greater than -1.0, then the result is negative zero. Note that the value of Math.ceil(x) is exactly the value of -Math.floor(-x). Parameters: a - a value. Returns: the smallest (closest to negative infinity) floating-point value that is not less than the argument and is equal to a mathematical integer < x <= 4.0

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 31 Math.max(), Math.min()

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 32 Math.random() public static double random() –Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range. Note the upper value is less than <= Math.random() < 1.0 TASK: Show the code that will generate random numbers that are between 1 and 50 for the lotto.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 33 Math.round() round public static long round(double a) Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. Math.round(1.5)  Math.floor(2.0)  2L Math.round(1.6)  Math.floor(2.1)  2L Math.round(-3.4)  Math.floor(-2.9)  -3L

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 34 Wrapper Classes Makes objects out of primitives Integer intObj = new Integer(5);// int Integer intObj2 = new Integer(“6”);// String Double dblObj = new Double(9.5); Boolean boolObj = new Boolean(true); Boolean boolObj2 = new Boolean(“false”); Long longObj = new Long(5); Long longObj2 = new Long(6L); Byte byteObj = new Byte( (byte)1 ); Character charObj = new Character(‘a’); Short shortObj = new Short( (short)45 );

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 35 valueOf() method Use the static valueOf() method to convert a String to a wrapper (eg, Integer). Holds for all wrapper classes except Character. Both throw NumberFormatException. Use either one, if base 10. Use valueOf() when other than base 10, since the Integer constructors do not take a parameter of the radix. It actually does this: new Integer( Integer.parseInt(s) ) Integer intObj = Integer.valueOf(“123”); Integer intObj2 = Integer.valueOf(“fff”, 16);// radix = base = 16

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 36 xxxValue() Allows you to get the primitive value that is wrapped in the object: Integer intObj = Integer.valueOf(“abc”, 16);// hex int value = intObj.intValue(); System.out.println(value); intObj = Integer.valueOf(“abc”, 15); // base 15 value = intObj.intValue(); System.out.println(value);

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 37 parseXXX() Very similar to valueOf(), except parseXXX returns the primitive (eg, int), and valueOf() returns the wrapper object (eg, Integer). int value = Integer.parseInt(“123”);// 123 value = Integer.parseInt(“123”, 16);// 291

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 38 End of Chapter 6