Print your name and age with variables
Description: Create a String variable for your name and an int variable for your age. Print the sentence My name is Riya and I am 21 years old. (use your own values).
Hint:
- Join text and variables with
+. - Or use
String.format()with%sand%d.
Solution
public class Main {
public static void main(String[] args) {
String name = "Riya";
int age = 21;
System.out.println("My name is " + name + " and I am " + age + " years old.");
System.out.println(String.format("My name is %s and I am %d years old.", name, age));
}
}
Output
My name is Riya and I am 21 years old.
My name is Riya and I am 21 years old.
How it works
+joins aStringwith other values, and Java changes the number to text.%sand%dinString.format()are placeholders for text and whole numbers.
Read Java Variables.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |