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 %s and %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 a String with other values, and Java changes the number to text.
  • %s and %d in String.format() are placeholders for text and whole numbers.

Read Java Variables.


Learn more about the similar topics:
Tutorials
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java User Input with Scanner
Java Math Class
Exercises & Assignments
Print your name and age with variables
Swap two numbers with and without a third variable
Convert Celsius to Fahrenheit
Interview Questions & Answers
What are the primitive data types in Java?
What are autoboxing and unboxing in Java?