☰ Contents Programs and Values

Operators

Using Arithmetic and Operators

Student: I noticed you used * a few times in the last lesson. Was that multiplication?
Prof: That’s right.
Student: What other arithmetic operators are defined?
Prof: The standard ones are * for multiplication, / for division, - for subtraction, and + for addition. Here’s an example that uses a few of them.
Student: OK, 36 minus 25 is 11, divided by 2 is 5.5 not 5.
Prof: Good catch – / in Java does integer division on int values, so it always rounds towards 0 if it is working with ints.
Student: Hm. Different than Python but I think I remember seeing that in some other language…
Prof: Many languages do this – the idea is that all of these operators take and return integer values, so some decision about rounding has to be made on /.
Student: Alright. I can buy that.
Prof: One other detail to be aware of – + also works on strings (but the other operators don’t). On strings it does concatenation:
Student: Oh so now you’ll tell me about that difference in + from the last conversation?
Prof: Right! Thank you for remembering. We said age + 1 vs. label + 1 would have different behavior in that example because age was int and label was String. Let’s run it now:
Student: Interesting. So Java always concatenates if one side is a String.
Prof: You’ve got it! That’s the basics of integers and Strings in Java. Of course, there’s a lot more you can do with them, but it’s enough to get started.

Practice

After this program runs, the book prints the value of each name. Fill in what it prints.

int total = 7 * 3;
int half = total / 2;
String label = "Total: " + total;
total =
half =
label =