Vous êtes sur la page 1sur 25

Lesson5: JAVA

Objects and Strings

INTRODUCTION TO JAVA PROGRAMMING,


1
EHSAN CHAUHDRY
Objects-I
• So far, we have seen:
methods, which represent behavior

variables, which represent data

types, which represent categories of


data

INTRODUCTION TO JAVA PROGRAMMING,


2
EHSAN CHAUHDRY
Objects-II
• In Java and other "object-oriented" programming
languages, it is possible to create new types that are
combinations 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, storing
its data.
• There are methods inside the object,
representing its behavior.

• how to communicate with certain objects that exist in


Java.

INTRODUCTION TO JAVA PROGRAMMING,


3
EHSAN CHAUHDRY
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 can
be 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,


4
EHSAN CHAUHDRY
Reminder: primitive variables
• We now need to examine some important differences
between 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 is
copied.
– Example:
int x = 5;
int y = x; // x = 5, y = 5
y = 17; // x = 5, y = 17
x = 8; // x = 8, y = 17

INTRODUCTION TO JAVA PROGRAMMING,


5
EHSAN CHAUHDRY
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,


6
EHSAN CHAUHDRY
References example
• When panel2 refers to the same object as panel1,
modifying either variable's background color will affect the
same 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,


7
EHSAN CHAUHDRY
Modifying parameters
• When we call a method and pass primitive variables' values as parameters, it is
legal 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 value
was 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


8 (variable x INTRODUCTION
in main isTOunaffected)
JAVA PROGRAMMING,
EHSAN CHAUHDRY
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's
parameter.
– 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,


9
EHSAN CHAUHDRY
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 primitive


values:
– 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,


10
EHSAN CHAUHDRY
Indexes
• The characters in a String are each internally numbered
with an index, starting with 0 for the first character:
– Example:
String name = "M. Stepp";

name -->0 1 2 3 4 5 6 7
'M' '.' ' ' 'S' 't' 'e' 'p' 'p'
• Individual text characters are represented by a primitive
type called char. Literal char values are surrounded with
apostrophe (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).

INTRODUCTION TO JAVA PROGRAMMING,


11
EHSAN CHAUHDRY
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 the
method. 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,


12
EHSAN CHAUHDRY
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 String
appears 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
index2
toLowerCase() a new String with all lowercase letters
toUpperCase() a new String with all uppercase letters

INTRODUCTION TO JAVA PROGRAMMING,


13
EHSAN CHAUHDRY
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,


14
EHSAN CHAUHDRY
Methods that return values
• The methods of String objects do not print their results
to 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 a


method, 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 values
give information outward from the method to the caller.
– The methods of String objects produce (or return) a result which
is either a new String or a number, depending on the method.
– The result can be used in a larger expression, stored in a
variable, or printed to the console.

INTRODUCTION TO JAVA PROGRAMMING,


15
EHSAN CHAUHDRY
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 the
String? The last letter?

• What expression would trim any String, not just the one
above, to its first word?
– Does our answer assume anything about the letters in the
String?
INTRODUCTION TO JAVA PROGRAMMING,
16
EHSAN CHAUHDRY
Modify and reassign
• The various methods that modify Strings return a new String with
the new contents.
– They don't modify the existing String.
• Just like int or double variables, String variables do not
change when used in an expression unless you reassign them:
– Bad Example:
String s = "I get it";
s.toUpperCase();  Equivalent with an int:
System.out.println(s); int//
x I= get
3; it
– Better Code: x + 1;
String s = "I get it"; System.out.println(x); // 3
s = s.toUpperCase();
System.out.println(s);  Equivalent
// I GET with
IT an int:
int x = 3;
x = x + 1;
17 System.out.println(x);
INTRODUCTION TO JAVA PROGRAMMING, // 4
EHSAN CHAUHDRY
Strings vs. other objects
• Strings are extremely useful objects, but they behave differently
than 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 should
be 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 an
immutable object.

– It is harder to visualize Strings as having data and behavior, but a


String's data is its characters, and its behavior is the methods like
toUpperCase and length that manipulate or examine those
characters.

INTRODUCTION TO JAVA PROGRAMMING,


18
EHSAN CHAUHDRY
Selected Methods of String Class

INTRODUCTION TO JAVA PROGRAMMING,


19
EHSAN CHAUHDRY
More Useful Methods

INTRODUCTION TO JAVA PROGRAMMING,


20
EHSAN CHAUHDRY
Some Comparison Methods

INTRODUCTION TO JAVA PROGRAMMING,


21
EHSAN CHAUHDRY
String Example-1
public 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

Code is taken from WROX INTRODUCTION TO JAVA PROGRAMMING,


22
EHSAN CHAUHDRY
Example-1 Cont.
int index = -1; // Current index position
String andStr = "and"; // Search substring
String 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);
}
Code is taken from WROX INTRODUCTION TO JAVA PROGRAMMING,
23
EHSAN CHAUHDRY
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");
}
}

Code is taken from WROX INTRODUCTION TO JAVA PROGRAMMING,


24
EHSAN CHAUHDRY
Example-2 Cont.
String firstString = "Peter";
String secondString = “David";
if (firstString.compareTo(secondString) < 0)
System.out.println("firstString comes before
secondString");
else if (firstString.compareTo(secondString) > 0)
System.out.println("firstString comes after
secondString");
else
System.out.println("firstString and secondString are
equal");

Code is taken from WROX INTRODUCTION TO JAVA PROGRAMMING,


25
EHSAN CHAUHDRY

Vous aimerez peut-être aussi