Printing Variables in Java
Once variables are declared and initialized, you can print their values using the System.out.println()
or System.out.print()
methods.
Key Topics
1. Printing Variables
You can print variables directly by passing them to the print methods.
public class PrintVariables {
public static void main(String[] args) {
int age = 30;
System.out.println(age); // Prints: 30
}
}
2. String Concatenation
You can combine strings and variables using the +
operator.
public class StringConcat {
public static void main(String[] args) {
String name = "Bob";
int age = 25;
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
Output:
Name: Bob
Age: 25
Age: 25
Key Takeaways
- Use
System.out.println()
to print variables to the console. - Combine variables with strings using the
+
operator for concatenation.