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.



Displaying Variables with Text

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

String name = "Alice";
System.out.println("Hello " + name);

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:

String firstName = "Alice ";
String lastName = "Smith";
String fullName = firstName + lastName;
System.out.println(fullName);

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:

int a = 10;
int b = 15;
System.out.println(a + b); // Prints the value of a + b

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.
Scroll to Top