06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Exercise 17-2: Loop through and print every character of a String one at a time.<br />

String message = " a bunch of text here. ";<br />

for (int i = 0; i < _____________ ); i + + ) {<br />

}<br />

char c = ________________ ;<br />

println(c);<br />

We can also change a String <strong>to</strong> all uppercase (or lowercase) using the <strong>to</strong>UpperCase( ) method.<br />

String uppercase = message.<strong>to</strong>UpperCase() ;<br />

println(uppercase);<br />

Text 307<br />

You might notice something a bit odd here. Why didn’t we simply say “ message.<strong>to</strong>UpperCase( ) ” and then<br />

print the “ message ” variable? Instead, we assigned the result of “ message.<strong>to</strong>UpperCase( ) ” <strong>to</strong> a new variable<br />

with a diff erent name— “ uppercase ” .<br />

Th is is because a String is a special kind of object. It is immutable . An immutable object is one whose data<br />

can never be changed. Once we create a String , it stays the same for life. Any time we want <strong>to</strong> change the<br />

String , we have <strong>to</strong> create a new one. So in the case of converting <strong>to</strong> uppercase, the method <strong>to</strong>UpperCase( )<br />

returns a copy of the String object with all caps.<br />

Th e last method we will cover in this chapter is equals( ) . You might fi rst think <strong>to</strong> compare Strings using<br />

the “ = = ” opera<strong>to</strong>r.<br />

String one = " hello";<br />

String two = " hello";<br />

println(one = = two);<br />

Technically speaking, when “ � � ” is used with objects, it compares the memory addresses for each object.<br />

Even though each string contains the same data— “ hello ” —if they are diff erent object instances, then<br />

“ � � ” could result in a false comparison. Th e equals( ) function ensures that we are checking <strong>to</strong> see if two<br />

String objects contain the exact same sequence of characters, regardless of where that data is s<strong>to</strong>red in the<br />

computer’s memory.<br />

String one = " hello";<br />

String two = " hello";<br />

println(one.equals(two));<br />

Although both of the above methods return the correct result, it is safer <strong>to</strong> use equals( ) . Depending on<br />

how String objects are created in a sketch, “ � � ” will not always work.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!