06.09.2021 Views

Java with BlueJ, 2016a

Java with BlueJ, 2016a

Java with BlueJ, 2016a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

46 CHAPTER 2. BASICS<br />

2.5 The String Class<br />

It is very common for a program to work <strong>with</strong> text strings and the <strong>Java</strong><br />

String class is provided to facilitate the many things that programmers need<br />

to do <strong>with</strong> text strings. String literals are written as a sequence of characters<br />

that are delimited by double quotes. For example:<br />

"this is a line of text"<br />

"my first name is Joe"<br />

"Joe was born on May 1, 1999"<br />

The assignment statement:<br />

String fullName = "Joe Smith";<br />

declares fullName to be of type String. fullName is a variable and the<br />

<strong>Java</strong> compiler allocates memory for fullName. The memory location for<br />

fullName will contain a reference (an address) to the storage location where<br />

the text string ”Joe Smith” is actually stored. Memory for primitive types is<br />

handled differently. The memory location associated <strong>with</strong> a primitive type<br />

contains the value (not an address) of the variable. For example, an int<br />

variable will have a memory location reserved for it where the value of the<br />

variable is stored.<br />

There is a subtle difference that may be hard to appreciate at this time: a<br />

variable (of type String) holds a reference to the value instead of holding<br />

the actual value. The diagram below attempts to show the difference.<br />

Object References

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

Saved successfully!

Ooh no, something went wrong!