JAVA VARIABLES
Printing Java variables
The method println() is often used to display variable values in the console. The operator + can join text and variables or add numbers.
Outputting a variable’s value
To display a variable’s value, pass its name to the method System.out.println(). Write the variable name without quotes:
String vardas = "Jonas";
System.out.println(vardas);Jonas
On the first line, we create something like a box named vardas and put the text inside it: Jonas. On the second line, println() asks to display what is in that box. Because we write vardas without quotes, Java displays its contents rather than the word “vardas” itself.
Text and a variable on one line
The operator + joins text with a variable’s value. This joining of strings is called
String vardas = "Jonas";
System.out.println("Labas, " + vardas + "!");Labas, Jonas!
Java starts with the text Labas, , then appends the name stored in the variable Jonas, and finally an exclamation mark. The + sign acts like glue joining three pieces of text. The space after the comma matters too; without it, we would get Labas,Jonas!.
Joining multiple text variables
The operator + can also join multiple String variables:
String vardas = "Jonas ";
String pavarde = "Jonaitis";
String pilnasVardas = vardas + pavarde;
System.out.println(pilnasVardas);Jonas Jonaitis
The variable vardas stores Jonas , while pavarde stores Jonaitis. Java joins the contents of both boxes and puts the result in a new box named pilnasVardas. There is already a space after the word Jonas, so the first and last names appear neatly separated in the console.
Two meanings of the + operator
The Java operator + behaves differently depending on the data types involved:
- For text it joins the values into a single
String. - For numbers it performs mathematical addition.
int x = 5;
int y = 6;
System.out.println(x + y);11
- The box
xreceives the number5. - The box
yreceives the number6. - Because both values are numbers,
+adds them:5 + 6 = 11. println()displays the resulting number in the console:11.
Mixing text and numbers
Order matters when joining text and numbers. Java evaluates the expression from left to right. Once the result becomes text, subsequent uses of + join the remaining values as text:
int x = 5;
int y = 6;
System.out.println("Suma yra " + x + y);
System.out.println("Suma yra " + (x + y));Suma yra 56
Suma yra 11
Java reads the first line from left to right. It sees the text Suma yra and appends x, producing Suma yra 5. This is already text, so when it adds y , Java no longer performs arithmetic — it simply appends the digit 6, producing Suma yra 56.
On the second line, parentheses mean “calculate what is inside first”. Java first calculates 5 + 6 and gets 11. Only then does it join that result with the text, so the console displays Suma yra 11.
The form "Suma yra " + (x + y) clearly shows that addition must happen before string concatenation.