How to Use the Plus Sign in Your Java Code
The plus sign is a versatile tool when programming with Java. It gives you some different options when writing code. In Java, you can do two different things with a plus sign:
You can add numbers with a plus sign.
For example, you can write
numberOfSheep = 2 + 5;
You can concatenate strings with a plus sign.
When you concatenate strings, you scrunch them together, one right after another. For example, the expression
"Barry" + " " + "Burd"
scrunches together Barry, a blank space, and Burd. The new scrunched-up string is (you guessed it) Barry Burd.
anAccount.lastName = "" + (char) (myRandom.nextInt(26) + 'A') + (char) (myRandom.nextInt(26) + 'a') + (char) (myRandom.nextInt(26) + 'a');
has many plus signs, and some of the plus signs concatenate things together. The first thing is a mysterious empty string (""). This empty string is invisible, so it never gets in the way of your seeing the second, third, and fourth things.
Onto the empty string, the program concatenates a second thing. This second thing is the value of the expression (char) (myRandom.nextInt(26) + 'A'). The expression may look complicated, but it’s really no big deal. This expression represents an uppercase letter (any uppercase letter, generated randomly).
Onto the empty string and the uppercase letter, the program concatenates a third thing. This third thing is the value of the expression (char) (myRandom.nextInt(26) + 'a'). This expression represents a lowercase letter (any lowercase letter, generated randomly).
Onto all this stuff, the program concatenates another lowercase letter. So altogether, you have a randomly generated three-letter name. For more details, see the upcoming sidebar.
The statement anAccount.balance = myRandom.nextInt(10000) assigns an int value to balance. But balance is a double variable, not an int variable. That’s okay. In a rare case of permissiveness, Java allows you to assign an int value to a double variable. The result of the assignment is no big surprise. If you assign the int value 8734 to the double variable balance, the value of balance becomes 8734.00.
Using the double type to store an amount of money is generally a bad idea.