Expression fundamentals

A Java expression is a piece of code that evaluates to a value. Here is an example:

years * 365 * 24 * 60 * 60

Given someone's age in the years variable, this expression would evaluate to how many seconds old they are (as: age in years, times the number of days in a year, times the number of hours in a day, times the number of minutes in an hour, times the number of seconds in a minute). The asterisk (*) is the multiplication operator. This expression might appear in an assignment statement, like below:

ageInSeconds = years * 365 * 24 * 60 * 60;

The RHS of an assignment statement is an expression. It's evaluated, then assigned to the variable (or field or array element) named by the LHS.

Literals

The simplest expressions are those consisting of only a number or letter or String. Like the following:

die = 1;
years = 59;
gender = 'F';
title = "Dr.";
Java Literal Syntax
Type Example literals
int 1, 2, 3, ... If you want to express an int in hexadecimal, you can prefix the number with 0x or 0X, and use only the hexadecimal digits (0–9, a–f or A–F). E.g. 0xDEADBEEF
long If you want to express a long value, add L to the end of the number. And if you want, you can add an underscore character to make the literals easier to read. E.g., 90_827_345_098L
float 0.0f, 2.0f, 3.14159f
double 0.0, 2.0, 6.02214076E+23. double is the default type for a floating-point literal, but you can add “d” or “D” if you want to.
boolean true, false
char 'a', 'B', 'c'. Note the use of single quotes.
String "What's your name?" Note the use of double, rather than single, quotes.

With String literals there is the complication that sometimes you want the double-quote character to be part of the string. You can't simply include one in the string, because then Java wouldn't know which one terminated the string. To include a double-quote character in a string, you need to escape it.

String question = "Is \"compup\" a word?";

The escape character “\” is also useful for including characters that don't have a key on the keyboard, like the tab character (\t) or the newline character (\n), which you will find useful when you want control over your output (more on that later).

Magic numbers (avoid them)

In the example above where we calculated someone's age in seconds, the RHS expression (years * 365 * 24 * 60 * 60) might not have been too hard to puzzle out, because the numbers 365, 24, and 60 are pretty well-known as the number of days in a year, the number of hours in a day, and the number of minutes in an hour. And 3.14159, as an approximate value for π, might be fairly recognizable as well.

But a lot of numbers will not be obvious to your readers (or yourself, after a few days). Programmers call these “magic numbers,” because, to the reader, they are inexplicable. Better code would be:

int NUMBER_OF_SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
...
ageInSeconds = years * NUMBER_OF_SECONDS_IN_YEAR;