8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 1/25
Lesson5: JAVA
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
Objects and Strings
1
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 2/25
2
Objects-I
• So far, we have seen:
methods, which represent behavior
variables, which represent data
types, which represent categories ofdata
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 3/25
Objects-II
• In Java and other "object-oriented" programminglanguages, it is possible to create new types that arecombinations of the existing primitive types.– Such types are called object types or reference
types.– An object is an entity that contains data and behavior.
• There are variables inside the object, storingits data.
• There are methods inside the object,
representing its behavior.
• how to communicate with certain objects that exist inJava.
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
3
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 4/25
4
Constructing objects
• construct: To create a new object.– Objects are constructed with the new keyword.
– Most objects other than Strings must be constructed before they canbe used.
• Constructing objects, general syntax:<Object type> < Object name> = new < Object type> ( <parameters> );
– Examples:
– SimpleInput keyword = new SimpleInput();
DrawingPanel panel = new DrawingPanel(300,200);
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 5/25
5
Reminder: primitive variables
• We now need to examine some important differencesbetween the behavior of objects and primitive values.
• We saw with primitive variables that modifying the value of one variable does not modify the value of another.
• When one variable is assigned to another, the value iscopied.– Example:
int x = 5;
int y = x; // x = 5, y = 5y = 17; // x = 5, y = 17
x = 8; // x = 8, y = 17
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 6/25
6
Reference variables
• However, objects behave differently than primitives.– When working with objects, we have to understand the distinction
between an object, and the variable that stores it.
– Variables of object types are called reference variables.
– Reference variables do not actually store an object; they store the
address of an object's location in the computer memory.– If two reference variables are assigned to refer to the same object, the
object is not copied; both variables literally share the same object.Calling a method on either variable will modify the same object.
– Example:
DrawingPanel p1 = new DrawingPanel(80, 50);
DrawingPanel p2 = p1; // same window
p2.setBackground(Color.CYAN);
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 7/25
7
References example
• When panel2 refers to the same object as panel1,modifying either variable's background color will affect thesame window:DrawingPanel panel1 = new DrawingPanel(80,50);
DrawingPanel panel2 = new DrawingPanel(80,50);
DrawingPanel panel3 = new DrawingPanel(80,50);
panel1.setBackground(Color.RED);panel2.setBackground(Color.GREEN);
panel3.setBackground(Color.BLUE);
panel2 = panel1;panel2.setBackground(Color.MAGENTA);
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 8/25
8
Modifying parameters
• When we call a method and pass primitive variables' values as parameters, it islegal to assign new values to the parameters inside the method.
– But this does not affect the value of the variable that was passed, because its valuewas copied.
– Example:
public static void main(String[] args) {
int x = 1;
foo(x);
System.out.println(x); // output: 1
}
public static void foo(int x) {
x = 2;
}
value 1 is copied into parameter
parameter's value is changed to 2
(variable x in main is unaffected)INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 9/25
9
Objects as parameters
• When an object is passed as a parameter, it is not copied.It is shared between the original variable and the method'sparameter.– If a method is called on the parameter, it will affect the original
object that was passed to the method.–
Example:public static void main(String[] args) {DrawingPanel p = new DrawingPanel(80,
50);p.setBackground(Color.YELLOW);foo(p);
}
public static void foo(DrawingPanel panel) {panel.setBackground(Color.CYAN);
}
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 10/25
10
Strings
• One of the most common types of objects in Java is type String.– String: A sequence of text characters.– Object types' names are usually uppercase (String), unlike primitives
(int).
•
String variables can be declared and assigned, just like primitivevalues:– String <name> = "<text>";– String <name> = <expression that produces a String>;
– Examples:String name = "Marla Singer";
int x = 3, y = 5;String point = "(" + x + ", " + y + ")";
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 11/25
11
Indexes
• The characters in a String are each internally numberedwith an index , starting with 0 for the first character:– Example:String name = "M. Stepp";
name -->
• Individual text characters are represented by a primitive
type called char. Literal char values are surrounded withapostrophe (single-quote) marks, such as 'a' or '4'.– An escape sequence can be represented as a char, such as'\n' (new-line character) or '\'' (apostrophe).
0 1 2 3 4 5 6 7
'M' '.' ' ' 'S' 't' 'e' 'p' 'p'
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 12/25
12
Calling methods of Strings
• Strings are objects that contain methods.– A String contains code inside it that can manipulate or process the
String in several useful ways.– When we call a method of a String, we don't just write the method's
name. We also have to write which String we want to execute themethod. The results will be different from one String to another.
• Calling a method of an object, general syntax:<name> . <methodName> ( <parameters> )
– Examples:String name = "Marty";
System.out.println(name.toUpperCase()); //MARTY
String name2 = "Marty Stepp";System.out.println(name2.length()); //11
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 13/25
13
String methods
• Here are several of the most useful String methods:
Method name Description
charAt(index ) character at a specific index
indexOf(String) index where the start of the given Stringappears in this String (-1 if it is not there)
length() number of characters in this String
substring(index1, index2) the characters from index1 to just before
index2toLowerCase() a new String with all lowercase letters
toUpperCase() a new String with all uppercase letters
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 14/25
14
String method examples
// index 012345678901
String s1 = "Stuart Reges";
String s2 = "Marty Stepp";
System.out.println(s1.length()); // 12
System.out.println(s1.indexOf("e")); // 8
System.out.println(s1.substring(1, 4)); // tua
String s3 = s2.toUpperCase();
System.out.println(s3.substring(6, 10)); // STEP
String s4 = s1.substring(0, 6);System.out.println(s4.toLowerCase()); // stuart
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 15/25
15
Methods that return values
• The methods of String objects do not print their resultsto the console.– Instead, a call to one of these methods can be used as an
expression or part of an expression.
• Recall: return value: A value that is produced by a call to amethod, and can be used in an expression.– Return values are the opposite of parameters. Parameters pass
information inward into a method from the caller. Return valuesgive information outward from the method to the caller.
– The methods of String objects produce (or return) a result whichis either a new String or a number, depending on the method.
– The result can be used in a larger expression, stored in avariable, or printed to the console.
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 16/25
16
Return values example
String str = "Janet Smith";int len = 2 * str.length() + 1;System.out.println(len);// 23
String first = str.substring(0, 5);
System.out.println("first name is " + first);// Janet
• What expression would produce the first letter of theString? The last letter?
• What expression would trim any String, not just the oneabove, to its first word?– Does our answer assume anything about the letters in the
String?
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 17/25
17
Modify and reassign
• The various methods that modify Strings return a new String withthe new contents.– They don't modify the existing String.
• Just like int or double variables, String variables do notchange when used in an expression unless you reassign them:–
Bad Example:String s = "I get it";s.toUpperCase();System.out.println(s); // I get it
– Better Code:
String s = "I get it";s = s.toUpperCase();
System.out.println(s); // I GET IT
Equivalent with an int:
int x = 3;
x + 1;
System.out.println(x); // 3
Equivalent with an int:
int x = 3;
x = x + 1;
System.out.println(x); // 4INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 18/25
18
Strings vs. other objects
• Strings are extremely useful objects, but they behave differentlythan most objects in Java.– Strings are created differently than most objects.
We don't use the new keyword when constructing Strings.(This is because Sun felt that Strings were so important, they shouldbe integrated into the language with a shorter syntax.)
– Strings can't be modified without reassigning them.• Color objects are the same way.
• An object that cannot be changed after construction is sometimes called animmutable object.
– It is harder to visualize Strings as having data and behavior, but aString's data is its characters, and its behavior is the methods liketoUpperCase and length that manipulate or examine thosecharacters.
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 19/25
Selected Methods of String Class
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
19
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 20/25
More Useful Methods
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
20
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 21/25
Some Comparison Methods
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
21
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 22/25
String Example-1public class FindCharacters {
public static void main(String[] args) {// Text string to be analyzed
String text = "To be or not to be, that is the question;"
+ " Whether 'tis nobler in the mind to suffer"
+ " the slings and arrows of outragous fortune,"
+ " or to take arms against a sea of troubles,"
+ " and by opposing end them?";
int andCount = 0; // Number of and's
int theCount = 0; // Number of the's
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
22Code is taken from WROX
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 23/25
Example-1 Cont.int index = -1; // Current index position
String andStr = "and"; // Search substringString theStr = "the"; // Search substring
// Search forwards for "and"
index = text.indexOf(andStr); // Find 1st 'and'while(index >= 0) {
++andCount;
index += andStr.length(); // Step to position after last 'and'index = text.indexOf(andStr, index);
}
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
23Code is taken from WROX
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 24/25
Example – 1 Cont.// Search backwards for "the"
index = text.lastIndexOf(theStr); // Find last 'the'while(index >= 0) {
++theCount;
index -= theStr.length(); // Step to position before last 'the'
index = text.lastIndexOf(theStr, index);
}
System.out.println("The text contains " + andCount + " ands\n"
+ "The text contains " + theCount + " thes\n");}
}
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
24Code is taken from WROX
8/7/2019 Lesson5 Objects_Strings
http://slidepdf.com/reader/full/lesson5-objectsstrings 25/25
Example-2 Cont.String firstString = "Peter";
String secondString = “David";if (firstString.compareTo(secondString) < 0)
System.out.println("firstString comes beforesecondString");
else if (firstString.compareTo(secondString) > 0)System.out.println("firstString comes after
secondString");
else
System.out.println("firstString and secondString areequal");
INTRODUCTION TO JAVA PROGRAMMING,EHSAN CHAUHDRY
25Code is taken from WROX
Recommended