Joseph Haugh
University of New Mexico
Java
"")String s1 = "Maelle";
String s2 = "";
Python
'') or double ("") quotess1 = "Maelle"
s2 = ''
Denoted with single ('') quotes
Only a single character allowed inside
char c1 = 'j';
char c2 = 'H';
char c3 = 'he'; // ERRORvoid main() {
String s1 = "Hello";
String s2 = "World";
String s3 = s1 + s2;
IO.println(s3); // Prints: HelloWorld
IO.println(s1 + " " + s2); // Prints: Hello World
}
+) used to add numbers?void main() {
int a = 5;
int b = 7;
IO.println(a + b); // Prints: 12
IO.println("Sum is " + a + b); // Prints: Sum is 57
IO.println("Sum is " + (a + b)); // Prints: Sum is 12
IO.println(a + b + "boo"); // Prints: 12boo
}
void main() {
int a = 3;
a = 2 * a + 1;
int b = 2;
IO.println(a + "/" + b + "= " + a / b);
}
Prints: 7/2= 3
Methods are functions we can call on a given variable with a type such as a String
We call methods using the following syntax:
<<variableName>>.<<methodName>>(<<argList>>);For example, we can check if two Strings are equal using the equal method. We cannot use the == operator on Strings to check for equality:
void main() {
String s1 = "CS152";
String s2 = "CS";
s2 += "152";
IO.println(s1.equals(s2)); // true
IO.println(s1 == s2); // false
}== is used to check for equality of primitive types
equal is used to check for equality of reference types
void main() {
String s1 = "Maelle";
String s2 = "Verso";
IO.println(s1.length() + s2.length()); // Prints: 11
}
void main() {
String s1 = "Maelle";
IO.println(s1.charAt(0)); // Prints: M
IO.println(s1.charAt(5)); // Prints: e
IO.println(s1.charAt(6)); // ERROR
}
void main() {
String s1 = "Maelle";
s1.toUpperCase();
IO.println(s1); // Prints: Maelle
s1 = s1.toUpperCase();
IO.println(s1); // Prints: MAELLE
}
void main() {
String s1 = "Maelle";
IO.println(s1.substring(2)); // Prints: elle
IO.println(s1.substring(3, 5)); // Prints: ll
}
void main() {
String s1 = "expedition33";
for (int i = 0; i < s1.length(); i++) {
if (i % 2 == 0) {
char c = s1.charAt(i);
IO.println(c);
}
}
}
What if instead of printing out the individual even index characters we wanted to create a new string with them?
void main() {
String s1 = "expedition33";
String result = "";
for (int i = 0; i < s1.length(); i++) {
if (i % 2 == 0) {
char c = s1.charAt(i);
result += c;
}
}
IO.println(result);
}IntelliJ may warn you do change this, don’t listen!