Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008)
|
|
- Norma Higgins
- 6 years ago
- Views:
Transcription
1 Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008) In previous chapters, methods were called with parameters that were primitive data types. This chapter discusses how to use object references as parameters. The class String is used in many examples. Chapter Topics: String literals The null value More about garbage The String class String concatenation Strings are immutable Some String methods o concat() o length() o trim() o substring() o tolowercase() o startswith() o charat() Cascading methods Students taking the computer science Advanced Placement examination are expected to be familiar with the String class. QUESTION 1: (Review:) What TWO things does the following statement do? String zeta = new String( "The last rose of summer." ); Used by permission. Page 1 of 38
2 A new String object is created, containing the characters between quote marks. A reference to the object is saved in the variable zeta. Easy way to Construct Strings String objects are very useful and are frequently used. To make life easier for programmers, Java has a short-cut way of creating a String object: String zeta = "The last rose of summer." ; This creates a String object containing the characters between quote marks. A String created in this short-cut way is called a String literal. Remember that if several statements in a program ask for literals containing the same characters, only one object will actually be constructed (see chapter 26). Other classes do not have short-cuts like this. Objects of most classes are constructed by using the new operator. QUESTION 2: Can a String reference be a parameter for a method? Used by permission. Page 2 of 38
3 Yes, a String reference is often a parameter. String References as Parameters Some methods require a parameter that is a reference to a String object. For example, The picture that shows how the method call works. (Both objects have many methods, but only the equals() method of one object is pictured.) The String object referred to by stringa has an equals() method. That method is called with a parameter, a reference to another String object, stringb. The method checks if both String objects contain identical sequences of characters, and if so, evaluates to true. Careful: The previous paragraph is correctly stated, but awkward. People often say "String" when they really mean "reference to a String". This is fine, but remember that a reference variable like stringa does not contain an object, but only a reference to an object. This may seem picky, but there is nothing quite as picky as a computer. Students who are not careful about this often run into problems. Used by permission. Page 3 of 38
4 QUESTION 3: (Review:) Examine the following snippet of code. Answer the questions using careful words (like the above on the right). String a; Point b; What is the data type of the variable a? What is the data type of the variable b? How many objects are there (so far)? Used by permission. Page 4 of 38
5 What is the data type of the variable a? o a is a reference to a String object. What is the data type of the variable b? o b is a reference to a Point object. How many objects are there (so far)? o So far, there are no objects, just variables that can reference objects, once there are some. The null Value A reference variable holds information about the location of an object. It does not hold the object itself. This code String a; Point b; declares two reference variables but does not construct any objects. The following constructs objects and puts references in the variables: a = "Elaine the fair" ; b = new Point( 23, 491 ); 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; Point b = null; QUESTION 4: (Thought Question:) Do you think that null can be assigned to reference variables of any type? Hint: How many types of nothing are there? Used by permission. Page 5 of 38
6 Yes. Null Assigned to any Reference Variable It would be awful if each class had its own special value to show that no object of that class was present. We need a universal value that means "nothing here". The value null works for this and can be assigned to any reference variable. In most programs, objects come and objects go, depending on the data and on what is being computed. (Think of a computer game, where monsters show up, and monsters get killed). A reference variable sometimes does and sometimes does not refer to an object, and can refer to different objects at different times. You need a way to say that a variable does not now refer to an object. You do this by assigning null to the variable. Inspect the code below. Variables a and c are initialized to object references. Variable b is initialized to null. QUESTION 5: What exactly is variable c initialized to? Consider: the absence of paper and a blank sheet of paper. Used by permission. Page 6 of 38
7 The code "" calls for a literal, which is a String object. Although the object exists, it contains no characters (since there are no characters inside ""). The reference variable c is initialized to a reference to this String object. This is most certainly a different value than null. The Empty String A String object that contains no characters is still an object. Such an object is called an empty string. It is similar to having a blank sheet of paper, versus having no paper at all. Overlooking this distinction is one of the classic confusions of computer programming. It will happen to you. It still happens to me. To prepare for future confusion, study this program, step-by-step: Used by permission. Page 7 of 38
8 The System.out.println() method expects a reference to a String object as a parameter. The example program tests that each variable contains a String reference before calling println() with it. (If println() gets a null parameter, it prints out "null" which would be OK. But some methods crash if they get a null parameter. Usually you should ensure that methods get the data they expect.) QUESTION 6: Examine the following code snippet: String alpha = new String("Red Rose") ; alpha = null;... Where is an object constructed? What becomes of that object? Used by permission. Page 8 of 38
9 String alpha = new String("Red Rose") ; alpha = null;... Where is an object constructed? In the first statement. What becomes of that object? It became garbage in the second statement. Garbage The first statement does two things: (1) a String object is created, containing the characters "Red Rose". Then, (2) a reference to that object is saved in the reference variable alpha. The second statement assigns the value null to alpha. When this happens, the reference to the object is lost. Since there is no reference to the object elsewhere, it is now garbage. The line through the box in the second statement symbolizes the null value. The object still exists in memory. The memory it consists of will eventually be recycled by the garbage collector and will be made available for new objects. Used by permission. Page 9 of 38
10 QUESTION 7: Examine this (slightly altered) snippet of code: String alpha = new String("Red Rose"); String beta = alpha; alpha = null; Where is an object created? 2. What happens in the second statement? 3. What becomes of that object? Used by permission. Page 10 of 38
11 String alpha = new String("Red Rose"); String beta = alpha; alpha = null; When was an object instantiated? In the first statement. What happenes in the second statement? The reference to the object is copied to beta. What becomes of that object? It remains "alive," because there is still a reference to it. Not Garbage Used by permission. Page 11 of 38
12 This time, the object does not become garbage. This is because in the second statement a reference to the object is saved in a second variable, beta. Now when, in the third statement, alpha is set to null, there is still a reference to the object. There can be many copies of the reference to an object. Only when there is no reference to an object anywhere does the object become garbage. QUESTION 8: (Review:) How can you determine what an object of a particular class can do? Used by permission. Page 12 of 38
13 The variables and methods of a class will be documented somewhere. Class String With a Java development environment such as such as Borland JBuilder or Symantec Café the documentation is in the environment (in the editor, put the cursor over a class name and push F1). If you downloaded Java from Sun Microsystems, you might have downloaded the documentation for it, also. Otherwise, use Google or other search engine. To find documentation for class String search for Java String. Here is a short version of the documentation for String. Used by permission. Page 13 of 38
14 The documentation first lists constructors. Then it describes the methods. For example, public String concat(string str); says that the method requires a String reference parameter the name of the method the method returns a reference to a new String object anywhere you have a String object, you can use this method public will be explained in greater detail in another chapter. QUESTION 9: Is the following code correct? String first = "Red " ; String last = "Rose" ; String name = first.concat( last ); You don't have to know what concat() does (yet); look at the documentation and see if all the types are correct. Used by permission. Page 14 of 38
15 Yes. The concat() Method The parts of the statement match the documentation correctly: String name = first.concat( last ); a String reference parameter the name of the method dot notation used to call an object's method the method returns a reference to a new String object The concat method performs String concatenation. A new String is constructed using the data from two other Strings. In the example, the first two Strings (referenced by first and last) supply the data that concat() uses to construct a third String (referenced by name.) String first = "Red " ; String last = "Rose" ; String name = first.concat( last ); The first two Strings are NOT changed by the action of concat(). A new String is constructed that contains the characters "Red Rose". Used by permission. Page 15 of 38
16 The picture shows the operation of the concat() method before the reference to the new object has been assigned to name. QUESTION 10: (Review:) Have you seen String concatenation before? Used by permission. Page 16 of 38
17 Yes: in output statements like this: System.out.println( "Result is:" + result ); The + operator is a short way of asking for concatenation. (If result is a number, it is first converted into characters before the concatenation is done.) Used by permission. Page 17 of 38
18 + Operat Here the + operator is used instead of using the concat() method: String first = "Red " ; String last = "Rose" ; String name = first + last ; String concatenation, done by concat() or by +, always constructs a new object based on data in other objects. Those objects are not altered at all. When the operands on either side of + are numbers, then + means "addition". If one or both of the operands is a String reference, then String concatenation is performed. When an operator such as + changes meaning depending on its arguments, it is said to be overloaded. QUESTION 11: Say that the following statement is added after the others: String reversed = last + first; Does it change first, last, or name? Used by permission. Page 18 of 38
19 No. It uses the data in last and in first to construct a new object. No objects are altered. Strings are Forever Java was designed after programmers had about 15 years of experience with object oriented programming. One of the lessons learned in those years is that it is safer to construct a new object rather than to modify an old one. (This is because many places in the program might refer to the old object, and it is hard to be sure that they will all work correctly when the object is changed.) Objects of some Java classes cannot be altered after construction. The class String is one of these. Sometimes immutable objects are called write-once objects. Once a String object has been constructed, the characters it contains will always be the same. None of its methods will change those characters, and there is no other way to change them. The characters can be used for various purposes (such as in constructing new String objects), and can be inspected. But never altered. Confusion Alert!! This is a place where it is important to distinguish between reference variables and their objects. A reference variable referring to a String can be altered (it can be made to point to a different String object.) The String object it refers to cannot be altered. QUESTION 12: Inspect the following code: String ring = "One ring to rule them all, " String find = "One ring to find them." ring = ring + find; Does the last statement violate the rule that Strings are immutable? Used by permission. Page 19 of 38
20 No. The String objects don't change. The reference variable ring is changed in the third statement to refer to a different String than originally. (Its original String becomes garbage, which is collected by the garbage collector.) The Length of a String The length of a string is the number of characters it contains, including space characters and punctuation. For example: An empty string has length zero. The length() method of a String returns its length: public int length(); The method takes no parameters, but the () is needed when it is used. QUESTION 13: Inspect the following code: String stringa = "Alphabet " ; String stringb = "Soup" ; String stringc = stringa + stringb; System.out.println( stringc.length() ) ; What does the code print? Used by permission. Page 20 of 38
21 13 Don't forget to count the space. The trim() Method Here is a line of the documentation for the String class. public String trim(); The trim() method of a String object creates a new String that is the same as the original except that any leading or trailing space is trimmed off (removed). QUESTION 14: Examine the following code: String userdata = " 745 "; String fixed; fixed = userdata.trim(); Has the trim() method been used correctly? How many objects have been created? Used by permission. Page 21 of 38
22 Has the trim() method been used correctly? How many objects have been created? 2 Yes trim() with Input data The trim() method creates a new String. The new String contains the same characters as the old one but has whitespace characters (blanks, tabs, and several other non-printing characters) removed from both ends (but not from the middle). So, for example, after the last statement String userdata = " 745 "; String fixed; fixed = userdata.trim(); the new String referenced by fixed will contain the characters "745" without any surrounding spaces. (Usage Note:) This method is often useful. Extraneous spaces on either end of user input is a common problem. QUESTION 15: Inspect the following: String dryden = " None but the brave deserves the fair. " ; System.out.println( " " + dryden.trim() + " " ); What is printed out? Used by permission. Page 22 of 38
23 None but the brave deserves the fair. charat() The charat(int index) method returns a single character at the specified index. If the index is negative, or greater than length()-1, an IndexOutOfBoundsException is thrown (and for now your program stops running). The return values are primitive char data, hence the values are delimited by single quotes, as in 'S'. String literals would be delimited by double quotes, as in "R". The value returned by charat(int index) is a char, not a String containing a single character. A char is a primitive data type, consisting of two bytes that encode a single character. It has no methods or other data. QUESTION 16: What is the output of the following fragment: String singlea = "A" ; String singleb = new String( "B" ); System.out.println( singlea.length() ); System.out.println( singlea.concat( singleb ) ); What is wrong with the following fragment: char onec = 'C' ; char oned = new char( 'B' ); System.out.println( onec.length() ); System.out.println( oned.concat( onec ) ); Used by permission. Page 23 of 38
24 String singlea = "A" ; String singleb = new String( "B" ); System.out.println( singlea.length() ); System.out.println( singlea.concat( singleb ) ); outputs: 1 AB The following char onec = 'C' ; char oned = new char( 'B' ); System.out.println( onec.length() ); System.out.println( oned.concat( onec ) ); will not even compile. Line two will not compile because a char is not an object, and so has no constructor. The remaining lines will not compile because a char primitive has no methods. Column Checker Here is a program that checks that every line of a text file has a space character in column 10. This might be used to verify the correct formatting of columnar data or of assembly language source programs. Used by permission. Page 24 of 38
25 The program is used with redirection (see Chapter 21): C:\>javac ColumnCheck.java C:\>java ColumnCheck < datafile.txt A better program would ask the user for several column numbers to check. QUESTION 17: Will the program crash if a line has fewer than 10 characters? Inspect the statement if ( line.length() > colnum && line.charat( colnum )!= ' ' ) System.out.println( counter + ":\t" + line ); How is the short-circuit nature of && used here? Used by permission. Page 25 of 38
26 if ( line.length() > colnum && line.charat( colnum )!= ' ' ) System.out.println( counter + ":\t" + line ); The short-circuit operation of && means that line.length() > colnum is tested first. If this result is false, then the next part of the condition is not tested (since the result of AND will be false regardless of its result). So line.charat( colnum ) is only performed when it is certain that the line contains a character at index colnum Substrings A substring of a string is a sequence of characters from the original string. The characters are in the same order as in the original string and no characters are skipped. For example, the following are all substrings of the string "applecart": apple cart pple e lecar You have previously seen (in chapter 9) the substring() method of String objects: public String substring(int beginindex ) This method creates a new substring that consists of the characters from character number beginindex to the end of the string. For example "applecart".substring(5) contains the characters "cart". Remember: character numbering starts with zero. The leftmost character of a string is character zero. The rightmost character is character length-1. QUESTION 18: What is printed by the following code: String source = "applecart"; String sub = source.substring(6); System.out.println( sub ); System.out.println( source ); Used by permission. Page 26 of 38
27 art applecart Tricky Rules The method public String substring(int beginindex ) creates a new string. The original string is not changed. There are two tricky rules: If beginindex is exactly equal to the length of the original string, a substring is created, but it contains no characters (it is an empty string) If beginindex is greather than the length of the original string, or a negative value, a IndexOutOfBoundsException is thrown (and for now, your program crashes). QUESTION 19: Decide on what string is formed by the following expressions: Used by permission. Page 27 of 38
28 Another substring() Here is another method of String objects: substring(int beginindex, int endindex) This method creates a new String containing characters from the original string starting at beginindex and ending at endindex-1. Warning: the character at endindex is not included. The length of the resulting substring is endindex-beginindex. QUESTION 20: Examine the following code: String stars = "*****" ; int j = 1; while ( j <= stars.length() ) { System.out.println( stars.substring(0,j) ); j = j+1; } Used by permission. Page 28 of 38
29 * ** *** **** ***** More Tricky Rules As with the other substring method, this one public String substring(int beginindex, int endindex ) creates a new string. The original string is not changed. There are some tricky rules. Essentially, the rules say that if the indexes make no sense, a IndexOutOfBoundsException is thrown. If beginindex is negative value, an IndexOutOfBoundsException is thrown. If beginindex is larger than endindex, an IndexOutOfBoundsException is thrown. If endindex is larger than the length, an IndexOutOfBoundsException is thrown. If beginindex equals endindex, and both are within range, then an empty string is returned. Usually, when an exception is thrown your program halts. Future chapters discuss how to deal with exceptions QUESTION 21: Decide on what string is formed by the following expressions: Used by permission. Page 29 of 38
30 Control Characters inside String Objects Recall that control characters are bit patterns that indicate such things as the end of a line or page separations. Other control characters represent the mechanical activities of old communications equipment. The characters that a String object contains can include control characters. For example, examine the following code: The sequence \n represents the control character that ends a line. This control character is embedded in the data of the strings. The object referenced by poem has two of them. The program writes to the monitor: Only to the wanderer comes Ever new this shock of beauty Used by permission. Page 30 of 38
31 Although you do not see them in the output, the control characters are part of the data in the String. Here is another method from the String class: public String tolowercase(); This method constructs a new String object containing all lower case letters. There is also a method that produces a new String object containing all upper case letters: public String touppercase(); QUESTION 22: Here are some lines of code. Which ones are correct? Used by permission. Page 31 of 38
32 Temporary Objects The "correct" answer for the last two lines might surprise you, but those lines are correct (although perhaps not very sensible.) Here is why: The temporary object is used to construct a second object. The reference to the second object is assigned to d. Now look at the last statement: System.out.println( "Dark, forlorn...".tolowercase() ); Used by permission. Page 32 of 38
33 A String is constructed. Then a second String is constructed (by the tolowercase() method). A reference to the second String is used a parameter for println(). Both String objects are temporary. After println() finishes, both Strings are garbage. (There is nothing special about temporary objects. What makes them temporary is how the program uses them. The objects in the above statement are temporary because the program saves no reference to them. The garbage collector will soon recycle them.) QUESTION 23: Tedious review: Can an object reference variable exist without referring to an object? Can an object exist without an object reference variable that refers to it? Used by permission. Page 33 of 38
34 Can an object reference variable exist that without referring to an object? Yes, a reference variable can be declared without initialization: String mystring; Also, a reference can be set to null. Can an object exist without an object reference variable that refers to it? Yes, as seen in the previous example. Such objects are temporary. The startswith() Method Here is another method of the String class: public boolean startswith(string prefix); The startswith() method tests if one String is the prefix of another. This is frequently needed in programs. (Although this example is too short to show a real-world situation, study it carefully.) Notice how trim() is used in the last if statement. QUESTION 24: What does the program write to the monitor? Used by permission. Page 34 of 38
35 Prefix 1 matches. Prefix 2 fails. Prefix 3 fails. Prefix 4 matches. More String Operations Here is how the last if of the program worked: The String " My love" starts with two spaces, so it does not match the start of the String referenced by burns. However, its trim() method is called, which creates a new String without those leading spaces: Used by permission. Page 35 of 38
36 Programmers usually do not think about what happens in such detail. Usually, a programmer thinks: "trim the spaces of one String and see if it is the prefix of another." But sometimes, you need to analyze a statement carefully to be sure it does what you want. Look again at the above statement and practice thinking about it at several levels of detail. QUESTION 25: What does the tolowercase() method of class String do? Used by permission. Page 36 of 38
37 It creates a new String which is a lower case version of the original string. Cascaded String Operations Sometimes a method of a String creates another String, and then a method of that second String is invoked to create a third String (and so on). This is sometimes called a cascade. Usually a cascade involves intermediate temporary objects. Look at these lines of code: Hint: decide what the parameter is by carrying out the operations of " MY LOVE".trim().toLowerCase(). Then decide what string invokes the startswith() method. QUESTION 26: What does the above write to the monitor? Used by permission. Page 37 of 38
38 Both start with the same letters. " MY LOVE".trim().toLowerCase() creates the temporary string "my love". "burns.tolower() creates the temporary string "my love is like a red, red rose." The parameter string starts with the same characters as the tolower()method's string. End of the Chapter That was a complicated question. I hope you rose to the occasion. If you got burned, review the example. You may wish to review the following. An easy way to construct a String. The null value. How an object becomes garbage. String class description. String concatenation. Shorthand notation for String concatenation. Strings as immutable objects. Overloaded operators. Length of a string. charat() method Substrings The trim() method. The startswith() method. Cascaded operations Used by permission. Page 38 of 38
Chapter 29B: More about Strings Bradley Kjell (Revised 06/12/2008)
Chapter 29B: More about Strings Bradley Kjell (Revised 06/12/2008) String objects are frequently used in programs. This chapter provides extra practice in using them. Chapter Topics: Strings are Immutable
More informationLecture Notes for CS 150 Fall 2009; Version 0.5
for CS 150 Fall 2009; Version 0.5 Draft! Do not distribute without prior permission. Copyright 2001-2009 by Mark Holliday Comments, corrections, and other feedback appreciated holliday@email.wcu.edu Chapter
More informationSTUDENT LESSON A10 The String Class
STUDENT LESSON A10 The String Class Java Curriculum for AP Computer Science, Student Lesson A10 1 STUDENT LESSON A10 The String Class INTRODUCTION: Strings are needed in many programming tasks. Much of
More information"Hello" " This " + "is String " + "concatenation"
Strings About Strings Strings are objects, but there is a special syntax for writing String literals: "Hello" Strings, unlike most other objects, have a defined operation (as opposed to a method): " This
More informationStrings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics
Strings Strings and their methods Produced by: Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Topics list Primitive Types: char Object Types: String Primitive vs Object Types
More informationStrings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics
Strings Strings and their methods Produced by: Mairead Meagher Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Topics list Primitive Types: char Object Types: String Primitive
More informationA variable is a name for a location in memory A variable must be declared
Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;
More informationJava s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"
1 Java s String Class in simplest form, just quoted text "This is a string" "So is this" "hi" used as parameters to Text constructor System.out.println 2 The Empty String smallest possible string made
More informationMore non-primitive types Lesson 06
CSC110 2.0 Object Oriented Programming Ms. Gnanakanthi Makalanda Dept. of Computer Science University of Sri Jayewardenepura More non-primitive types Lesson 06 1 2 Outline 1. Two-dimensional arrays 2.
More informationWe now start exploring some key elements of the Java programming language and ways of performing I/O
We now start exploring some key elements of the Java programming language and ways of performing I/O This week we focus on: Introduction to objects The String class String concatenation Creating objects
More informationCMPT 125: Lecture 3 Data and Expressions
CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,
More informationIntro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16
Intro to Strings Lecture 7 CGS 3416 Spring 2017 February 13, 2017 Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, 2017 1 / 16 Strings in Java In Java, a string is an object. It is not a primitive
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All This chapter discusses class String, from the java.lang package. These classes provide the foundation for string and character manipulation
More informationUsing Java Classes Fall 2018 Margaret Reid-Miller
Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationLab 14 & 15: String Handling
Lab 14 & 15: String Handling Prof. Navrati Saxena TA: Rochak Sachan String Handling 9/11/2012 22 String Handling Java implements strings as objects of type String. Once a String object has been created,
More informationLesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014
Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Advanced Java This chapter discusses class String, class StringBuilder and class Character from the java.lang package. These classes provide
More informationBM214E Object Oriented Programming Lecture 8
BM214E Object Oriented Programming Lecture 8 Instance vs. Class Declarations Instance vs. Class Declarations Don t be fooled. Just because a variable might be declared as a field within a class that does
More informationSlide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto
CS 170 Java Programming 1 More on Strings Working with the String class Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 What are Strings in Java? Immutable sequences of 0 n characters
More informationIntro to Strings. Lecture 7 COP 3252 Summer May 23, 2017
Intro to Strings Lecture 7 COP 3252 Summer 2017 May 23, 2017 Strings in Java In Java, a string is an object. It is not a primitive type. The String class is used to create and store immutable strings.
More informationGetting started with Java
Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving
More informationProgramming with Java
Programming with Java String & Making Decision Lecture 05 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives By the end of this lecture you should be able to : Understand another
More informationChapter 8: Strings and Things
Chapter 8: Strings and Things Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Word Of Fortune Program this will be cleared when it's working 1-2 Chapter Topics Chapter 8 discusses
More informationSTRINGS AND STRINGBUILDERS. Spring 2019
STRINGS AND STRINGBUILDERS Spring 2019 STRING BASICS In Java, a string is an object. Three important pre-built classes used in string processing: the String class used to create and store immutable strings
More informationLecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4
Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program,
More informationAppendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method
Appendix 3 Java - String charat() Method This method returns the character located at the String's specified index. The string indexes start from zero. public char charat(int index) index -- Index of the
More informationCOE318 Lecture Notes Week 4 (Sept 26, 2011)
COE318 Software Systems Lecture Notes: Week 4 1 of 11 COE318 Lecture Notes Week 4 (Sept 26, 2011) Topics Announcements Data types (cont.) Pass by value Arrays The + operator Strings Stack and Heap details
More informationReview Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:
More informationStrings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.
Strings Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and
More informationMore on variables and methods
More on variables and methods Robots Learning to Program with Java Byron Weber Becker chapter 7 Announcements (Oct 12) Reading for Monday Ch 7.4-7.5 Program#5 out Character Data String is a java class
More informationappreciate the difference between a char and a string understand and use the String class methods
1 8 THE STRING CLASS Terry Marris 16 April 2001 8.1 OBJECTIVES By the end of this lesson the student should be able to appreciate the difference between a char and a string understand and use the String
More informationCSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI
CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 08 Constants and Inline Functions Welcome to module 6 of Programming
More informationTable of Contents Date(s) Title/Topic Page #s. Abstraction
Table of Contents Date(s) Title/Topic Page #s 9/10 2.2 String Literals, 2.3 Variables and Assignment 34-35 Abstraction An abstraction hides (or suppresses) the right details at the right time An object
More informationDEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Internal Examination 1 Answer Key DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Branch & Sec : CSE Date : 08.08.2014 Semester : V Sem Max Marks : 50 Marks Sub Code& Title : CS2305 Programming Paradigms
More informationUsing System.out.println()
Programming Assignments Read instructions carefully Many deduction on Program 3 for items in instructions Comment your code Coding conventions 20% of program grade going forward Class #23: Characters,
More information5. Control Statements
5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements
More informationCS112 Lecture: Characters and Strings
CS112 Lecture: Characters and Strings Objectives: Last Revised 3/21/06 1. To introduce the data type char and related basic information (escape sequences, Unicode). 2. To introduce the library classes
More information6.001 Notes: Section 8.1
6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything
More informationJava Foundations: Unit 3. Parts of a Java Program
Java Foundations: Unit 3 Parts of a Java Program class + name public class HelloWorld public static void main( String[] args ) System.out.println( Hello world! ); A class creates a new type, something
More informationFall 2017 CISC124 10/1/2017
CISC124 Today First onq quiz this week write in lab. More details in last Wednesday s lecture. Repeated: The quiz availability times will change to match each lab as the week progresses. Useful Java classes:
More informationCS 116x Winter 2015 Craig S. Kaplan. Module 09 Text Processing. Topics
CS 116x Winter 2015 Craig S. Kaplan Module 09 Text Processing Topics Useful String functions Useful Character functions Introduction to regular expressions Readings The first part of Shiffman s online
More informationObject oriented programming. Instructor: Masoud Asghari Web page: Ch: 3
Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning
More informationFunctional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute
Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute Module # 02 Lecture - 03 Characters and Strings So, let us turn our attention to a data type we have
More informationVariables of class Type. Week 8. Variables of class Type, Cont. A simple class:
Week 8 Variables of class Type - Correction! Libraries/Packages String Class, reviewed Screen Input/Output, reviewed File Input/Output Coding Style Guidelines A simple class: Variables of class Type public
More informationStudent Performance Q&A:
Student Performance Q&A: 2016 AP Computer Science A Free-Response Questions The following comments on the 2016 free-response questions for AP Computer Science A were written by the Chief Reader, Elizabeth
More informationCS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style
CS125 : Introduction to Computer Science Lecture Notes #4 Type Checking, Input/Output, and Programming Style c 2005, 2004, 2002, 2001, 2000 Jason Zych 1 Lecture 4 : Type Checking, Input/Output, and Programming
More information2. All the strings gets collected in a special memory are for Strings called " String constant pool".
Basics about Strings in Java 1. You can create Strings in various ways:- a) By Creating a String Object String s=new String("abcdef"); b) By just creating object and then referring to string String a=new
More informationClass. Chapter 6: Data Abstraction. Example. Class
Chapter 6: Data Abstraction In Java, there are three types of data values primitives arrays objects actually, arrays are a special type of object Class In Java, objects are used to represent data values
More informationStrings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.
The only operator that can be applied to String objects is concatenation (+) for combining one or more strings. Java also provides many methods with the String class to allow us to manipulate text. These
More informationTOPIC 2 INTRODUCTION TO JAVA AND DR JAVA
1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared
More informationCOMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods
COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,
More informationLecture Topics. Administrivia
ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality
More informationChapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.
Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationString. Other languages that implement strings as character arrays
1. length() 2. tostring() 3. charat() 4. getchars() 5. getbytes() 6. tochararray() 7. equals() 8. equalsignorecase() 9. regionmatches() 10. startswith() 11. endswith() 12. compareto() 13. indexof() 14.
More informationJ.43 The length field of an array object makes the length of the array available. J.44 ARRAYS
ARRAYS A Java array is an Object that holds an ordered collection of elements. Components of an array can be primitive types or may reference objects, including other arrays. Arrays can be declared, allocated,
More informationCOMP-202 Unit 5: Basics of Using Objects
COMP-202 Unit 5: Basics of Using Objects CONTENTS: Concepts: Classes, Objects, and Methods Creating and Using Objects Introduction to Basic Java Classes (String, Random, Scanner, Math...) Introduction
More informationExam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming
Exam 1 Prep Dr. Demetrios Glinos University of Central Florida COP3330 Object Oriented Programming Progress Exam 1 is a Timed Webcourses Quiz You can find it from the "Assignments" link on Webcourses choose
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationActivity 9: Object-Oriented
Activity 9: Object-Oriented Internally, the library class java.lang.string stores an array of characters. It also provides a variety of useful methods for comparing, manipulating, and searching text in
More informationSOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)
SOFTWARE DEVELOPMENT 1 Strings and Enumerations 2018W (Institute of Pervasive Computing, JKU Linz) CHARACTER ENCODING On digital systems, each character is represented by a specific number. The character
More informationCONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays
CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202
More informationJava How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;
More informationJava Bytecode (binary file)
Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.
More informationSummer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationOutput with printf Input. from a file from a command arguments from the command read
More Scripting 1 Output with printf Input from a file from a command arguments from the command read 2 A script can test whether or not standard input is a terminal [ -t 0 ] What about standard output,
More informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More informationBits, Words, and Integers
Computer Science 52 Bits, Words, and Integers Spring Semester, 2017 In this document, we look at how bits are organized into meaningful data. In particular, we will see the details of how integers are
More informationCS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output
CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables
More informationAccount joeacct = new Account (100, new Account (500)); Account joeacct = new Account (100, new Account (500, null));
Exam information 369 students took the exam. Scores ranged from 1 to 20, with a median of 11 and an average of 11.1. There were 40 scores between 15.5 and 20, 180 between 10.5 and 15, 132 between 5.5 and
More informationTopics. Class Basics and Benefits Creating Objects.NET Architecture and Base Class Libraries 3-2
Classes & Objects Topics Class Basics and Benefits Creating Objects.NET Architecture and Base Class Libraries 3-2 Object-Oriented Programming Classes combine data and the methods (code) to manipulate the
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationFirst Java Program - Output to the Screen
First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the
More informationA couple of decent C++ web resources you might want to bookmark:
CS106X Handout 10 Autumn 2012 September 28 th, 2012 C++ and CS106 Library Reference Written by Julie Zelenski and revised by Jerry. A couple of decent C++ web resources you might want to bookmark: http://www.cppreference.com
More informationComputer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Strings
Computer Science 252 Problem Solving with Java The College of Saint Rose Spring 2016 Topic Notes: Strings This semester we ve spent most of our time on applications that are graphical in nature: Manipulating
More informationVariables and Data Representation
You will recall that a computer program is a set of instructions that tell a computer how to transform a given set of input into a specific output. Any program, procedural, event driven or object oriented
More informationdo fifty two: Language Reference Manual
do fifty two: Language Reference Manual Sinclair Target Jayson Ng Josephine Tirtanata Yichi Liu Yunfei Wang 1. Introduction We propose a card game language targeted not at proficient programmers but at
More informationData and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:
Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions
More informationString Theory. Chapter Cut and Paste
Chapter 8 String Theory A great deal of the data processed by computer programs is represented as text. Word processors, email programs, and chat clients are primarily concerned with manipulating text.
More informationCS 1301 Ch 8, Part A
CS 1301 Ch 8, Part A Sections Pages Review Questions Programming Exercises 8.1 8.8 264 291 1 30 2,4,6,8,10,12,14,16,18,24,28 This section of notes discusses the String class. The String Class 1. A String
More informationQUIZ. What is wrong with this code that uses default arguments?
QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code
More informationDefining Classes. Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining
Defining Classes Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining Classes, fields, and constructors Methods and parameters, mutators and accessors Assignment
More informationChapter 3: Operators, Expressions and Type Conversion
101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To
More informationChapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics
Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional
More informationCSCI 6610: Intermediate Programming / C Chapter 12 Strings
... 1/26 CSCI 6610: Intermediate Programming / C Chapter 12 Alice E. Fischer February 10, 2016 ... 2/26 Outline The C String Library String Processing in C Compare and Search in C C++ String Functions
More informationSCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017
SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationCSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A
CSC 1051 Algorithms and Data Structures I Midterm Examination March 1, 2018 Name: KEY A Question Value Score 1 20 2 20 3 20 4 20 5 20 TOTAL 100 Please answer questions in the spaces provided. If you make
More informationCOMP 105 Homework: Type Systems
Due Tuesday, March 29, at 11:59 PM (updated) The purpose of this assignment is to help you learn about type systems. Setup Make a clone of the book code: git clone linux.cs.tufts.edu:/comp/105/build-prove-compare
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationSCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015
SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 06 / 03 / 2015 Instructor: Michael Eckmann Today s Topics Finish up discussion of projected homeruns 162 as a constant (final) double vs. int in calculation Scanner
More informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
More informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
More informationSection 2: Introduction to Java. Historical note
The only way to learn a new programming language is by writing programs in it. - B. Kernighan & D. Ritchie Section 2: Introduction to Java Objectives: Data Types Characters and Strings Operators and Precedence
More informationTypes and Expressions. Chapter 3
Types and Expressions Chapter 3 Chapter Contents 3.1 Introductory Example: Einstein's Equation 3.2 Primitive Types and Reference Types 3.3 Numeric Types and Expressions 3.4 Assignment Expressions 3.5 Java's
More informationThis course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units.
This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units. Introduction Overview Advancements in technology are
More informationCOMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string
COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an
More informationLecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4
Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete.
More information