Java Print Variables – Displaying Variables in Java
- Krishnamohan Yagneswaran
- Apr 30
- 2 min read
The println() method is commonly used to display variables in Java. But, what if you want to display both text and variables together? Let’s dive into how this works!
➕ Combining Text and Variables
To combine both text and a variable, you use the + character:
String name = "John";System.out.println("Hello " + name);
In this example, "Hello " is a text string, and name is a variable. The + operator joins them together, and the output will be:
Hello John
🔗 Combining Variables
You can also use the + operator to combine variables:
String firstName = "John ";String lastName = "Doe";String fullName = firstName + lastName;System.out.println(fullName);
This will print:
John Doe
➗ Combining Numeric Values
For numeric values, the + character acts as a mathematical operator:
int x = 5;int y = 6;System.out.println(x + y); // This will print the sum of x + y
This will output:
11
🧮 Example Explanation:
x stores 5
y stores 6
When we use the println() method, Java adds x + y, which equals 11.
📝 Java Declare Multiple Variables – How to
Declare More Than One Variable
To declare more than one variable of the same type, you can use a comma-separated list:
Instead of writing:
int x = 5;int y = 6;int z = 50;System.out.println(x + y + z);
You can simply write:
int x = 5, y = 6, z = 50;System.out.println(x + y + z);
✍️ One Value to Multiple Variables
You can also assign the same value to multiple variables in one line:
int x, y, z;x = y = z = 50;System.out.println(x + y + z);
📛 Java Identifiers – Naming Your Variables
In Java, every variable must have a unique name, which is called an identifier.
You can use short names like x and y, or more descriptive names like age, sum, or totalVolume.
✅ Good Naming Practice:
int minutesPerHour = 60;
⚠️ Not So Easy to Understand:
int m = 60;
📝 Rules for Naming Variables:
Names can contain letters, digits, underscores (_), and dollar signs ($).
They must begin with a letter.
Names should start with a lowercase letter.
Reserved words (like Java keywords such as int, boolean, etc.) cannot be used as variable names.
Names are case-sensitive ("myVar" and "myvar" are different variables).
Comments