Java Print Variables

In this lesson, we’ll explore how to display variables in Java using the println() method. This method is commonly used to output variables. We’ll learn how to combine text and variables, concatenate variables, and use the + character as a mathematical operator with numerical values.

Tutorials dojo strip



Displaying Variables with Text

To display a variable along with text, you can use the + character to concatenate them. Here’s an example:

JAVA

In this example, the name variable, which holds the value “Alice,” is combined with the text “Hello” and displayed using the println() method.




Concatenating Multiple Variables

You can also concatenate multiple variables using the + character. Here’s how you can do it:

JAVA

In this example, the firstName variable (“Alice “) and the lastName variable (“Smith”) are concatenated to form the fullName variable, which is then displayed.




Using the + Character with Numeric Values

When working with numeric values, the + character acts as a mathematical operator. Here’s an example demonstrating this:

JAVA

In this example:

  • The variable a stores the value 10.
  • The variable b stores the value 15.
  • The println() method displays the sum of a and b, which is 25.




Summary

  • Combining Text and Variables: Use the + character to concatenate text and variables.
  • Concatenating Variables: Use the + character to combine multiple variables.
  • Mathematical Operations: The + character can also be used as a mathematical operator with numeric values.
Tutorials dojo strip