02 Java
02 Java
15-121 (Reid-Miller) 7
There is no required textbook.
• Examples:
int numDimes;
double length; camelCase is the
Java convention
char courseSection;
boolean done;
String lastName;
count length
count = 3; count 3
length = 72.3 + 2.0; length 74.3
n = n + 1; n += 1; n++;
n = n - 1; n -= 1; n--;
Sequence Meaning
\t tab character
\n newline character
\" double quote
\' single quote
\\ backslash character
System.out.println(
"What \"character\" is this \\? ");
Fall 2020 15-121 (Reid-Miller) 22
An object of type String is a
sequence of (unicode) characters.
• Example:
String founder = "Carnegie";
int numChar = founder.length();
object dot operator method
Example:
String school = "Carnegie Mellon";
String founder = school.substring(0, 8);
String founder2 = school.substring(9);
Fall 2020 15-121 (Reid-Miller) 27
Replacing Characters
String replace(char oldChar, char newChar)
Returns a new String object resulting from replacing
every occurrence of oldChar with newChar.
• The original String object is unchanged.
(Strings are immutable!)
Example:
String founder = "Carnegie";
System.out.println( OUTPUT:
CarnEgiE
founder.replace('e', 'E')); Carnegie
System.out.println(founder);
Fall 2020 15-121 (Reid-Miller) 28
Changing Case
String toUpperCase()
Returns a new String object with all letters
converted to uppercase.
String toLowerCase()
Returns a new String object with all letters
converted to lowercase.
Immutable: You
need to print or
Example: assign the result to
String founder = "Carnegie"; a variable!
String upper = founder.toUpperCase();
String lower = founder.toLowerCase();
Example:
String founder = "Carnegie";
founder.equals(“Carnegie”); // returns true
founder.equals(“carnegie”); // returns false
• For example:
if (day == 1 && month.equals(“APRIL”)) {
System.out.println(“It’s April Fool’s Day”);
}
Example:
“mellon”.compareTo(“carnegie”); // returns positive #
“Mellon”.compareTo(“mellon”); // returns negative #