When one side of + is a String, + turns the number into text and joins them. When both sides are numbers, + adds. Java works left to right, which causes a classic trap.
+
"Age: " + 5 // Age: 5 (String + number, joins as text) 5 + 3 // 8 (number + number, adds) "" + 5 + 3 // 53 (left to right: "5" then "53") 5 + 3 + "" // 8 (5 + 3 = 8 first, then + "")
▶ Try it: run this, then change something and run it again.
What does "Age: " + 5 print?
"Age: " + 5
What does "" + 5 + 3 print?
"" + 5 + 3
What does 5 + 3 + "" print?
5 + 3 + ""
Type exactly what this prints:
System.out.println("Sum: " + (2 + 3));
True or false?
Write the body of label that takes a String name and an int age and returns the text name is age — for example, label("Ada", 30) returns Ada is 30.
label
String name
int age
name is age
label("Ada", 30)
Ada is 30