Comments in Java . On this page, you see some text preceded with “ // ”. Such text is called a
comment . We write comments in a Java program to help us understand the pro-
gram. Comments are ignored by Java.
A comment that begins with // ends at the end of the line; it is called a sin-
gle-line comment . A comment can also have the form /* ... */ ; it can be a
multi-line comment . The comment may span many lines.
we could not write this (try it in your IDE!):
int quantity; // This declaration is illegal
To place a value in a variable, use an assignment statement . Here are examples:
Execution of the first assignment statement evaluates the expression, 8 , and
stores its value in variable quantity . The second assignment statement is exe-
cuted similarly, and quantity and price now look like this:
Any int expression may appear in place of expressions 8 and 3.99 in the
first assignment statement. For example, we can write this assignment statement
(which has the same result as the first assignment statement above):
quantity= 4 + 4;
There is one restriction: the type of the variable in an assignment statement
has to be the same as or wider than the type of the expression. For example, the
first assignment statement below is legal but the second one is illegal because
type int is narrower than type double . If the type of the variable is wider than
the type of the expression, the value of the expression is cast to the type of the
The assignment sign =. In the 1600s, Robert Recorde introduced the sign = to stand for equali-
ty, and after many years, the world universally adopted that convention. In the
late 1960s, the programming language C decided that = would be used for
assignment and == for equality, because programmers wrote more assignment
statements than equality relations. This change has caused more confusion and
wasted time than perhaps any other notational convention. Beginning program-
mers often ask why we write x=x+1; —how could x and x+1 be equal?
We write the assignment in the form
x= x + 1;
with no blank before the = , so that it does not look symmetric and is less liable
to be mistaken for an equality test.