Suppose we want to read some input from the user. The function IO.readln() (optionally) takes a prompt to give to the user and returns one line of input that the user typed on their console. Like so:
IO.readln("Am I sentient?");
If we don't simply want to ignore whatever the user writes as an answer, we need to create a variable to store the user's input in. In Java, all variables have types. The type of the user's input is a String, so we'll declare a variable called answer and use it to store the user's input. Extending our Java greeter:
void main() {
String answer = IO.readln("Am I sentient?");
IO.println("Your answer was " + answer);
}
This example demonstrates two new concepts: assignment using the = operator, and concatenation with the + operator.
In Java, when we write:
answer = "Hello";
It should not be understood as a "defining equation" or a mathematical definition of the variable answer. That is because (unlike in, say, Haskell, where variables are unchanging) the value of a variable in Java can change as the program executes. This is called mutability. Instead, the above line of code should be understood to mean "replace whatever value is in the answer variable with the "Hello" string".
$ javac Main.java
$ java Main
Am I sentient?no
Your answer was no
$