Programming and Problem Solving with Java

(やまだぃちぅ) #1
2.1 The Elements of Java Programs | 61

lastName = “Lincoln”; // String literal assigned to string variable
title = “President”; // String literal assigned to string variable
middleInitial = ‘ ‘; // char literal assigned to char variable
myChar = ‘B’; // char literal assigned to char variable


The following assignments are notvalid:

Invalid Assignment Statement Explanation
middleInitial = “A.”; middleInitialis of type char; ”A.”is a string
myChar = firstName; myCharis of type char; firstNameis of type String
myChar = “ “; myCharis of type char; ” “is a one-character literal string
firstName = Thomas; Thomasis an undeclared identifier
”Edison”= lastName; Only a variable can appear to the left of =
lastName = ; The expression to the right of =is missing

Figure 2.2 shows the variable myChar with the letter B stored in it.

String Expressions Although we can’t perform


arithmetic on strings, Java provides the
Stringclass with a special string operation,
called concatenation, that uses the +opera-
tor. Concatenating (joining) two strings
yields a new string containing the characters
from both strings. For example, given the
statements


String bookTitle;
String phrase1;
String phrase2;


phrase1 = “Introduction to Programming and Problem Solving “;
phrase2 =“with Java”;


we could write


bookTitle = phrase1 + phrase2;


which results in bookTitlebeing set equal to the character string


“Introduction to Programming and Problem Solving with Java”


The order of the strings in the expression determines how they appear in the resulting
string. If, for example, we write


bookTitle = phrase2 + phrase1;


Variable B

Value

myChar
(memory location 1101010011)

Variable identifier

char

Data type

Figure 2.2 Variable with Value
Free download pdf